context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security; using System.Diagnostics; namespace Yort.OnlineEftpos.Net40.Tests { [TestClass] public class IntegrationTests { #region Payment Tests [TestInitializeAttribute] public void InitialiseTests() { if (!System.Net.ServicePointManager.SecurityProtocol.HasFlag(System.Net.SecurityProtocolType.Tls12)) System.Net.ServicePointManager.SecurityProtocol = (System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls12); System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { return true; }; System.Net.ServicePointManager.Expect100Continue = false; System.Net.ServicePointManager.UseNagleAlgorithm = false; } [TestMethod] [TestCategory("Integration")] public async Task Integration_RequestPayment() { var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var orderId = System.Guid.NewGuid().ToString(); var result = await client.RequestPayment(new OnlineEftpos.OnlineEftposPaymentRequest() { Bank = new BankDetails() { BankId = "ASB", PayerIdType = "MOBILE", PayerId = "021555123" }, Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new PaymentDetails() { Amount = 1000, Currency = "NZD", Description = "Test Tran", OrderId = orderId, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(result); Assert.IsTrue(!String.IsNullOrWhiteSpace(result.Id), "Invalid (blank) id returned."); Assert.AreEqual(result.Bank.BankId, "ASB"); Assert.AreEqual(result.Bank.PayerId, "021555123"); Assert.AreEqual(result.Bank.PayerIdType, "MOBILE"); Assert.AreEqual(result.Transaction.Amount, 1000); Assert.AreEqual(result.Transaction.Description, "Test Tran"); Assert.AreEqual(result.Transaction.OrderId, orderId); Assert.AreEqual(result.Merchant.MerchantIdCode, Environment.GetEnvironmentVariable("PaymarkMerchantId")); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. } [TestMethod] [TestCategory("Integration")] public async Task Integration_RequestPayment_WithTrustSetup() { var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var orderId = System.Guid.NewGuid().ToString(); var result = await client.RequestPayment(new OnlineEftpos.OnlineEftposPaymentRequest() { Bank = new BankDetails() { BankId = "ASB", PayerIdType = "MOBILE", PayerId = "021555125" }, Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new PaymentDetails() { Amount = 1000, Currency = "NZD", Description = "Test Tran", OrderId = orderId, TransactionType = OnlineEftposTransactionTypes.TrustSetup, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); try { Assert.IsNotNull(result); Assert.IsTrue(!String.IsNullOrWhiteSpace(result.Id), "Invalid (blank) id returned."); Assert.AreEqual(result.Bank.BankId, "ASB"); Assert.AreEqual(result.Bank.PayerId, "021555125"); Assert.AreEqual(result.Bank.PayerIdType, "MOBILE"); Assert.AreEqual(result.Transaction.Amount, 1000); Assert.AreEqual(result.Transaction.Description, "Test Tran"); Assert.AreEqual(result.Transaction.OrderId, orderId); Assert.AreEqual(result.Transaction.TransactionType, OnlineEftposTransactionTypes.TrustSetup); Assert.IsNotNull(result.Trust.Id); Assert.IsNotNull(result.Trust.Status); Assert.AreEqual(result.Merchant.MerchantIdCode, Environment.GetEnvironmentVariable("PaymarkMerchantId")); } finally { if (!String.IsNullOrEmpty(result?.Trust?.Id)) await DeleteTrustRelationshipAsync(client, result.Trust.Id); } System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. } /// <summary> /// /// </summary> /// <returns></returns> [TestMethod] [TestCategory("Integration")] public async Task Integration_CheckPaymentStatus() { #region Test Setup var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); //Make a payment var paymentId = System.Guid.NewGuid().ToString(); IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var result = await client.RequestPayment(new OnlineEftpos.OnlineEftposPaymentRequest() { Bank = new BankDetails() { BankId = "ASB", PayerIdType = "MOBILE", PayerId = "021555123" }, Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new PaymentDetails() { Amount = 109 * 100, Currency = "NZD", Description = "Test Tran", OrderId = paymentId, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(result); Assert.IsTrue(!String.IsNullOrWhiteSpace(result.Id), "Invalid (blank) id returned."); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. #endregion var statusResult = await client.CheckPaymentStatus(result.Id).ConfigureAwait(false); Assert.AreEqual(paymentId, statusResult.Transaction.OrderId); Assert.AreEqual(109 * 100, statusResult.Transaction.Amount); Assert.AreEqual("NZD", statusResult.Transaction.Currency); Assert.AreEqual("ASB", statusResult.Bank.BankId); Assert.AreEqual("MOBILE", statusResult.Bank.PayerIdType); Assert.AreEqual("021555123", statusResult.Bank.PayerId); Assert.AreEqual(Environment.GetEnvironmentVariable("PaymarkMerchantId"), statusResult.Merchant.MerchantIdCode); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. } [TestMethod] [TestCategory("Integration")] public async Task Integration_CheckPaymentStatusByOrderId() { #region Test Setup var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); //Make a payment var orderId = System.Guid.NewGuid().ToString(); IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var result = await client.RequestPayment(new OnlineEftpos.OnlineEftposPaymentRequest() { Bank = new BankDetails() { BankId = "ASB", PayerIdType = "MOBILE", PayerId = "021555123" }, Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new PaymentDetails() { Amount = 1000, Currency = "NZD", Description = "Test Tran", OrderId = orderId, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(result); Assert.IsTrue(!String.IsNullOrWhiteSpace(result.Id), "Invalid (blank) id returned."); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. #endregion var searchResult = await client.PaymentSearch(new OnlineEftposPaymentSearchOptions() { OrderId = orderId }).ConfigureAwait(false); Assert.IsNotNull(searchResult); Assert.AreEqual(1, searchResult.Payments.Count()); var paymentResult = searchResult.Payments.First(); Assert.IsTrue(!String.IsNullOrWhiteSpace(paymentResult.Id), "Invalid (blank) id returned in search result."); Assert.AreEqual(orderId, paymentResult.Transaction.OrderId); Assert.AreEqual(1000, paymentResult.Transaction.Amount); Assert.AreEqual("NZD", paymentResult.Transaction.Currency); Assert.AreEqual("021555123", paymentResult.Bank.PayerId); Assert.AreEqual(Environment.GetEnvironmentVariable("PaymarkMerchantId"), paymentResult.Merchant.MerchantIdCode); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. } [TestMethod] [TestCategory("Integration")] public async Task Integration_CheckPaymentStatusSearchPagination() { #region Test Setup var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); #endregion IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var searchResult = await client.PaymentSearch(new OnlineEftposPaymentSearchOptions() { MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), Limit = 1 }).ConfigureAwait(false); Assert.IsTrue(searchResult.Payments.Count() > 0, "No payments returned, expected some payments."); Assert.IsFalse(searchResult.Payments.Count() > 1, "Too many payments returned, limit not being applied."); Assert.IsNotNull(searchResult.NextPageUri, "No next page URI returned, expected next page with limit of 1 result per page."); Assert.IsNull(searchResult.PreviousPageUri, "Previous page URI returned, not expected on first search request."); var paymentId = searchResult.Payments.First().Id; searchResult = await client.PaymentSearch(new OnlineEftposPaymentSearchOptions() { PaginationUri = searchResult.NextPageUri }).ConfigureAwait(false); Assert.IsNotNull(searchResult.PreviousPageUri, "Previous page URI not returned, expected on second search request."); Assert.AreNotEqual(paymentId, searchResult.Payments.First().Id, "First and second search request returned same payment."); } [ExpectedException(typeof(OnlineEftposApiException))] [TestMethod] [TestCategory("Integration")] public async Task Integration_CheckPaymentStatus_PaymentDoesNotExist() { #region Test Setup var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); //Make a payment IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); #endregion var paymentId = System.Guid.NewGuid().ToString(); #pragma warning disable IDE0059 // Unnecessary assignment of a value var statusResult = await client.CheckPaymentStatus(paymentId).ConfigureAwait(false); #pragma warning restore IDE0059 // Unnecessary assignment of a value } #endregion #region Refund Tests [TestMethod] [TestCategory("Integration")] public async Task Integration_SendRefund() { #region Test Setup var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var orderId = System.Guid.NewGuid().ToString(); var result = await client.RequestPayment(new OnlineEftpos.OnlineEftposPaymentRequest() { Bank = new BankDetails() { BankId = "ASB", PayerIdType = "MOBILE", PayerId = "021555123" }, Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new PaymentDetails() { Amount = 1000, Currency = "NZD", Description = "Test Tran", OrderId = orderId, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(result); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. var sw = new Stopwatch(); sw.Start(); while (result.Status != PaymentStatus.Authorised && sw.Elapsed.Seconds < 60) { System.Threading.Thread.Sleep(1000); result = await client.CheckPaymentStatus(result.Id).ConfigureAwait(false); } Assert.IsTrue(result.Status == PaymentStatus.Authorised, "Payment wasn't authroised after 1 minute, cannot attempt refund."); #endregion var refundResult = await client.SendRefund(new OnlineEftposRefundRequest() { Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new RefundDetails() { RefundId = System.Guid.NewGuid().ToString(), RefundAmount = 1000, RefundReason = "Test", OriginalPaymentId = result.Id, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(refundResult); Assert.IsTrue(!String.IsNullOrWhiteSpace(refundResult.Id), "Invalid (blank) refund id returned."); Assert.AreEqual(refundResult.Merchant.MerchantIdCode, Environment.GetEnvironmentVariable("PaymarkMerchantId")); Assert.IsTrue(refundResult.Status == RefundStatus.Refunded, "Status is not refunded"); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. } [TestMethod] [TestCategory("Integration")] public async Task Integration_CheckRefundStatus() { #region Test Setup var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var orderId = System.Guid.NewGuid().ToString(); var result = await client.RequestPayment(new OnlineEftpos.OnlineEftposPaymentRequest() { Bank = new BankDetails() { BankId = "ASB", PayerIdType = "MOBILE", PayerId = "021555123" }, Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new PaymentDetails() { Amount = 1000, Currency = "NZD", Description = "Test Tran", OrderId = orderId, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(result); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. var sw = new Stopwatch(); sw.Start(); while (result.Status != PaymentStatus.Authorised && sw.Elapsed.Seconds < 60) { System.Threading.Thread.Sleep(1000); result = await client.CheckPaymentStatus(result.Id).ConfigureAwait(false); } Assert.IsTrue(result.Status == PaymentStatus.Authorised, "Payment wasn't authroised after 1 minute, cannot attempt refund."); var refundResult = await client.SendRefund(new OnlineEftposRefundRequest() { Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new RefundDetails() { RefundId = System.Guid.NewGuid().ToString(), RefundAmount = 1000, RefundReason = "Test", OriginalPaymentId = result.Id, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(refundResult); Assert.IsTrue(!String.IsNullOrWhiteSpace(refundResult.Id), "Invalid (blank) refund id returned."); Assert.AreEqual(refundResult.Merchant.MerchantIdCode, Environment.GetEnvironmentVariable("PaymarkMerchantId")); Assert.IsTrue(refundResult.Status == RefundStatus.Refunded, "Status is not refunded"); var refundId = refundResult.Id; #endregion refundResult = await client.CheckRefundStatus(refundId).ConfigureAwait(false); Assert.IsNotNull(refundResult); Assert.IsTrue(!String.IsNullOrWhiteSpace(refundResult.Id), "Invalid (blank) refund id returned."); Assert.AreEqual(refundResult.Merchant.MerchantIdCode, Environment.GetEnvironmentVariable("PaymarkMerchantId")); Assert.IsTrue(refundResult.Status == RefundStatus.Refunded, "Status is not refunded"); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. } [TestMethod] [TestCategory("Integration")] public async Task Integration_CheckRefundStatusByRefundId() { #region Test Setup var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var orderId = System.Guid.NewGuid().ToString(); var result = await client.RequestPayment(new OnlineEftpos.OnlineEftposPaymentRequest() { Bank = new BankDetails() { BankId = "ASB", PayerIdType = "MOBILE", PayerId = "021555123" }, Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new PaymentDetails() { Amount = 1000, Currency = "NZD", Description = "Test Tran", OrderId = orderId, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(result); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. var sw = new Stopwatch(); sw.Start(); while (result.Status != PaymentStatus.Authorised && sw.Elapsed.Seconds < 60) { System.Threading.Thread.Sleep(1000); result = await client.CheckPaymentStatus(result.Id).ConfigureAwait(false); } Assert.IsTrue(result.Status == PaymentStatus.Authorised, "Payment wasn't authroised after 1 minute, cannot attempt refund."); var refundResult = await client.SendRefund(new OnlineEftposRefundRequest() { Merchant = new MerchantDetails() { CallbackUrl = new Uri(Environment.GetEnvironmentVariable("PaymarkTestCallbackUrl")), MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), MerchantUrl = new Uri("http://www.ontempo.co.nz") }, Transaction = new RefundDetails() { RefundId = System.Guid.NewGuid().ToString(), RefundAmount = 1000, RefundReason = "Test", OriginalPaymentId = result.Id, UserAgent = "Yort.OnlineEftpos.Tests", UserIPAddress = "10.10.10.100" } }).ConfigureAwait(false); Assert.IsNotNull(refundResult); Assert.IsTrue(!String.IsNullOrWhiteSpace(refundResult.Id), "Invalid (blank) refund id returned."); Assert.AreEqual(refundResult.Merchant.MerchantIdCode, Environment.GetEnvironmentVariable("PaymarkMerchantId")); Assert.IsTrue(refundResult.Status == RefundStatus.Refunded, "Status is not refunded"); #endregion var recheckResult = await client.CheckRefundStatus(refundResult.Id).ConfigureAwait(false); Assert.IsNotNull(recheckResult); Assert.IsTrue(!String.IsNullOrWhiteSpace(recheckResult.Id), "Invalid (blank) refund id returned."); Assert.AreEqual(recheckResult.Merchant.MerchantIdCode, Environment.GetEnvironmentVariable("PaymarkMerchantId")); Assert.IsTrue(recheckResult.Status == RefundStatus.Refunded, "Status is not refunded"); System.Threading.Thread.Sleep(10000); // Sandbox environment not designed to cope with more than 1 transaction per 5-10 seconds, // have been asked to ensure we don't overrun the system. } [TestMethod] [TestCategory("Integration")] public async Task Integration_CheckRefundStatusSearchPagination() { #region Test Setup var credProvider = new SecureStringOnlineEftposCredentialProvider( SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatKey")), SecureStringFromString(Environment.GetEnvironmentVariable("PaymarkUatSecret")) ); #endregion IOnlineEftposClient client = new OnlineEftpos.OnlineEftposClient(credProvider, OnlineEftposApiVersion.None, OnlineEftposApiEnvironment.Sandbox); var searchResult = await client.RefundSearch(new OnlineEftposRefundSearchOptions() { MerchantIdCode = Environment.GetEnvironmentVariable("PaymarkMerchantId"), Limit = 1 }).ConfigureAwait(false); Assert.IsTrue(searchResult.Refunds.Count() > 0, "No refunds returned, expected some payments."); Assert.IsFalse(searchResult.Refunds.Count() > 1, "Too many refunds returned, limit not being applied."); Assert.IsNotNull(searchResult.NextPageUri, "No next page URI returned, expected next page with limit of 1 result per page."); Assert.IsNull(searchResult.PreviousPageUri, "Previous page URI returned, not expected on first search request."); var paymentId = searchResult.Refunds.First().Id; searchResult = await client.RefundSearch(new OnlineEftposRefundSearchOptions() { PaginationUri = searchResult.NextPageUri }).ConfigureAwait(false); Assert.IsNotNull(searchResult.PreviousPageUri, "Previous page URI not returned, expected on second search request."); Assert.AreNotEqual(paymentId, searchResult.Refunds.First().Id, "First and second search request returned same payment."); } #endregion private async Task DeleteTrustRelationshipAsync(IOnlineEftposClient client, string id) { try { var result = await client.DeleteTrust(new OnlineEftposDeleteTrustOptions() { TrustId = id }); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Failed to remove test trust relationship: " + ex.ToString()); } } private SecureString SecureStringFromString(string sourceText) { var retVal = new SecureString(); if (sourceText == null) return retVal; foreach (var c in sourceText) { retVal.AppendChar(c); } return retVal; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using NuGet.Packaging; using osu.Framework.Audio.Track; using osu.Framework.Extensions; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Textures; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Formats; using osu.Game.Database; using osu.Game.IO; using osu.Game.IO.Archives; using osu.Game.Models; using osu.Game.Rulesets; using osu.Game.Rulesets.Objects; using osu.Game.Skinning; using Realms; #nullable enable namespace osu.Game.Stores { /// <summary> /// Handles the storage and retrieval of Beatmaps/WorkingBeatmaps. /// </summary> [ExcludeFromDynamicCompile] public class BeatmapImporter : RealmArchiveModelImporter<RealmBeatmapSet>, IDisposable { public override IEnumerable<string> HandledExtensions => new[] { ".osz" }; protected override string[] HashableFileTypes => new[] { ".osu" }; // protected override bool CheckLocalAvailability(RealmBeatmapSet model, System.Linq.IQueryable<RealmBeatmapSet> items) // => base.CheckLocalAvailability(model, items) || (model.OnlineID > -1)); private readonly BeatmapOnlineLookupQueue? onlineLookupQueue; public BeatmapImporter(RealmContextFactory contextFactory, Storage storage, BeatmapOnlineLookupQueue? onlineLookupQueue = null) : base(storage, contextFactory) { this.onlineLookupQueue = onlineLookupQueue; } protected override bool ShouldDeleteArchive(string path) => Path.GetExtension(path).ToLowerInvariant() == ".osz"; protected override Task Populate(RealmBeatmapSet beatmapSet, ArchiveReader? archive, Realm realm, CancellationToken cancellationToken = default) { if (archive != null) beatmapSet.Beatmaps.AddRange(createBeatmapDifficulties(beatmapSet.Files, realm)); foreach (RealmBeatmap b in beatmapSet.Beatmaps) b.BeatmapSet = beatmapSet; validateOnlineIds(beatmapSet, realm); bool hadOnlineBeatmapIDs = beatmapSet.Beatmaps.Any(b => b.OnlineID > 0); if (onlineLookupQueue != null) { // TODO: this required `BeatmapOnlineLookupQueue` to somehow support new types. // await onlineLookupQueue.UpdateAsync(beatmapSet, cancellationToken).ConfigureAwait(false); } // ensure at least one beatmap was able to retrieve or keep an online ID, else drop the set ID. if (hadOnlineBeatmapIDs && !beatmapSet.Beatmaps.Any(b => b.OnlineID > 0)) { if (beatmapSet.OnlineID > 0) { beatmapSet.OnlineID = -1; LogForModel(beatmapSet, "Disassociating beatmap set ID due to loss of all beatmap IDs"); } } return Task.CompletedTask; } protected override void PreImport(RealmBeatmapSet beatmapSet, Realm realm) { // We are about to import a new beatmap. Before doing so, ensure that no other set shares the online IDs used by the new one. // Note that this means if the previous beatmap is restored by the user, it will no longer be linked to its online IDs. // If this is ever an issue, we can consider marking as pending delete but not resetting the IDs (but care will be required for // beatmaps, which don't have their own `DeletePending` state). if (beatmapSet.OnlineID > 0) { var existingSetWithSameOnlineID = realm.All<RealmBeatmapSet>().SingleOrDefault(b => b.OnlineID == beatmapSet.OnlineID); if (existingSetWithSameOnlineID != null) { existingSetWithSameOnlineID.DeletePending = true; existingSetWithSameOnlineID.OnlineID = -1; foreach (var b in existingSetWithSameOnlineID.Beatmaps) b.OnlineID = -1; LogForModel(beatmapSet, $"Found existing beatmap set with same OnlineID ({beatmapSet.OnlineID}). It will be deleted."); } } } private void validateOnlineIds(RealmBeatmapSet beatmapSet, Realm realm) { var beatmapIds = beatmapSet.Beatmaps.Where(b => b.OnlineID > 0).Select(b => b.OnlineID).ToList(); // ensure all IDs are unique if (beatmapIds.GroupBy(b => b).Any(g => g.Count() > 1)) { LogForModel(beatmapSet, "Found non-unique IDs, resetting..."); resetIds(); return; } // find any existing beatmaps in the database that have matching online ids List<RealmBeatmap> existingBeatmaps = new List<RealmBeatmap>(); foreach (var id in beatmapIds) existingBeatmaps.AddRange(realm.All<RealmBeatmap>().Where(b => b.OnlineID == id)); if (existingBeatmaps.Any()) { // reset the import ids (to force a re-fetch) *unless* they match the candidate CheckForExisting set. // we can ignore the case where the new ids are contained by the CheckForExisting set as it will either be used (import skipped) or deleted. var existing = CheckForExisting(beatmapSet, realm); if (existing == null || existingBeatmaps.Any(b => !existing.Beatmaps.Contains(b))) { LogForModel(beatmapSet, "Found existing import with online IDs already, resetting..."); resetIds(); } } void resetIds() => beatmapSet.Beatmaps.ForEach(b => b.OnlineID = -1); } protected override bool CanSkipImport(RealmBeatmapSet existing, RealmBeatmapSet import) { if (!base.CanSkipImport(existing, import)) return false; return existing.Beatmaps.Any(b => b.OnlineID > 0); } protected override bool CanReuseExisting(RealmBeatmapSet existing, RealmBeatmapSet import) { if (!base.CanReuseExisting(existing, import)) return false; var existingIds = existing.Beatmaps.Select(b => b.OnlineID).OrderBy(i => i); var importIds = import.Beatmaps.Select(b => b.OnlineID).OrderBy(i => i); // force re-import if we are not in a sane state. return existing.OnlineID == import.OnlineID && existingIds.SequenceEqual(importIds); } public override string HumanisedModelName => "beatmap"; protected override RealmBeatmapSet? CreateModel(ArchiveReader reader) { // let's make sure there are actually .osu files to import. string? mapName = reader.Filenames.FirstOrDefault(f => f.EndsWith(".osu", StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(mapName)) { Logger.Log($"No beatmap files found in the beatmap archive ({reader.Name}).", LoggingTarget.Database); return null; } Beatmap beatmap; using (var stream = new LineBufferedReader(reader.GetStream(mapName))) beatmap = Decoder.GetDecoder<Beatmap>(stream).Decode(stream); return new RealmBeatmapSet { OnlineID = beatmap.BeatmapInfo.BeatmapSet?.OnlineBeatmapSetID ?? -1, // Metadata = beatmap.Metadata, DateAdded = DateTimeOffset.UtcNow }; } /// <summary> /// Create all required <see cref="RealmBeatmap"/>s for the provided archive. /// </summary> private List<RealmBeatmap> createBeatmapDifficulties(IList<RealmNamedFileUsage> files, Realm realm) { var beatmaps = new List<RealmBeatmap>(); foreach (var file in files.Where(f => f.Filename.EndsWith(".osu", StringComparison.OrdinalIgnoreCase))) { using (var memoryStream = new MemoryStream(Files.Store.Get(file.File.StoragePath))) // we need a memory stream so we can seek { IBeatmap decoded; using (var lineReader = new LineBufferedReader(memoryStream, true)) decoded = Decoder.GetDecoder<Beatmap>(lineReader).Decode(lineReader); string hash = memoryStream.ComputeSHA2Hash(); if (beatmaps.Any(b => b.Hash == hash)) { Logger.Log($"Skipping import of {file.Filename} due to duplicate file content.", LoggingTarget.Database); continue; } var decodedInfo = decoded.BeatmapInfo; var decodedDifficulty = decodedInfo.BaseDifficulty; var ruleset = realm.All<RealmRuleset>().FirstOrDefault(r => r.OnlineID == decodedInfo.RulesetID); if (ruleset?.Available != true) { Logger.Log($"Skipping import of {file.Filename} due to missing local ruleset {decodedInfo.RulesetID}.", LoggingTarget.Database); continue; } var difficulty = new RealmBeatmapDifficulty { DrainRate = decodedDifficulty.DrainRate, CircleSize = decodedDifficulty.CircleSize, OverallDifficulty = decodedDifficulty.OverallDifficulty, ApproachRate = decodedDifficulty.ApproachRate, SliderMultiplier = decodedDifficulty.SliderMultiplier, SliderTickRate = decodedDifficulty.SliderTickRate, }; var metadata = new RealmBeatmapMetadata { Title = decoded.Metadata.Title, TitleUnicode = decoded.Metadata.TitleUnicode, Artist = decoded.Metadata.Artist, ArtistUnicode = decoded.Metadata.ArtistUnicode, Author = decoded.Metadata.AuthorString, Source = decoded.Metadata.Source, Tags = decoded.Metadata.Tags, PreviewTime = decoded.Metadata.PreviewTime, AudioFile = decoded.Metadata.AudioFile, BackgroundFile = decoded.Metadata.BackgroundFile, }; var beatmap = new RealmBeatmap(ruleset, difficulty, metadata) { Hash = hash, DifficultyName = decodedInfo.Version, OnlineID = decodedInfo.OnlineBeatmapID ?? -1, AudioLeadIn = decodedInfo.AudioLeadIn, StackLeniency = decodedInfo.StackLeniency, SpecialStyle = decodedInfo.SpecialStyle, LetterboxInBreaks = decodedInfo.LetterboxInBreaks, WidescreenStoryboard = decodedInfo.WidescreenStoryboard, EpilepsyWarning = decodedInfo.EpilepsyWarning, SamplesMatchPlaybackRate = decodedInfo.SamplesMatchPlaybackRate, DistanceSpacing = decodedInfo.DistanceSpacing, BeatDivisor = decodedInfo.BeatDivisor, GridSize = decodedInfo.GridSize, TimelineZoom = decodedInfo.TimelineZoom, MD5Hash = memoryStream.ComputeMD5Hash(), }; updateBeatmapStatistics(beatmap, decoded); beatmaps.Add(beatmap); } } return beatmaps; } private void updateBeatmapStatistics(RealmBeatmap beatmap, IBeatmap decoded) { var rulesetInstance = ((IRulesetInfo)beatmap.Ruleset).CreateInstance(); if (rulesetInstance == null) return; decoded.BeatmapInfo.Ruleset = rulesetInstance.RulesetInfo; // TODO: this should be done in a better place once we actually need to dynamically update it. beatmap.StarRating = rulesetInstance.CreateDifficultyCalculator(new DummyConversionBeatmap(decoded)).Calculate().StarRating; beatmap.Length = calculateLength(decoded); beatmap.BPM = 60000 / decoded.GetMostCommonBeatLength(); } private double calculateLength(IBeatmap b) { if (!b.HitObjects.Any()) return 0; var lastObject = b.HitObjects.Last(); //TODO: this isn't always correct (consider mania where a non-last object may last for longer than the last in the list). double endTime = lastObject.GetEndTime(); double startTime = b.HitObjects.First().StartTime; return endTime - startTime; } public void Dispose() { onlineLookupQueue?.Dispose(); } /// <summary> /// A dummy WorkingBeatmap for the purpose of retrieving a beatmap for star difficulty calculation. /// </summary> private class DummyConversionBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; public DummyConversionBeatmap(IBeatmap beatmap) : base(beatmap.BeatmapInfo, null) { this.beatmap = beatmap; } protected override IBeatmap GetBeatmap() => beatmap; protected override Texture? GetBackground() => null; protected override Track? GetBeatmapTrack() => null; protected internal override ISkin? GetSkin() => null; public override Stream? GetStream(string storagePath) => null; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using Firebase.Firestore; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Tests { public class FirestoreAssertionFailure : Exception { public FirestoreAssertionFailure(string message) : base(message) {} } public static class TestAsserts { public static IEnumerator AwaitCompletion(Task t) { yield return new WaitUntil((() => t.IsCompleted)); } public static IEnumerator AwaitSuccess(Task t) { yield return AwaitCompletion(t); AssertTaskSucceeded(t); } public static IEnumerator AwaitFaults(Task t) { yield return AwaitCompletion(t); AssertTaskFaulted(t); } private static void AssertTaskProperties(Task t, bool isCompleted, bool isFaulted, bool isCanceled) { Assert.That(t.IsCompleted, Is.EqualTo(isCompleted)); Assert.That(t.IsFaulted, Is.EqualTo(isFaulted)); Assert.That(t.IsCanceled, Is.EqualTo(isCanceled)); } public static void AssertTaskSucceeded(Task t) { AssertTaskProperties(t, isCompleted: true, isFaulted: false, isCanceled: false); } public static void AssertTaskIsPending(Task t) { AssertTaskProperties(t, isCompleted: false, isFaulted: false, isCanceled: false); } public static Exception AssertTaskFaulted(Task t) { Assert.That(t.Exception, Is.Not.Null, "Task is supposed to fail with exception, yet it succeeds."); AggregateException e = t.Exception; Assert.That(e.InnerExceptions.Count, Is.EqualTo(1), "Task faulted with multiple exceptions"); AssertTaskProperties(t, isCompleted: true, isFaulted: true, isCanceled: false); return e.InnerExceptions[0]; } public static FirestoreException AssertTaskFaulted(Task t, FirestoreError expectedError, string expectedMessageRegex = null) { var exception = AssertTaskFaulted(t); Assert.That( exception, Is.TypeOf<FirestoreException>(), "The task faulted (as expected); however, its exception was expected to " + $"be FirestoreException with ErrorCode={expectedError} but the actual exception " + $"was {exception.GetType()}: {exception}"); var firestoreException = (FirestoreException)exception; Assert.That(firestoreException.ErrorCode, Is.EqualTo(expectedError), "The task faulted with FirestoreException (as expected); however, its " + $"ErrorCode was expected to be {expectedError} but the actual ErrorCode was" + $" {firestoreException.ErrorCode}: {firestoreException}"); if (expectedMessageRegex != null) { Assert.That(Regex.IsMatch(firestoreException.Message, expectedMessageRegex, RegexOptions.Singleline), $"The task faulted with FirestoreException with ErrorCode={expectedError} " + "(as expected); however, its message did not match the regular " + $"expression {expectedMessageRegex}: {firestoreException.Message}"); } return firestoreException; } public static async Task AssertExpectedDocument(DocumentReference doc, Dictionary<string, object> expected) { var snap = await doc.GetSnapshotAsync(); Assert.That(snap.ToDictionary(), Is.EquivalentTo(expected)); } } // Tests for `TestAsserts` itself. public class TestAssertsTests { [UnityTest] public IEnumerator AssertTaskFaulted_ShouldWork_WithFirestoreException() { var tcs = new TaskCompletionSource<object>(); tcs.SetException(new FirestoreException(FirestoreError.Unavailable)); yield return tcs.Task; Assert.That(() => { TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Unavailable); }, Throws.Nothing); } [UnityTest] public IEnumerator AssertTaskFaulted_ShouldWork_WithMatchingMessage() { var tcs = new TaskCompletionSource<object>(); tcs.SetException(new FirestoreException(FirestoreError.Ok, "TheActualMessage")); yield return tcs.Task; Assert.That(() => { TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Ok, "The.*Message"); }, Throws.Nothing); } // Verify that AssertTaskFaults() fails if the Task faults with an AggregateException that, // when flattened, resolves to a FirestoreException with the expected error code. [UnityTest] public IEnumerator AssertTaskFaulted_ShouldThrow_IfFaultedWithAggregateException() { var tcs = new TaskCompletionSource<object>(); var firestoreException = new FirestoreException(FirestoreError.Unavailable); var aggregateException1 = new AggregateException(new[] { firestoreException }); var aggregateException2 = new AggregateException(new[] { aggregateException1 }); tcs.SetException(aggregateException2); yield return tcs.Task; Assert.That( () => { TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Unavailable); }, Throws.Exception, "AssertTaskFaults() should have thrown an exception because the AggregateException" + "has multiple nested AggregateException instances."); } [UnityTest] public IEnumerator AssertTaskFaulted_ShouldThrow_IfFaultedWithUnexpectedErrorCode() { var tcs = new TaskCompletionSource<object>(); tcs.SetResult(new FirestoreException(FirestoreError.Unavailable)); yield return tcs.Task; Assert.That(() => { TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Ok); }, Throws.Exception, "AssertTaskFaults() should have thrown an exception because the task faulted " + "with an incorrect error code."); } [UnityTest] public IEnumerator AssertTaskFaulted_ShouldThrow_WhenTaskCompletes() { var tcs = new TaskCompletionSource<object>(); tcs.SetResult(null); yield return tcs.Task; Assert.That(() => { TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Ok); }, Throws.Exception, "AssertTaskFaults() should have thrown an exception because the task faulted " + "with an incorrect error code."); } [UnityTest] public IEnumerator AssertTaskFaulted_ShouldThrow_IfFaultedWithNonFirestoreException() { var tcs = new TaskCompletionSource<object>(); tcs.SetException(new InvalidOperationException()); yield return tcs.Task; Assert.That(() => { TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Ok); }, Throws.Exception, "AssertTaskFaults() should have thrown an exception because the task faulted " + "with an incorrect exception type."); } [UnityTest] public IEnumerator AssertTaskFaulted_ShouldThrow_IfFaultedWithUnexpectedAggregateException() { var tcs = new TaskCompletionSource<object>(); var exception1 = new InvalidOperationException(); var exception2 = new AggregateException(new[] { exception1 }); var exception3 = new AggregateException(new[] { exception2 }); tcs.SetException(exception3); yield return tcs.Task; Assert.That(() => { TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Ok); }, Throws.Exception, "AssertTaskFaults() should have thrown an exception because the task faulted " + "with an AggregateException that flattened to an unexpected exception."); } [UnityTest] public IEnumerator AssertTaskFaulted_ShouldThrow_IfFaultedWithMoreThanOneInnerExceptions() { var tcs = new TaskCompletionSource<object>(); var exception1 = new InvalidOperationException(); var exception2 = new InvalidOperationException(); var exception3 = new AggregateException(new[] { exception1, exception2 }); tcs.SetException(exception3); yield return tcs.Task; Assert.That(() => { TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Ok); }, Throws.Exception, "AssertTaskFaults() should have thrown an exception because the task faulted " + "with an AggregateException that could not be fully flattened."); } [UnityTest] public IEnumerator AssertTaskFaulted_ShouldThrow_IfFaultedWithMissingMessages() { var tcs = new TaskCompletionSource<object>(); tcs.SetException(new FirestoreException(FirestoreError.Ok)); yield return tcs.Task; Exception thrownException = Assert.Throws<AssertionException>( () => TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Ok, "SomeMessageRegex")); Assert.That(thrownException.Message, Contains.Substring("SomeMessageRegex"), "AssertTaskFaults() threw an exception (as expected); however, its message was " + "incorrect: " + thrownException.Message); } [UnityTest] public IEnumerator AssertTaskFaulted_ShouldThrow_IfFaultedWithMismatchMessages() { var tcs = new TaskCompletionSource<object>(); tcs.SetException(new FirestoreException(FirestoreError.Ok, "TheActualMessage")); yield return tcs.Task; Exception thrownException = Assert.Throws<AssertionException>( () => TestAsserts.AssertTaskFaulted(tcs.Task, FirestoreError.Ok, "The.*MeaningOfLife")); Assert.That(thrownException.Message, Contains.Substring("TheActualMessage")); Assert.That(thrownException.Message, Contains.Substring("The.*MeaningOfLife"), "AssertTaskFaults() threw an exception (as expected); however, its message was " + thrownException.Message); } } }
// 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.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Open API 2.0 Specs for Azure RecoveryServices Backup service /// </summary> public partial class RecoveryServicesBackupClient : ServiceClient<RecoveryServicesBackupClient>, IRecoveryServicesBackupClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The subscription Id. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IBackupResourceVaultConfigsOperations. /// </summary> public virtual IBackupResourceVaultConfigsOperations BackupResourceVaultConfigs { get; private set; } /// <summary> /// Gets the IBackupEnginesOperations. /// </summary> public virtual IBackupEnginesOperations BackupEngines { get; private set; } /// <summary> /// Gets the IProtectionContainerRefreshOperationResultsOperations. /// </summary> public virtual IProtectionContainerRefreshOperationResultsOperations ProtectionContainerRefreshOperationResults { get; private set; } /// <summary> /// Gets the IProtectionContainersOperations. /// </summary> public virtual IProtectionContainersOperations ProtectionContainers { get; private set; } /// <summary> /// Gets the IProtectionContainerOperationResultsOperations. /// </summary> public virtual IProtectionContainerOperationResultsOperations ProtectionContainerOperationResults { get; private set; } /// <summary> /// Gets the IProtectedItemsOperations. /// </summary> public virtual IProtectedItemsOperations ProtectedItems { get; private set; } /// <summary> /// Gets the IBackupsOperations. /// </summary> public virtual IBackupsOperations Backups { get; private set; } /// <summary> /// Gets the IProtectedItemOperationResultsOperations. /// </summary> public virtual IProtectedItemOperationResultsOperations ProtectedItemOperationResults { get; private set; } /// <summary> /// Gets the IProtectedItemOperationStatusesOperations. /// </summary> public virtual IProtectedItemOperationStatusesOperations ProtectedItemOperationStatuses { get; private set; } /// <summary> /// Gets the IRecoveryPointsOperations. /// </summary> public virtual IRecoveryPointsOperations RecoveryPoints { get; private set; } /// <summary> /// Gets the IItemLevelRecoveryConnectionsOperations. /// </summary> public virtual IItemLevelRecoveryConnectionsOperations ItemLevelRecoveryConnections { get; private set; } /// <summary> /// Gets the IRestoresOperations. /// </summary> public virtual IRestoresOperations Restores { get; private set; } /// <summary> /// Gets the IBackupJobsOperations. /// </summary> public virtual IBackupJobsOperations BackupJobs { get; private set; } /// <summary> /// Gets the IJobDetailsOperations. /// </summary> public virtual IJobDetailsOperations JobDetails { get; private set; } /// <summary> /// Gets the IJobCancellationsOperations. /// </summary> public virtual IJobCancellationsOperations JobCancellations { get; private set; } /// <summary> /// Gets the IJobOperationResultsOperations. /// </summary> public virtual IJobOperationResultsOperations JobOperationResults { get; private set; } /// <summary> /// Gets the IExportJobsOperationResultsOperations. /// </summary> public virtual IExportJobsOperationResultsOperations ExportJobsOperationResults { get; private set; } /// <summary> /// Gets the IJobsOperations. /// </summary> public virtual IJobsOperations Jobs { get; private set; } /// <summary> /// Gets the IBackupOperationResultsOperations. /// </summary> public virtual IBackupOperationResultsOperations BackupOperationResults { get; private set; } /// <summary> /// Gets the IBackupOperationStatusesOperations. /// </summary> public virtual IBackupOperationStatusesOperations BackupOperationStatuses { get; private set; } /// <summary> /// Gets the IBackupPoliciesOperations. /// </summary> public virtual IBackupPoliciesOperations BackupPolicies { get; private set; } /// <summary> /// Gets the IProtectionPoliciesOperations. /// </summary> public virtual IProtectionPoliciesOperations ProtectionPolicies { get; private set; } /// <summary> /// Gets the IProtectionPolicyOperationResultsOperations. /// </summary> public virtual IProtectionPolicyOperationResultsOperations ProtectionPolicyOperationResults { get; private set; } /// <summary> /// Gets the IProtectionPolicyOperationStatusesOperations. /// </summary> public virtual IProtectionPolicyOperationStatusesOperations ProtectionPolicyOperationStatuses { get; private set; } /// <summary> /// Gets the IBackupProtectableItemsOperations. /// </summary> public virtual IBackupProtectableItemsOperations BackupProtectableItems { get; private set; } /// <summary> /// Gets the IBackupProtectedItemsOperations. /// </summary> public virtual IBackupProtectedItemsOperations BackupProtectedItems { get; private set; } /// <summary> /// Gets the IBackupProtectionContainersOperations. /// </summary> public virtual IBackupProtectionContainersOperations BackupProtectionContainers { get; private set; } /// <summary> /// Gets the ISecurityPINsOperations. /// </summary> public virtual ISecurityPINsOperations SecurityPINs { get; private set; } /// <summary> /// Gets the IBackupResourceStorageConfigsOperations. /// </summary> public virtual IBackupResourceStorageConfigsOperations BackupResourceStorageConfigs { get; private set; } /// <summary> /// Gets the IBackupUsageSummariesOperations. /// </summary> public virtual IBackupUsageSummariesOperations BackupUsageSummaries { get; private set; } /// <summary> /// Gets the IOperations. /// </summary> public virtual IOperations Operations { get; private set; } /// <summary> /// Initializes a new instance of the RecoveryServicesBackupClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected RecoveryServicesBackupClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the RecoveryServicesBackupClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected RecoveryServicesBackupClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the RecoveryServicesBackupClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected RecoveryServicesBackupClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the RecoveryServicesBackupClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected RecoveryServicesBackupClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the RecoveryServicesBackupClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public RecoveryServicesBackupClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the RecoveryServicesBackupClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public RecoveryServicesBackupClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the RecoveryServicesBackupClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public RecoveryServicesBackupClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the RecoveryServicesBackupClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public RecoveryServicesBackupClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { BackupResourceVaultConfigs = new BackupResourceVaultConfigsOperations(this); BackupEngines = new BackupEnginesOperations(this); ProtectionContainerRefreshOperationResults = new ProtectionContainerRefreshOperationResultsOperations(this); ProtectionContainers = new ProtectionContainersOperations(this); ProtectionContainerOperationResults = new ProtectionContainerOperationResultsOperations(this); ProtectedItems = new ProtectedItemsOperations(this); Backups = new BackupsOperations(this); ProtectedItemOperationResults = new ProtectedItemOperationResultsOperations(this); ProtectedItemOperationStatuses = new ProtectedItemOperationStatusesOperations(this); RecoveryPoints = new RecoveryPointsOperations(this); ItemLevelRecoveryConnections = new ItemLevelRecoveryConnectionsOperations(this); Restores = new RestoresOperations(this); BackupJobs = new BackupJobsOperations(this); JobDetails = new JobDetailsOperations(this); JobCancellations = new JobCancellationsOperations(this); JobOperationResults = new JobOperationResultsOperations(this); ExportJobsOperationResults = new ExportJobsOperationResultsOperations(this); Jobs = new JobsOperations(this); BackupOperationResults = new BackupOperationResultsOperations(this); BackupOperationStatuses = new BackupOperationStatusesOperations(this); BackupPolicies = new BackupPoliciesOperations(this); ProtectionPolicies = new ProtectionPoliciesOperations(this); ProtectionPolicyOperationResults = new ProtectionPolicyOperationResultsOperations(this); ProtectionPolicyOperationStatuses = new ProtectionPolicyOperationStatusesOperations(this); BackupProtectableItems = new BackupProtectableItemsOperations(this); BackupProtectedItems = new BackupProtectedItemsOperations(this); BackupProtectionContainers = new BackupProtectionContainersOperations(this); SecurityPINs = new SecurityPINsOperations(this); BackupResourceStorageConfigs = new BackupResourceStorageConfigsOperations(this); BackupUsageSummaries = new BackupUsageSummariesOperations(this); Operations = new Operations(this); BaseUri = new System.Uri("https://management.azure.com"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<SchedulePolicy>("schedulePolicyType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<SchedulePolicy>("schedulePolicyType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RetentionPolicy>("retentionPolicyType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RetentionPolicy>("retentionPolicyType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<BackupEngineBase>("backupEngineType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<BackupEngineBase>("backupEngineType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<BackupRequest>("objectType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<BackupRequest>("objectType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ILRRequest>("objectType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ILRRequest>("objectType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Job>("jobType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Job>("jobType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<OperationResultInfoBase>("objectType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<OperationResultInfoBase>("objectType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<OperationStatusExtendedInfo>("objectType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<OperationStatusExtendedInfo>("objectType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ProtectedItem>("protectedItemType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ProtectedItem>("protectedItemType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ProtectionContainer>("protectableObjectType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ProtectionContainer>("protectableObjectType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ProtectionPolicy>("backupManagementType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ProtectionPolicy>("backupManagementType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RecoveryPoint>("objectType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RecoveryPoint>("objectType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RestoreRequest>("objectType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RestoreRequest>("objectType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<WorkloadProtectableItem>("protectableItemType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<WorkloadProtectableItem>("protectableItemType")); CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="GeographicViewServiceClient"/> instances.</summary> public sealed partial class GeographicViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="GeographicViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="GeographicViewServiceSettings"/>.</returns> public static GeographicViewServiceSettings GetDefault() => new GeographicViewServiceSettings(); /// <summary> /// Constructs a new <see cref="GeographicViewServiceSettings"/> object with default settings. /// </summary> public GeographicViewServiceSettings() { } private GeographicViewServiceSettings(GeographicViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetGeographicViewSettings = existing.GetGeographicViewSettings; OnCopy(existing); } partial void OnCopy(GeographicViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>GeographicViewServiceClient.GetGeographicView</c> and /// <c>GeographicViewServiceClient.GetGeographicViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetGeographicViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="GeographicViewServiceSettings"/> object.</returns> public GeographicViewServiceSettings Clone() => new GeographicViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="GeographicViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class GeographicViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<GeographicViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public GeographicViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public GeographicViewServiceClientBuilder() { UseJwtAccessWithScopes = GeographicViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref GeographicViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<GeographicViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override GeographicViewServiceClient Build() { GeographicViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<GeographicViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<GeographicViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private GeographicViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return GeographicViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<GeographicViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return GeographicViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => GeographicViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => GeographicViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => GeographicViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>GeographicViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage geographic views. /// </remarks> public abstract partial class GeographicViewServiceClient { /// <summary> /// The default endpoint for the GeographicViewService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default GeographicViewService scopes.</summary> /// <remarks> /// The default GeographicViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="GeographicViewServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="GeographicViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="GeographicViewServiceClient"/>.</returns> public static stt::Task<GeographicViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new GeographicViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="GeographicViewServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="GeographicViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="GeographicViewServiceClient"/>.</returns> public static GeographicViewServiceClient Create() => new GeographicViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="GeographicViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="GeographicViewServiceSettings"/>.</param> /// <returns>The created <see cref="GeographicViewServiceClient"/>.</returns> internal static GeographicViewServiceClient Create(grpccore::CallInvoker callInvoker, GeographicViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } GeographicViewService.GeographicViewServiceClient grpcClient = new GeographicViewService.GeographicViewServiceClient(callInvoker); return new GeographicViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC GeographicViewService client</summary> public virtual GeographicViewService.GeographicViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GeographicView GetGeographicView(GetGeographicViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(GetGeographicViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(GetGeographicViewRequest request, st::CancellationToken cancellationToken) => GetGeographicViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GeographicView GetGeographicView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetGeographicView(new GetGeographicViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetGeographicViewAsync(new GetGeographicViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetGeographicViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GeographicView GetGeographicView(gagvr::GeographicViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetGeographicView(new GetGeographicViewRequest { ResourceNameAsGeographicViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(gagvr::GeographicViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetGeographicViewAsync(new GetGeographicViewRequest { ResourceNameAsGeographicViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(gagvr::GeographicViewName resourceName, st::CancellationToken cancellationToken) => GetGeographicViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>GeographicViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage geographic views. /// </remarks> public sealed partial class GeographicViewServiceClientImpl : GeographicViewServiceClient { private readonly gaxgrpc::ApiCall<GetGeographicViewRequest, gagvr::GeographicView> _callGetGeographicView; /// <summary> /// Constructs a client wrapper for the GeographicViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="GeographicViewServiceSettings"/> used within this client.</param> public GeographicViewServiceClientImpl(GeographicViewService.GeographicViewServiceClient grpcClient, GeographicViewServiceSettings settings) { GrpcClient = grpcClient; GeographicViewServiceSettings effectiveSettings = settings ?? GeographicViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetGeographicView = clientHelper.BuildApiCall<GetGeographicViewRequest, gagvr::GeographicView>(grpcClient.GetGeographicViewAsync, grpcClient.GetGeographicView, effectiveSettings.GetGeographicViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetGeographicView); Modify_GetGeographicViewApiCall(ref _callGetGeographicView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetGeographicViewApiCall(ref gaxgrpc::ApiCall<GetGeographicViewRequest, gagvr::GeographicView> call); partial void OnConstruction(GeographicViewService.GeographicViewServiceClient grpcClient, GeographicViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC GeographicViewService client</summary> public override GeographicViewService.GeographicViewServiceClient GrpcClient { get; } partial void Modify_GetGeographicViewRequest(ref GetGeographicViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::GeographicView GetGeographicView(GetGeographicViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetGeographicViewRequest(ref request, ref callSettings); return _callGetGeographicView.Sync(request, callSettings); } /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::GeographicView> GetGeographicViewAsync(GetGeographicViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetGeographicViewRequest(ref request, ref callSettings); return _callGetGeographicView.Async(request, callSettings); } } }
/* * 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.Net.Sockets; using System.Net; using System.Net.NetworkInformation; using System.Reflection; using log4net; namespace OpenSim.Framework { /// <summary> /// Handles NAT translation in a 'manner of speaking' /// Allows you to return multiple different external /// hostnames depending on the requestors network /// /// This enables standard port forwarding techniques /// to work correctly with OpenSim. /// </summary> public static class NetworkUtil { // Logger private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static bool m_disabled = true; public static bool Enabled { set { m_disabled = value; } get { return m_disabled; } } // IPv4Address, Subnet static readonly Dictionary<IPAddress,IPAddress> m_subnets = new Dictionary<IPAddress, IPAddress>(); public static IPAddress GetIPFor(IPAddress user, IPAddress simulator) { if (m_disabled) return simulator; // Check if we're accessing localhost. foreach (IPAddress host in Dns.GetHostAddresses(Dns.GetHostName())) { if (host.Equals(user) && host.AddressFamily == AddressFamily.InterNetwork) { m_log.Info("[NetworkUtil] Localhost user detected, sending them '" + host + "' instead of '" + simulator + "'"); return host; } } // Check for same LAN segment foreach (KeyValuePair<IPAddress, IPAddress> subnet in m_subnets) { byte[] subnetBytes = subnet.Value.GetAddressBytes(); byte[] localBytes = subnet.Key.GetAddressBytes(); byte[] destBytes = user.GetAddressBytes(); if (subnetBytes.Length != destBytes.Length || subnetBytes.Length != localBytes.Length) return null; bool valid = true; for (int i = 0; i < subnetBytes.Length; i++) { if ((localBytes[i] & subnetBytes[i]) != (destBytes[i] & subnetBytes[i])) { valid = false; break; } } if (subnet.Key.AddressFamily != AddressFamily.InterNetwork) valid = false; if (valid) { m_log.Info("[NetworkUtil] Local LAN user detected, sending them '" + subnet.Key + "' instead of '" + simulator + "'"); return subnet.Key; } } // Otherwise, return outside address return simulator; } private static IPAddress GetExternalIPFor(IPAddress destination, string defaultHostname) { // Adds IPv6 Support (Not that any of the major protocols supports it...) if (destination.AddressFamily == AddressFamily.InterNetworkV6) { foreach (IPAddress host in Dns.GetHostAddresses(defaultHostname)) { if (host.AddressFamily == AddressFamily.InterNetworkV6) { m_log.Info("[NetworkUtil] Localhost user detected, sending them '" + host + "' instead of '" + defaultHostname + "'"); return host; } } } if (destination.AddressFamily != AddressFamily.InterNetwork) return null; // Check if we're accessing localhost. foreach (KeyValuePair<IPAddress, IPAddress> pair in m_subnets) { IPAddress host = pair.Value; if (host.Equals(destination) && host.AddressFamily == AddressFamily.InterNetwork) { m_log.Info("[NATROUTING] Localhost user detected, sending them '" + host + "' instead of '" + defaultHostname + "'"); return destination; } } // Check for same LAN segment foreach (KeyValuePair<IPAddress, IPAddress> subnet in m_subnets) { byte[] subnetBytes = subnet.Value.GetAddressBytes(); byte[] localBytes = subnet.Key.GetAddressBytes(); byte[] destBytes = destination.GetAddressBytes(); if (subnetBytes.Length != destBytes.Length || subnetBytes.Length != localBytes.Length) return null; bool valid = true; for (int i=0;i<subnetBytes.Length;i++) { if ((localBytes[i] & subnetBytes[i]) != (destBytes[i] & subnetBytes[i])) { valid = false; break; } } if (subnet.Key.AddressFamily != AddressFamily.InterNetwork) valid = false; if (valid) { m_log.Info("[NetworkUtil] Local LAN user detected, sending them '" + subnet.Key + "' instead of '" + defaultHostname + "'"); return subnet.Key; } } // Check to see if we can find a IPv4 address. foreach (IPAddress host in Dns.GetHostAddresses(defaultHostname)) { if (host.AddressFamily == AddressFamily.InterNetwork) return host; } // Unable to find anything. throw new ArgumentException("[NetworkUtil] Unable to resolve defaultHostname to an IPv4 address for an IPv4 client"); } static NetworkUtil() { try { foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation address in ni.GetIPProperties().UnicastAddresses) { if (address.Address.AddressFamily == AddressFamily.InterNetwork) { if (address.IPv4Mask != null) { m_subnets.Add(address.Address, address.IPv4Mask); } } } } } catch (NotImplementedException) { // Mono Sucks. } } public static IPAddress GetIPFor(IPEndPoint user, string defaultHostname) { if (!m_disabled) { // Try subnet matching IPAddress rtn = GetExternalIPFor(user.Address, defaultHostname); if (rtn != null) return rtn; } // Otherwise use the old algorithm IPAddress ia; if (IPAddress.TryParse(defaultHostname, out ia)) return ia; ia = null; foreach (IPAddress Adr in Dns.GetHostAddresses(defaultHostname)) { if (Adr.AddressFamily == AddressFamily.InterNetwork) { ia = Adr; break; } } return ia; } public static string GetHostFor(IPAddress user, string defaultHostname) { if (!m_disabled) { IPAddress rtn = GetExternalIPFor(user, defaultHostname); if (rtn != null) return rtn.ToString(); } return defaultHostname; } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Glass.Mapper.Configuration; using Glass.Mapper.Sc.Configuration; using Sitecore.Data.Fields; namespace Glass.Mapper.Sc.DataMappers { /// <summary> /// Class AbstractSitecoreFieldMapper /// </summary> public abstract class AbstractSitecoreFieldMapper : AbstractDataMapper { /// <summary> /// Gets the types handled. /// </summary> /// <value>The types handled.</value> public IEnumerable<Type> TypesHandled { get; private set; } /// <summary> /// The default value to return if the field isn't found /// </summary> protected virtual object DefaultValue { get { return null; } } /// <summary> /// Initializes a new instance of the <see cref="AbstractSitecoreFieldMapper"/> class. /// </summary> /// <param name="typesHandled">The types handled.</param> public AbstractSitecoreFieldMapper(params Type [] typesHandled) { TypesHandled = typesHandled; } public override void MapCmsToProperty(AbstractDataMappingContext mappingContext) { var scConfig = Configuration as SitecoreFieldConfiguration; if ((scConfig.Setting & SitecoreFieldSettings.PageEditorOnly) == SitecoreFieldSettings.PageEditorOnly) { return; } base.MapCmsToProperty(mappingContext); } public override void MapPropertyToCms(AbstractDataMappingContext mappingContext) { var scConfig = Configuration as SitecoreFieldConfiguration; if ((scConfig.Setting & SitecoreFieldSettings.PageEditorOnly) == SitecoreFieldSettings.PageEditorOnly) { return; } base.MapPropertyToCms(mappingContext); } /// <summary> /// Maps data from the .Net property value to the CMS value /// </summary> /// <param name="mappingContext">The mapping context.</param> /// <returns>The value to write</returns> public override void MapToCms(AbstractDataMappingContext mappingContext) { var scConfig = Configuration as SitecoreFieldConfiguration; var scContext = mappingContext as SitecoreDataMappingContext ; var field = Utilities.GetField(scContext.Item, scConfig.FieldId, scConfig.FieldName); if(field ==null) return; object value = Configuration.PropertyInfo.GetValue(mappingContext.Object, null); SetField(field, value, scConfig, scContext); } /// <summary> /// Maps data from the CMS value to the .Net property value /// </summary> /// <param name="mappingContext">The mapping context.</param> /// <returns>System.Object.</returns> public override object MapToProperty(AbstractDataMappingContext mappingContext) { var scConfig = Configuration as SitecoreFieldConfiguration; var scContext = mappingContext as SitecoreDataMappingContext; var field = Utilities.GetField(scContext.Item, scConfig.FieldId, scConfig.FieldName); if (field == null) return DefaultValue; return GetField(field, scConfig, scContext); } /// <summary> /// Gets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.Object.</returns> public virtual object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { var fieldValue = field.Value; try { return GetFieldValue(fieldValue, config, context); } catch (Exception ex) { #if NCRUNCH throw new MapperException("Failed to map field {0} with value {1}".Formatted(field.ID, fieldValue), ex); #else throw new MapperException("Failed to map field {0} with value {1}".Formatted(field.Name, fieldValue), ex); #endif } } /// <summary> /// Sets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> public virtual void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { field.Value = SetFieldValue(value, config, context); } /// <summary> /// Sets the field value. /// </summary> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.String.</returns> public abstract string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context); /// <summary> /// Gets the field value. /// </summary> /// <param name="fieldValue">The field value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.Object.</returns> public abstract object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config, SitecoreDataMappingContext context); /// <summary> /// Indicates that the data mapper will mapper to and from the property /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="context">The context.</param> /// <returns><c>true</c> if this instance can handle the specified configuration; otherwise, <c>false</c>.</returns> public override bool CanHandle(Mapper.Configuration.AbstractPropertyConfiguration configuration, Context context) { return configuration is SitecoreFieldConfiguration && TypesHandled.Any(x => x == configuration.PropertyInfo.PropertyType); } public override void Setup(Mapper.Pipelines.DataMapperResolver.DataMapperResolverArgs args) { var scArgs = args.PropertyConfiguration as FieldConfiguration; this.ReadOnly = scArgs.ReadOnly; base.Setup(args); } } }
// These interfaces serve as an extension to the BCL's SymbolStore interfaces. namespace OpenRiaServices.DomainServices.Tools.Pdb.SymStore { using System; using System.Diagnostics.SymbolStore; using System.Runtime.InteropServices; using System.Text; [ ComImport, Guid("B62B923C-B500-3158-A543-24F307A8B7E1"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false) ] internal interface ISymUnmanagedMethod { void GetToken(out SymbolToken pToken); void GetSequencePointCount(out int retVal); void GetRootScope([MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedScope retVal); void GetScopeFromOffset(int offset, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedScope retVal); void GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal); void GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=3)] int[] ranges); void GetParameters(int cParams, out int pcParams, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedVariable[] parms); void GetNamespace([MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedNamespace retVal); void GetSourceStartEnd(ISymUnmanagedDocument[] docs, [In, Out, MarshalAs(UnmanagedType.LPArray)] int[] lines, [In, Out, MarshalAs(UnmanagedType.LPArray)] int[] columns, out Boolean retVal); void GetSequencePoints(int cPoints, out int pcPoints, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] int[] offsets, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedDocument[] documents, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] int[] lines, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] int[] columns, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] int[] endLines, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] int[] endColumns); } [ ComImport, Guid("85E891DA-A631-4c76-ACA2-A44A39C46B8C"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false) ] internal interface ISymENCUnmanagedMethod { void GetFileNameFromOffset(int dwOffset, int cchName, out int pcchName, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder name); void GetLineFromOffset(int dwOffset, out int pline, out int pcolumn, out int pendLine, out int pendColumn, out int pdwStartOffset); } internal class SymMethod : ISymbolMethod, ISymbolEnCMethod { ISymUnmanagedMethod m_unmanagedMethod; public SymMethod(ISymUnmanagedMethod unmanagedMethod) { // We should not wrap null instances if (unmanagedMethod == null) throw new ArgumentNullException("unmanagedMethod"); m_unmanagedMethod = unmanagedMethod; } public SymbolToken Token { get { SymbolToken token; m_unmanagedMethod.GetToken(out token); return token; } } public int SequencePointCount { get { int retval = 0; m_unmanagedMethod.GetSequencePointCount(out retval); return retval; } } public void GetSequencePoints(int[] offsets, ISymbolDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns) { int spCount = 0; if (offsets != null) spCount = offsets.Length; else if (documents != null) spCount = documents.Length; else if (lines != null) spCount = lines.Length; else if (columns != null) spCount = columns.Length; else if (endLines != null) spCount = endLines.Length; else if (endColumns != null) spCount = endColumns.Length; // Don't do anything if they're not really asking for anything. if (spCount == 0) return; // Make sure all arrays are the same length. if ((offsets != null) && (spCount != offsets.Length)) throw new ArgumentException(); if ((lines != null) && (spCount != lines.Length)) throw new ArgumentException(); if ((columns != null) && (spCount != columns.Length)) throw new ArgumentException(); if ((endLines != null) && (spCount != endLines.Length)) throw new ArgumentException(); if ((endColumns != null) && (spCount != endColumns.Length)) throw new ArgumentException(); ISymUnmanagedDocument[] unmanagedDocuments = new ISymUnmanagedDocument[documents.Length]; int cPoints = 0; uint i; m_unmanagedMethod.GetSequencePoints(documents.Length, out cPoints, offsets, unmanagedDocuments, lines, columns, endLines, endColumns); // Create the SymbolDocument form the IntPtr's for (i = 0; i < documents.Length; i++) { documents[i] = new SymbolDocument(unmanagedDocuments[i]); } return; } public ISymbolScope RootScope { get { ISymUnmanagedScope retval = null; m_unmanagedMethod.GetRootScope(out retval); return new SymScope(retval); } } public ISymbolScope GetScope(int offset) { ISymUnmanagedScope retVal = null; m_unmanagedMethod.GetScopeFromOffset(offset, out retVal); return new SymScope(retVal); } public int GetOffset(ISymbolDocument document, int line, int column) { int retVal = 0; m_unmanagedMethod.GetOffset(((SymbolDocument)document).InternalDocument, line, column, out retVal); return retVal; } public int[] GetRanges(ISymbolDocument document, int line, int column) { int cRanges = 0; m_unmanagedMethod.GetRanges(((SymbolDocument)document).InternalDocument, line, column, 0, out cRanges, null); int[] Ranges = new int[cRanges]; m_unmanagedMethod.GetRanges(((SymbolDocument)document).InternalDocument, line, column, cRanges, out cRanges, Ranges); return Ranges; } public ISymbolVariable[] GetParameters() { int cVariables = 0; uint i; m_unmanagedMethod.GetParameters(0, out cVariables, null); ISymUnmanagedVariable[] unmanagedVariables = new ISymUnmanagedVariable[cVariables]; m_unmanagedMethod.GetParameters(cVariables, out cVariables, unmanagedVariables); ISymbolVariable[] Variables = new ISymbolVariable[cVariables]; for (i = 0; i < cVariables; i++) { Variables[i] = new SymVariable(unmanagedVariables[i]); } return Variables; } public ISymbolNamespace GetNamespace() { ISymUnmanagedNamespace retVal = null; m_unmanagedMethod.GetNamespace(out retVal); return new SymNamespace(retVal); } public bool GetSourceStartEnd(ISymbolDocument[] docs, int[] lines, int[] columns) { uint i; bool pRetVal = false; int spCount = 0; if (docs != null) spCount = docs.Length; else if (lines != null) spCount = lines.Length; else if (columns != null) spCount = columns.Length; // If we don't have at least 2 entries then return an error if (spCount < 2) throw new ArgumentException(); // Make sure all arrays are the same length. if ((docs != null) && (spCount != docs.Length)) throw new ArgumentException(); if ((lines != null) && (spCount != lines.Length)) throw new ArgumentException(); if ((columns != null) && (spCount != columns.Length)) throw new ArgumentException(); ISymUnmanagedDocument[] unmanagedDocuments = new ISymUnmanagedDocument[docs.Length]; m_unmanagedMethod.GetSourceStartEnd(unmanagedDocuments, lines, columns, out pRetVal); if (pRetVal) { for (i = 0; i < docs.Length;i++) { docs[i] = new SymbolDocument(unmanagedDocuments[i]); } } return pRetVal; } public String GetFileNameFromOffset(int dwOffset) { int cchName = 0; ((ISymENCUnmanagedMethod)m_unmanagedMethod).GetFileNameFromOffset(dwOffset, 0, out cchName, null); StringBuilder Name = new StringBuilder(cchName); ((ISymENCUnmanagedMethod)m_unmanagedMethod).GetFileNameFromOffset(dwOffset, cchName, out cchName, Name); return Name.ToString(); } public int GetLineFromOffset(int dwOffset, out int pcolumn, out int pendLine, out int pendColumn, out int pdwStartOffset) { int line = 0; ((ISymENCUnmanagedMethod)m_unmanagedMethod).GetLineFromOffset( dwOffset, out line, out pcolumn, out pendLine, out pendColumn, out pdwStartOffset); return line; } public ISymUnmanagedMethod InternalMethod { get { return m_unmanagedMethod; } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.IO; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings namespace Microsoft.PowerShell.Commands { #region ConsoleCmdletsBase /// <summary> /// Base class for all the Console related cmdlets. /// </summary> public abstract class ConsoleCmdletsBase : PSCmdlet { /// <summary> /// Runspace configuration for the current engine /// </summary> /// <remarks> /// Console cmdlets need <see cref="RunspaceConfigForSingleShell"/> object to work with. /// </remarks> internal RunspaceConfigForSingleShell Runspace { get { RunspaceConfigForSingleShell runSpace = Context.RunspaceConfiguration as RunspaceConfigForSingleShell; return runSpace; } } /// <summary> /// InitialSessionState for the current engine /// </summary> internal InitialSessionState InitialSessionState { get { return Context.InitialSessionState; } } /// <summary> /// Throws a terminating error. /// </summary> /// <param name="targetObject">Object which caused this exception.</param> /// <param name="errorId">ErrorId for this error.</param> /// <param name="innerException">Complete exception object.</param> /// <param name="category">ErrorCategory for this exception.</param> internal void ThrowError( Object targetObject, string errorId, Exception innerException, ErrorCategory category) { ThrowTerminatingError(new ErrorRecord(innerException, errorId, category, targetObject)); } } #endregion #region export-console /// <summary> /// Class that implements export-console cmdlet. /// </summary> [Cmdlet(VerbsData.Export, "Console", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113298")] public sealed class ExportConsoleCommand : ConsoleCmdletsBase { #region Parameters /// <summary> /// Property that gets/sets console file name. /// </summary> /// <remarks> /// If a parameter is not supplied then the file represented by $console /// will be used for saving. /// </remarks> [Parameter(Position = 0, Mandatory = false, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string Path { get { return _fileName; } set { _fileName = value; } } private string _fileName; /// <summary> /// Property that sets force parameter. This will reset the read-only /// attribute on an existing file before deleting it. /// </summary> [Parameter()] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Property that prevents file overwrite. /// </summary> [Parameter()] [Alias("NoOverwrite")] public SwitchParameter NoClobber { get { return _noclobber; } set { _noclobber = value; } } private bool _noclobber; #endregion #region Overrides /// <summary> /// Saves the current console info into a file. /// </summary> protected override void ProcessRecord() { // Get filename.. string file = GetFileName(); // if file is null or empty..prompt the user for filename if (string.IsNullOrEmpty(file)) { file = PromptUserForFile(); } // if file is still empty..write error and back out.. if (string.IsNullOrEmpty(file)) { PSArgumentException ae = PSTraceSource.NewArgumentException("file", ConsoleInfoErrorStrings.FileNameNotResolved); ThrowError(file, "FileNameNotResolved", ae, ErrorCategory.InvalidArgument); } if (WildcardPattern.ContainsWildcardCharacters(file)) { ThrowError(file, "WildCardNotSupported", PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.ConsoleFileWildCardsNotSupported, file), ErrorCategory.InvalidOperation); } // Ofcourse, you cant write to a file from HKLM: etc.. string resolvedPath = ResolveProviderAndPath(file); // If resolvedPath is empty just return.. if (string.IsNullOrEmpty(resolvedPath)) { return; } // Check whether the file ends with valid extension if (!resolvedPath.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase)) { // file does not end with proper extension..create one.. resolvedPath = resolvedPath + StringLiterals.PowerShellConsoleFileExtension; } if (!ShouldProcess(this.Path)) // should this be resolvedPath? return; //check if destination file exists. if (File.Exists(resolvedPath)) { if (NoClobber) { string message = StringUtil.Format( ConsoleInfoErrorStrings.FileExistsNoClobber, resolvedPath, "NoClobber"); // prevents localization Exception uae = new UnauthorizedAccessException(message); ErrorRecord errorRecord = new ErrorRecord( uae, "NoClobber", ErrorCategory.ResourceExists, resolvedPath); // NOTE: this call will throw ThrowTerminatingError(errorRecord); } // Check if the file is read-only System.IO.FileAttributes attrib = System.IO.File.GetAttributes(resolvedPath); if ((attrib & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly) { if (Force) { RemoveFileThrowIfError(resolvedPath); // Note, we do not attempt to set read-only on the new file } else { ThrowError(file, "ConsoleFileReadOnly", PSTraceSource.NewArgumentException(file, ConsoleInfoErrorStrings.ConsoleFileReadOnly, resolvedPath), ErrorCategory.InvalidArgument); } } } try { if (this.Runspace != null) { this.Runspace.SaveAsConsoleFile(resolvedPath); } else if (InitialSessionState != null) { this.InitialSessionState.SaveAsConsoleFile(resolvedPath); } else { Dbg.Assert(false, "Both RunspaceConfiguration and InitialSessionState should not be null"); throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.CmdletNotAvailable); } } catch (PSArgumentException mae) { ThrowError(resolvedPath, "PathNotAbsolute", mae, ErrorCategory.InvalidArgument); } catch (PSArgumentNullException mane) { ThrowError(resolvedPath, "PathNull", mane, ErrorCategory.InvalidArgument); } catch (ArgumentException ae) { ThrowError(resolvedPath, "InvalidCharactersInPath", ae, ErrorCategory.InvalidArgument); } // looks like saving succeeded. // Now try changing $console Exception e = null; try { //Update $Console variable Context.EngineSessionState.SetConsoleVariable(); } catch (ArgumentNullException ane) { e = ane; } catch (ArgumentOutOfRangeException aor) { e = aor; } catch (ArgumentException ae) { e = ae; } catch (SessionStateUnauthorizedAccessException sue) { e = sue; } catch (SessionStateOverflowException sof) { e = sof; } catch (ProviderNotFoundException pnf) { e = pnf; } catch (System.Management.Automation.DriveNotFoundException dnfe) { e = dnfe; } catch (NotSupportedException ne) { e = ne; } catch (ProviderInvocationException pin) { e = pin; } if (e != null) { throw PSTraceSource.NewInvalidOperationException(e, ConsoleInfoErrorStrings.ConsoleVariableCannotBeSet, resolvedPath); } } #endregion #region Private Methods /// <summary> /// Removes file specified by destination /// </summary> /// <param name="destination">Absolute path of the file to be removed.</param> private void RemoveFileThrowIfError(string destination) { Diagnostics.Assert(System.IO.Path.IsPathRooted(destination), "RemoveFile expects an absolute path"); System.IO.FileInfo destfile = new System.IO.FileInfo(destination); if (destfile != null) { Exception e = null; try { //Make sure the file is not read only destfile.Attributes = destfile.Attributes & ~(FileAttributes.ReadOnly | FileAttributes.Hidden); destfile.Delete(); } catch (FileNotFoundException fnf) { e = fnf; } catch (DirectoryNotFoundException dnf) { e = dnf; } catch (UnauthorizedAccessException uac) { e = uac; } catch (System.Security.SecurityException se) { e = se; } catch (ArgumentNullException ane) { e = ane; } catch (ArgumentException ae) { e = ae; } catch (PathTooLongException pe) { e = pe; } catch (NotSupportedException ns) { e = ns; } catch (IOException ioe) { e = ioe; } if (e != null) { throw PSTraceSource.NewInvalidOperationException(e, ConsoleInfoErrorStrings.ExportConsoleCannotDeleteFile, destfile); } } } /// <summary> /// Resolves the specified path and verifies the path belongs to /// FileSystemProvider. /// </summary> /// <param name="path">Path to resolve</param> /// <returns>A fully qualified string representing filename.</returns> private string ResolveProviderAndPath(string path) { // Construct cmdletprovidercontext CmdletProviderContext cmdContext = new CmdletProviderContext(this); // First resolve path PathInfo resolvedPath = ResolvePath(path, true, cmdContext); // Check whether this is FileSystemProvider.. if (resolvedPath != null) { if (resolvedPath.Provider.ImplementingType == typeof(FileSystemProvider)) { return resolvedPath.Path; } throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.ProviderNotSupported, resolvedPath.Provider.Name); } return null; } /// <summary> /// Resolves the specified path to PathInfo objects /// </summary> /// /// <param name="pathToResolve"> /// The path to be resolved. Each path may contain glob characters. /// </param> /// /// <param name="allowNonexistingPaths"> /// If true, resolves the path even if it doesn't exist. /// </param> /// /// <param name="currentCommandContext"> /// The context under which the command is running. /// </param> /// /// <returns> /// A string representing the resolved path. /// </returns> /// private PathInfo ResolvePath( string pathToResolve, bool allowNonexistingPaths, CmdletProviderContext currentCommandContext) { Collection<PathInfo> results = new Collection<PathInfo>(); try { // First resolve path Collection<PathInfo> pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath( pathToResolve, currentCommandContext); foreach (PathInfo pathInfo in pathInfos) { results.Add(pathInfo); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); } catch (System.Management.Automation.DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); } catch (ItemNotFoundException pathNotFound) { if (allowNonexistingPaths) { ProviderInfo provider = null; System.Management.Automation.PSDriveInfo drive = null; string unresolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath( pathToResolve, currentCommandContext, out provider, out drive); PathInfo pathInfo = new PathInfo( drive, provider, unresolvedPath, SessionState); results.Add(pathInfo); } else { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); } } if (results.Count == 1) { return results[0]; } else if (results.Count > 1) { Exception e = PSTraceSource.NewNotSupportedException(); WriteError( new ErrorRecord(e, "NotSupported", ErrorCategory.NotImplemented, results)); return null; } else { return null; } } // ResolvePath /// <summary> /// Gets the filename for the current operation. If Name parameter is empty /// checks $console. If $console is not present, prompts user? /// </summary> /// <returns> /// A string representing filename. /// If filename cannot be deduced returns null. /// </returns> /// <exception cref="PSArgumentException"> /// 1. $console points to an PSObject that cannot be converted to string. /// </exception> private string GetFileName() { if (!string.IsNullOrEmpty(_fileName)) { // if user specified input..just return return _fileName; } // no input is specified.. // check whether $console is set PSVariable consoleVariable = Context.SessionState.PSVariable.Get(SpecialVariables.ConsoleFileName); if (consoleVariable == null) { return string.Empty; } string consoleValue = consoleVariable.Value as string; if (consoleValue == null) { // $console is not in string format // Check whether it is in PSObject format PSObject consolePSObject = consoleVariable.Value as PSObject; if ((consolePSObject != null) && ((consolePSObject.BaseObject as string) != null)) { consoleValue = consolePSObject.BaseObject as string; } } if (consoleValue != null) { // ConsoleFileName variable is found.. return consoleValue; } throw PSTraceSource.NewArgumentException("fileName", ConsoleInfoErrorStrings.ConsoleCannotBeConvertedToString); } /// <summary> /// Prompt user for filename. /// </summary> /// <returns> /// User input in string format. /// If user chooses not to export, an empty string is returned. /// </returns> /// <remarks>No exception is thrown</remarks> private string PromptUserForFile() { // ask user what to do.. if (ShouldContinue( ConsoleInfoErrorStrings.PromptForExportConsole, null)) { string caption = StringUtil.Format(ConsoleInfoErrorStrings.FileNameCaptionForExportConsole, "export-console"); string message = ConsoleInfoErrorStrings.FileNamePromptMessage; // Construct a field description object of required parameters Collection<System.Management.Automation.Host.FieldDescription> desc = new Collection<System.Management.Automation.Host.FieldDescription>(); desc.Add(new System.Management.Automation.Host.FieldDescription("Name")); // get user input from the host System.Collections.Generic.Dictionary<string, PSObject> returnValue = this.PSHostInternal.UI.Prompt(caption, message, desc); if ((returnValue != null) && (returnValue["Name"] != null)) { return (returnValue["Name"].BaseObject as string); } // We dont have any input.. return string.Empty; } // If user chooses not to export, return empty string. return string.Empty; } #endregion } #endregion }
using System.Runtime.Serialization; namespace EncompassRest.Loans.Enums { /// <summary> /// FieldName /// </summary> public enum FieldName { /// <summary> /// WhoHave25Percent /// </summary> WhoHave25Percent = 0, /// <summary> /// WhoAreEmployedByFamily /// </summary> WhoAreEmployedByFamily = 1, /// <summary> /// WhoArePaidByCommissions /// </summary> WhoArePaidByCommissions = 2, /// <summary> /// WhoOwnRentalProperties /// </summary> WhoOwnRentalProperties = 3, /// <summary> /// WhoReceiveVariableIncome /// </summary> WhoReceiveVariableIncome = 4, /// <summary> /// DocumentOwnership /// </summary> DocumentOwnership = 5, /// <summary> /// AdequateLiquidity /// </summary> AdequateLiquidity = 6, /// <summary> /// PositiveSales /// </summary> PositiveSales = 7, /// <summary> /// TaxRefunds /// </summary> TaxRefunds = 8, /// <summary> /// Depletion /// </summary> Depletion = 9, /// <summary> /// Amortization /// </summary> Amortization = 10, /// <summary> /// MortgageOrNotesPayable /// </summary> MortgageOrNotesPayable = 11, /// <summary> /// MealsAndEntertainment /// </summary> MealsAndEntertainment = 12, /// <summary> /// SubTotal /// </summary> SubTotal = 13, /// <summary> /// PartnershipTotal /// </summary> PartnershipTotal = 14, /// <summary> /// NonRecurringOther /// </summary> NonRecurringOther = 15, /// <summary> /// Depreciation /// </summary> Depreciation = 16, /// <summary> /// AlimonyReceived /// </summary> AlimonyReceived = 17, /// <summary> /// MealsAndEntertaintment /// </summary> MealsAndEntertaintment = 18, /// <summary> /// CorporationTotal /// </summary> CorporationTotal = 19, /// <summary> /// TaxableIncome /// </summary> TaxableIncome = 20, /// <summary> /// TotalTax /// </summary> TotalTax = 21, /// <summary> /// NonRecurringLoss /// </summary> NonRecurringLoss = 22, /// <summary> /// NegateScheduleD /// </summary> NegateScheduleD = 23, /// <summary> /// NetOperatingLoss /// </summary> NetOperatingLoss = 24, /// <summary> /// SubTotalMultipliedBy /// </summary> SubTotalMultipliedBy = 25, /// <summary> /// DividendsPaidToBorrower /// </summary> DividendsPaidToBorrower = 26, /// <summary> /// PensionAndIRA /// </summary> PensionAndIRA = 27, /// <summary> /// NegateScheduleE /// </summary> NegateScheduleE = 28, /// <summary> /// UnemploymentCompensation /// </summary> UnemploymentCompensation = 29, /// <summary> /// SocialSecurity /// </summary> SocialSecurity = 30, /// <summary> /// SalaryDrawToIndividual /// </summary> SalaryDrawToIndividual = 31, /// <summary> /// NetProfitAmount /// </summary> NetProfitAmount = 32, /// <summary> /// NetProfitPercent /// </summary> NetProfitPercent = 33, /// <summary> /// NetProfitTotal /// </summary> NetProfitTotal = 34, /// <summary> /// AllowableAddbackAmount /// </summary> AllowableAddbackAmount = 35, /// <summary> /// AllowableAddbackPercent /// </summary> AllowableAddbackPercent = 36, /// <summary> /// AllowableAddbackTotal /// </summary> AllowableAddbackTotal = 37, /// <summary> /// YearToDateTotal /// </summary> YearToDateTotal = 38, /// <summary> /// NetProfitOrLoss /// </summary> NetProfitOrLoss = 39, /// <summary> /// NetFarmProfitOrLoss /// </summary> NetFarmProfitOrLoss = 40, /// <summary> /// Other /// </summary> Other = 41, /// <summary> /// TotalExpenses /// </summary> TotalExpenses = 42, /// <summary> /// Depreciation1 /// </summary> Depreciation1 = 43, /// <summary> /// InterestIncome /// </summary> InterestIncome = 44, /// <summary> /// DividendIncome /// </summary> DividendIncome = 45, /// <summary> /// Depreciation2 /// </summary> Depreciation2 = 46, /// <summary> /// BusinessUseOfHome /// </summary> BusinessUseOfHome = 47, /// <summary> /// RecurringCapitalGains /// </summary> RecurringCapitalGains = 48, /// <summary> /// PrincipalPaymentsReceived /// </summary> PrincipalPaymentsReceived = 49, /// <summary> /// GrossRentsAndRoyalties /// </summary> GrossRentsAndRoyalties = 50, /// <summary> /// Amortization1 /// </summary> Amortization1 = 51, /// <summary> /// InsuranceMortgageInterestAndTaxes /// </summary> InsuranceMortgageInterestAndTaxes = 52, /// <summary> /// NonTaxPortion /// </summary> NonTaxPortion = 53, /// <summary> /// Amortization2 /// </summary> Amortization2 = 54, /// <summary> /// OrdinaryIncome /// </summary> OrdinaryIncome = 55, /// <summary> /// NetIncome /// </summary> NetIncome = 56, /// <summary> /// GuaranteedPayments /// </summary> GuaranteedPayments = 57, /// <summary> /// Total /// </summary> Total = 58, /// <summary> /// TotalIncome /// </summary> TotalIncome = 59, /// <summary> /// Wages /// </summary> Wages = 60, /// <summary> /// TaxExempt /// </summary> TaxExempt = 61, /// <summary> /// Passthrough /// </summary> Passthrough = 62, /// <summary> /// OwnershipPercent /// </summary> OwnershipPercent = 63, /// <summary> /// Year2_FormB /// </summary> [EnumMember(Value = "Year2_FormB")] Year2FormB = 64, /// <summary> /// Year2_FormA /// </summary> [EnumMember(Value = "Year2_FormA")] Year2FormA = 65, /// <summary> /// Year1_FormA /// </summary> [EnumMember(Value = "Year1_FormA")] Year1FormA = 66, /// <summary> /// Year1_FormB /// </summary> [EnumMember(Value = "Year1_FormB")] Year1FormB = 67, /// <summary> /// BusinessName /// </summary> BusinessName = 68 } }
/* * XmlConvert.cs - Implementation of the "System.Xml.XmlConvert" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * 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 */ namespace System.Xml { using System; using System.Text; using System.Globalization; public class XmlConvert { // The list of all relevant DateTime formats for "ToDateTime". private static readonly String[] formatList = { "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:ss.f", "yyyy-MM-ddTHH:mm:ss.ff", "yyyy-MM-ddTHH:mm:ss.fff", "yyyy-MM-ddTHH:mm:ss.ffff", "yyyy-MM-ddTHH:mm:ss.fffff", "yyyy-MM-ddTHH:mm:ss.ffffff", "yyyy-MM-ddTHH:mm:ss.fffffff", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:ss.fZ", "yyyy-MM-ddTHH:mm:ss.ffZ", "yyyy-MM-ddTHH:mm:ss.fffZ", "yyyy-MM-ddTHH:mm:ss.ffffZ", "yyyy-MM-ddTHH:mm:ss.fffffZ", "yyyy-MM-ddTHH:mm:ss.ffffffZ", "yyyy-MM-ddTHH:mm:ss.fffffffZ", "yyyy-MM-ddTHH:mm:sszzzzzz", "yyyy-MM-ddTHH:mm:ss.fzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffzzzzzz", "yyyy-MM-ddTHH:mm:ss.fffzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffffzzzzzz", "yyyy-MM-ddTHH:mm:ss.fffffzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffffffzzzzzz", "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz", "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff", "HH:mm:ss.ffff", "HH:mm:ss.fffff", "HH:mm:ss.ffffff", "HH:mm:ss.fffffff", "HH:mm:ssZ", "HH:mm:ss.fZ", "HH:mm:ss.ffZ", "HH:mm:ss.fffZ", "HH:mm:ss.ffffZ", "HH:mm:ss.fffffZ", "HH:mm:ss.ffffffZ", "HH:mm:ss.fffffffZ", "HH:mm:sszzzzzz", "HH:mm:ss.fzzzzzz", "HH:mm:ss.ffzzzzzz", "HH:mm:ss.fffzzzzzz", "HH:mm:ss.ffffzzzzzz", "HH:mm:ss.fffffzzzzzz", "HH:mm:ss.ffffffzzzzzz", "HH:mm:ss.fffffffzzzzzz", "yyyy-MM-dd", "yyyy-MM-ddZ", "yyyy-MM-ddzzzzzz", "yyyy-MM", "yyyy-MMZ", "yyyy-MMzzzzzz", "yyyy", "yyyyZ", "yyyyzzzzzz", "--MM-dd", "--MM-ddZ", "--MM-ddzzzzzz", "---dd", "---ddZ", "---ddzzzzzz", "--MM--", "--MM--Z", "--MM--zzzzzz" }; private static readonly char[] hexCode = {'0','1','2','3','4','5','6','7' ,'8','9','A','B','C','D','E','F'}; // Constructor. public XmlConvert() {} // Determine if a character is hexadecimal. private static bool IsHex(char ch) { if(ch >= '0' && ch <= '9') { return true; } else if(ch >= 'a' && ch <= 'f') { return true; } else if(ch >= 'A' && ch <= 'F') { return true; } else { return false; } } // Convert a character from hex to integer. private static int FromHex(char ch) { if(ch >= '0' && ch <= '9') { return (int)(ch - '0'); } else if(ch >= 'a' && ch <= 'f') { return (int)(ch - 'a' + 10); } else { return (int)(ch - 'A' + 10); } } // Determine if a character is a name start. internal static bool IsNameStart(char ch, bool allowColon) { UnicodeCategory category = Char.GetUnicodeCategory(ch); if(category == UnicodeCategory.LowercaseLetter || category == UnicodeCategory.UppercaseLetter || category == UnicodeCategory.OtherLetter || category == UnicodeCategory.TitlecaseLetter || category == UnicodeCategory.LetterNumber) { return true; } else { return ((allowColon && ch == ':') || ch == '_'); } } // Determine if a character is a non-start name character. internal static bool IsNameNonStart(char ch, bool allowColon) { UnicodeCategory category = Char.GetUnicodeCategory(ch); if(category == UnicodeCategory.LowercaseLetter || category == UnicodeCategory.UppercaseLetter || category == UnicodeCategory.DecimalDigitNumber || category == UnicodeCategory.OtherLetter || category == UnicodeCategory.TitlecaseLetter || category == UnicodeCategory.LetterNumber || category == UnicodeCategory.SpacingCombiningMark || category == UnicodeCategory.EnclosingMark || category == UnicodeCategory.NonSpacingMark || category == UnicodeCategory.ModifierLetter) { return true; } else { return ((allowColon && ch == ':') || ch == '_' || ch == '-' || ch == '.'); } } // Decode a name that has escaped hexadecimal characters. public static String DecodeName(String name) { int posn, posn2; StringBuilder result; // Bail out if the name does not contain encoded characters. if(name == null || (posn = name.IndexOf("_x")) == -1) { return name; } // Decode the string and build a new one. result = new StringBuilder(); if(posn > 0) { result.Append(name.Substring(0, posn)); } while(posn <= (name.Length - 7)) { if(name[posn] == '_' && name[posn + 1] == 'x' && IsHex(name[posn + 2]) && IsHex(name[posn + 3]) && IsHex(name[posn + 4]) && IsHex(name[posn + 5]) && name[posn + 6] == '_') { // This is a hexadecimal character encoding. result.Append((char)((FromHex(name[posn + 2]) << 12) | (FromHex(name[posn + 3]) << 8) | (FromHex(name[posn + 4]) << 4) | FromHex(name[posn + 5]))); posn += 7; } else { // Search for the next candidate. posn2 = name.IndexOf('_', posn + 1); if(posn2 != -1) { result.Append(name.Substring(posn, posn2 - posn)); posn = posn2; } else { result.Append('_'); break; } } } if(posn < name.Length) { result.Append(name.Substring(posn)); } // Return the final string to the caller. return result.ToString(); } // Hex characters to use for encoding purposes. private static readonly String hexchars = "0123456789ABCDEF"; // Append the hexadecimal version of a character to a string builder. private static void AppendHex(StringBuilder result, char ch) { result.Append('_'); result.Append('x'); result.Append(hexchars[(ch >> 12) & 0x0F]); result.Append(hexchars[(ch >> 8) & 0x0F]); result.Append(hexchars[(ch >> 4) & 0x0F]); result.Append(hexchars[ch & 0x0F]); result.Append('_'); } // Inner version of "EncodeName", "EncodeLocalName", and "EncodeNmToken". private static String InnerEncodeName(String name, bool allowColon, bool isNmToken) { int posn; char ch; // Bail out if the name is null or empty. if(name == null || name.Length == 0) { return name; } // Bail out if the name is already OK. ch = name[0]; if((isNmToken && IsNameNonStart(ch, allowColon)) || (!isNmToken && IsNameStart(ch, allowColon))) { if(ch != '_' || name.Length == 1 || name[1] != 'x') { for(posn = 1; posn < name.Length; ++posn) { ch = name[posn]; if(!IsNameNonStart(ch, allowColon)) { break; } if(ch == '_' && (posn + 1) < name.Length && name[posn + 1] == 'x') { break; } } if(posn >= name.Length) { return name; } } } // Build a new string with the encoded form. StringBuilder result = new StringBuilder(); ch = name[0]; if((isNmToken && IsNameNonStart(ch, allowColon)) || (!isNmToken && IsNameStart(ch, allowColon))) { if(ch == '_' && name.Length > 1 && name[1] == 'x') { AppendHex(result, '_'); } else { result.Append(ch); } } else { AppendHex(result, ch); } for(posn = 1; posn < name.Length; ++posn) { ch = name[posn]; if(IsNameNonStart(ch, allowColon)) { if(ch == '_' && (posn + 1) < name.Length && name[posn + 1] == 'x') { AppendHex(result, '_'); } else { result.Append(ch); } } else { AppendHex(result, ch); } } // Return the encoded string to the caller. return result.ToString(); } // Encode a name to escape special characters using hexadecimal. public static String EncodeName(String name) { return InnerEncodeName(name, true, false); } // Encode a local name to escape special characters using hexadecimal. public static String EncodeLocalName(String name) { return InnerEncodeName(name, false, false); } // Encode a name token to escape special characters using hexadecimal. public static String EncodeNmToken(String name) { return InnerEncodeName(name, true, true); } // Convert a string to boolean. public static bool ToBoolean(String s) { if(s == null) { throw new ArgumentNullException("s"); } s = s.Trim(); if(s == "true" || s == "1") { return true; } else if(s == "false" || s == "0") { return false; } else { throw new FormatException(S._("Xml_InvalidBoolean")); } } // Convert a string to a byte value. public static byte ToByte(String s) { return Byte.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } // Convert a string to a character value. public static char ToChar(String s) { return Char.Parse(s); } // Convert a string into a DateTime value. public static DateTime ToDateTime(String s) { return DateTime.ParseExact(s, formatList, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } // Convert a string into a DateTime value using a specific format. public static DateTime ToDateTime(String s, String format) { return DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } // Convert a string into a DateTime value using a list of formats. public static DateTime ToDateTime(String s, String[] formats) { return DateTime.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } #if CONFIG_EXTENDED_NUMERICS // Convert a string to a decimal value. public static Decimal ToDecimal(String s) { return Decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } // Convert a string to a double-precision value. public static double ToDouble(String s) { s = s.Trim(); if(s == "-INF") { return Double.NegativeInfinity; } else if(s == "INF") { return Double.PositiveInfinity; } return Double.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } #endif #if !ECMA_COMPAT // Convert a string into a GUID value. public static Guid ToGuid(String value) { return new Guid(value); } #endif // Convert a string to an Int16 value. public static short ToInt16(String s) { return Int16.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } // Convert a string to a UInt16 value. [CLSCompliant(false)] public static ushort ToUInt16(String s) { return UInt16.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } // Convert a string to an Int32 value. public static int ToInt32(String s) { return Int32.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } // Convert a string to a UInt32 value. [CLSCompliant(false)] public static uint ToUInt32(String s) { return UInt32.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } // Convert a string to an Int64 value. public static long ToInt64(String s) { return Int64.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } // Convert a string to a UInt64 value. [CLSCompliant(false)] public static ulong ToUInt64(String s) { return UInt64.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } // Convert a string to a signed byte value. [CLSCompliant(false)] public static sbyte ToSByte(String s) { return SByte.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } #if CONFIG_EXTENDED_NUMERICS // Convert a string to a single-precision value. public static float ToSingle(String s) { s = s.Trim(); if(s == "-INF") { return Single.NegativeInfinity; } else if(s == "INF") { return Single.PositiveInfinity; } return Single.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } #endif // Convert a string to a TimeSpan value. public static TimeSpan ToTimeSpan(String s) { return TimeSpan.Parse(s); } // Convert a boolean value into a string. public static String ToString(bool value) { return (value ? "true" : "false"); } // Convert a character value into a string. public static String ToString(char value) { return value.ToString(null); } #if CONFIG_EXTENDED_NUMERICS // Convert a decimal value into a string. public static String ToString(Decimal value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } #endif // Convert a byte value into a string. public static String ToString(byte value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } // Convert a signed byte value into a string. [CLSCompliant(false)] public static String ToString(sbyte value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } // Convert an Int16 value into a string. public static String ToString(short value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } // Convert a UInt16 value into a string. [CLSCompliant(false)] public static String ToString(ushort value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } // Convert an Int32 value into a string. public static String ToString(int value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } // Convert a UInt32 value into a string. [CLSCompliant(false)] public static String ToString(uint value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } // Convert an Int64 value into a string. public static String ToString(long value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } // Convert a UInt64 value into a string. [CLSCompliant(false)] public static String ToString(ulong value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } #if CONFIG_EXTENDED_NUMERICS // Convert a single-precision value into a string. public static String ToString(float value) { if(Single.IsNegativeInfinity(value)) { return "-INF"; } else if(Single.IsPositiveInfinity(value)) { return "INF"; } return value.ToString("R", NumberFormatInfo.InvariantInfo); } // Convert a double-precision value into a string. public static String ToString(double value) { if(Double.IsNegativeInfinity(value)) { return "-INF"; } else if(Double.IsPositiveInfinity(value)) { return "INF"; } return value.ToString("R", NumberFormatInfo.InvariantInfo); } #endif // Convert a TimeSpan value into a string. public static String ToString(TimeSpan value) { return value.ToString(); } // Convert a DateTime value into a string using the default format. public static String ToString(DateTime value) { return ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz"); } // Convert a DateTime value into a string using a specified format. public static String ToString(DateTime value, String format) { return value.ToString (format, DateTimeFormatInfo.InvariantInfo); } #if !ECMA_COMPAT // Convert a GUID into a string. public static String ToString(Guid value) { return value.ToString(); } #endif // Inner version of "VerifyName" and "VerifyNCName". private static String InnerVerify(String name, bool allowColon) { int posn; if(name == null || name.Length == 0) { throw new ArgumentNullException("name"); } if(!IsNameStart(name[0], allowColon)) { throw new XmlException(S._("Xml_InvalidName")); } for(posn = 1; posn < name.Length; ++posn) { if(!IsNameNonStart(name[posn], allowColon)) { throw new XmlException(S._("Xml_InvalidName")); } } return name; } // Verify that a string is a valid XML name. public static String VerifyName(String name) { return InnerVerify(name, true); } // Verify that a string is a valid XML qualified name. public static String VerifyNCName(String name) { return InnerVerify(name, false); } // Characters to use to encode 6-bit values in base64. internal const String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Convert a byte buffer into a base64 string. internal static String ToBase64String (byte[] inArray, int offset, int length) { // Validate the parameters. if(inArray == null) { throw new ArgumentNullException("inArray"); } if(offset < 0 || offset > inArray.Length) { throw new ArgumentOutOfRangeException ("offset", S._("ArgRange_Array")); } if(length < 0 || length > (inArray.Length - offset)) { throw new ArgumentOutOfRangeException ("length", S._("ArgRange_Array")); } // Convert the bytes. StringBuilder builder = new StringBuilder ((int)(((((long)length) + 2L) * 4L) / 3L)); int bits = 0; int numBits = 0; String base64 = base64Chars; int size = length; while(size > 0) { bits = (bits << 8) + inArray[offset++]; numBits += 8; --size; while(numBits >= 6) { numBits -= 6; builder.Append(base64[bits >> numBits]); bits &= ((1 << numBits) - 1); } } length %= 3; if(length == 1) { builder.Append(base64[bits << (6 - numBits)]); builder.Append('='); builder.Append('='); } else if(length == 2) { builder.Append(base64[bits << (6 - numBits)]); builder.Append('='); } // Finished. return builder.ToString(); } // Convert a byte buffer into a hex String. internal static String ToHexString (byte[] inArray, int offset, int length) { // Validate the parameters. if(inArray == null) { throw new ArgumentNullException("inArray"); } if(offset < 0 || offset > inArray.Length) { throw new ArgumentOutOfRangeException ("offset", S._("ArgRange_Array")); } if(length < 0 || length > (inArray.Length - offset)) { throw new ArgumentOutOfRangeException ("length", S._("ArgRange_Array")); } byte currentByte; // Convert the bytes. StringBuilder builder = new StringBuilder ((int)(((long)length) * 2L)); for(int a = 0; a < length; a++) { currentByte = inArray[offset+a]; builder.Append(hexCode[currentByte >> 4]); builder.Append(hexCode[currentByte & 0xF]); } // Finished. return builder.ToString(); } }; // class XmlConvert }; // namespace System.Xml
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Apple; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class AppleCrypto { private static int AppleCryptoNative_SecKeyImportEphemeral( ReadOnlySpan<byte> pbKeyBlob, int isPrivateKey, out SafeSecKeyRefHandle ppKeyOut, out int pOSStatus) => AppleCryptoNative_SecKeyImportEphemeral( ref MemoryMarshal.GetReference(pbKeyBlob), pbKeyBlob.Length, isPrivateKey, out ppKeyOut, out pOSStatus); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SecKeyImportEphemeral( ref byte pbKeyBlob, int cbKeyBlob, int isPrivateKey, out SafeSecKeyRefHandle ppKeyOut, out int pOSStatus); private static int AppleCryptoNative_GenerateSignature( SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> pbDataHash, out SafeCFDataHandle pSignatureOut, out SafeCFErrorHandle pErrorOut) => AppleCryptoNative_GenerateSignature( privateKey, ref MemoryMarshal.GetReference(pbDataHash), pbDataHash.Length, out pSignatureOut, out pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_GenerateSignature( SafeSecKeyRefHandle privateKey, ref byte pbDataHash, int cbDataHash, out SafeCFDataHandle pSignatureOut, out SafeCFErrorHandle pErrorOut); private static int AppleCryptoNative_GenerateSignatureWithHashAlgorithm( SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> pbDataHash, PAL_HashAlgorithm hashAlgorithm, out SafeCFDataHandle pSignatureOut, out SafeCFErrorHandle pErrorOut) => AppleCryptoNative_GenerateSignatureWithHashAlgorithm( privateKey, ref MemoryMarshal.GetReference(pbDataHash), pbDataHash.Length, hashAlgorithm, out pSignatureOut, out pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_GenerateSignatureWithHashAlgorithm( SafeSecKeyRefHandle privateKey, ref byte pbDataHash, int cbDataHash, PAL_HashAlgorithm hashAlgorithm, out SafeCFDataHandle pSignatureOut, out SafeCFErrorHandle pErrorOut); private static int AppleCryptoNative_VerifySignature( SafeSecKeyRefHandle publicKey, ReadOnlySpan<byte> pbDataHash, ReadOnlySpan<byte> pbSignature, out SafeCFErrorHandle pErrorOut) => AppleCryptoNative_VerifySignature( publicKey, ref MemoryMarshal.GetReference(pbDataHash), pbDataHash.Length, ref MemoryMarshal.GetReference(pbSignature), pbSignature.Length, out pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_VerifySignature( SafeSecKeyRefHandle publicKey, ref byte pbDataHash, int cbDataHash, ref byte pbSignature, int cbSignature, out SafeCFErrorHandle pErrorOut); private static int AppleCryptoNative_VerifySignatureWithHashAlgorithm( SafeSecKeyRefHandle publicKey, ReadOnlySpan<byte> pbDataHash, ReadOnlySpan<byte> pbSignature, PAL_HashAlgorithm hashAlgorithm, out SafeCFErrorHandle pErrorOut) => AppleCryptoNative_VerifySignatureWithHashAlgorithm( publicKey, ref MemoryMarshal.GetReference(pbDataHash), pbDataHash.Length, ref MemoryMarshal.GetReference(pbSignature), pbSignature.Length, hashAlgorithm, out pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_VerifySignatureWithHashAlgorithm( SafeSecKeyRefHandle publicKey, ref byte pbDataHash, int cbDataHash, ref byte pbSignature, int cbSignature, PAL_HashAlgorithm hashAlgorithm, out SafeCFErrorHandle pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern ulong AppleCryptoNative_SecKeyGetSimpleKeySizeInBytes(SafeSecKeyRefHandle publicKey); private delegate int SecKeyTransform(ReadOnlySpan<byte> source, out SafeCFDataHandle outputHandle, out SafeCFErrorHandle errorHandle); private static byte[] ExecuteTransform(ReadOnlySpan<byte> source, SecKeyTransform transform) { const int Success = 1; const int kErrorSeeError = -2; SafeCFDataHandle data; SafeCFErrorHandle error; int ret = transform(source, out data, out error); using (error) using (data) { if (ret == Success) { return CoreFoundation.CFGetData(data); } if (ret == kErrorSeeError) { throw CreateExceptionForCFError(error); } Debug.Fail($"transform returned {ret}"); throw new CryptographicException(); } } private static bool TryExecuteTransform( ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten, SecKeyTransform transform) { SafeCFDataHandle outputHandle; SafeCFErrorHandle errorHandle; int ret = transform(source, out outputHandle, out errorHandle); using (errorHandle) using (outputHandle) { const int Success = 1; const int kErrorSeeError = -2; switch (ret) { case Success: return CoreFoundation.TryCFWriteData(outputHandle, destination, out bytesWritten); case kErrorSeeError: throw CreateExceptionForCFError(errorHandle); default: Debug.Fail($"transform returned {ret}"); throw new CryptographicException(); } } } internal static int GetSimpleKeySizeInBits(SafeSecKeyRefHandle publicKey) { ulong keySizeInBytes = AppleCryptoNative_SecKeyGetSimpleKeySizeInBytes(publicKey); checked { return (int)(keySizeInBytes * 8); } } internal static SafeSecKeyRefHandle ImportEphemeralKey(ReadOnlySpan<byte> keyBlob, bool hasPrivateKey) { Debug.Assert(keyBlob != null); SafeSecKeyRefHandle keyHandle; int osStatus; int ret = AppleCryptoNative_SecKeyImportEphemeral( keyBlob, hasPrivateKey ? 1 : 0, out keyHandle, out osStatus); if (ret == 1 && !keyHandle.IsInvalid) { return keyHandle; } if (ret == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"SecKeyImportEphemeral returned {ret}"); throw new CryptographicException(); } internal static byte[] GenerateSignature(SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> dataHash) { Debug.Assert(privateKey != null, "privateKey != null"); return ExecuteTransform( dataHash, (ReadOnlySpan<byte> source, out SafeCFDataHandle signature, out SafeCFErrorHandle error) => AppleCryptoNative_GenerateSignature( privateKey, source, out signature, out error)); } internal static byte[] GenerateSignature( SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> dataHash, PAL_HashAlgorithm hashAlgorithm) { Debug.Assert(privateKey != null, "privateKey != null"); Debug.Assert(hashAlgorithm != PAL_HashAlgorithm.Unknown, "hashAlgorithm != PAL_HashAlgorithm.Unknown"); return ExecuteTransform( dataHash, (ReadOnlySpan<byte> source, out SafeCFDataHandle signature, out SafeCFErrorHandle error) => AppleCryptoNative_GenerateSignatureWithHashAlgorithm( privateKey, source, hashAlgorithm, out signature, out error)); } internal static bool TryGenerateSignature( SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> source, Span<byte> destination, PAL_HashAlgorithm hashAlgorithm, out int bytesWritten) { Debug.Assert(privateKey != null, "privateKey != null"); Debug.Assert(hashAlgorithm != PAL_HashAlgorithm.Unknown, "hashAlgorithm != PAL_HashAlgorithm.Unknown"); return TryExecuteTransform( source, destination, out bytesWritten, delegate (ReadOnlySpan<byte> innerSource, out SafeCFDataHandle outputHandle, out SafeCFErrorHandle errorHandle) { return AppleCryptoNative_GenerateSignatureWithHashAlgorithm( privateKey, innerSource, hashAlgorithm, out outputHandle, out errorHandle); }); } internal static bool VerifySignature( SafeSecKeyRefHandle publicKey, ReadOnlySpan<byte> dataHash, ReadOnlySpan<byte> signature) { Debug.Assert(publicKey != null, "publicKey != null"); SafeCFErrorHandle error; int ret = AppleCryptoNative_VerifySignature( publicKey, dataHash, signature, out error); const int True = 1; const int False = 0; const int kErrorSeeError = -2; using (error) { switch (ret) { case True: return true; case False: return false; case kErrorSeeError: throw CreateExceptionForCFError(error); default: Debug.Fail($"VerifySignature returned {ret}"); throw new CryptographicException(); } } } internal static bool VerifySignature( SafeSecKeyRefHandle publicKey, ReadOnlySpan<byte> dataHash, ReadOnlySpan<byte> signature, PAL_HashAlgorithm hashAlgorithm) { Debug.Assert(publicKey != null, "publicKey != null"); Debug.Assert(hashAlgorithm != PAL_HashAlgorithm.Unknown); SafeCFErrorHandle error; int ret = AppleCryptoNative_VerifySignatureWithHashAlgorithm( publicKey, dataHash, signature, hashAlgorithm, out error); const int True = 1; const int False = 0; const int kErrorSeeError = -2; using (error) { switch (ret) { case True: return true; case False: return false; case kErrorSeeError: throw CreateExceptionForCFError(error); default: Debug.Fail($"VerifySignature returned {ret}"); throw new CryptographicException(); } } } } } namespace System.Security.Cryptography.Apple { internal sealed class SafeSecKeyRefHandle : SafeKeychainItemHandle { } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // 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.Data.Common; using System.Collections; using Xunit; namespace System.Data.Tests { public class DataTableReaderTest { private DataTable _dt; public DataTableReaderTest() { _dt = new DataTable("test"); _dt.Columns.Add("id", typeof(int)); _dt.Columns.Add("name", typeof(string)); _dt.PrimaryKey = new DataColumn[] { _dt.Columns["id"] }; _dt.Rows.Add(new object[] { 1, "mono 1" }); _dt.Rows.Add(new object[] { 2, "mono 2" }); _dt.Rows.Add(new object[] { 3, "mono 3" }); _dt.AcceptChanges(); } #region Positive Tests [Fact] public void CtorTest() { _dt.Rows[1].Delete(); DataTableReader reader = new DataTableReader(_dt); try { int i = 0; while (reader.Read()) i++; reader.Close(); Assert.Equal(2, i); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void RowInAccessibleTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Read(); // 2nd row _dt.Rows[1].Delete(); string value = reader[1].ToString(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void IgnoreDeletedRowsDynamicTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[1].Delete(); reader.Read(); // it should be 3rd row string value = reader[0].ToString(); Assert.Equal("3", value); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void SeeTheModifiedTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[1]["name"] = "mono changed"; reader.Read(); string value = reader[1].ToString(); Assert.Equal("mono changed", value); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void SchemaTest() { DataTable another = new DataTable("another"); another.Columns.Add("x", typeof(string)); another.Rows.Add(new object[] { "test 1" }); another.Rows.Add(new object[] { "test 2" }); another.Rows.Add(new object[] { "test 3" }); DataTableReader reader = new DataTableReader(new DataTable[] { _dt, another }); try { DataTable schema = reader.GetSchemaTable(); Assert.Equal(_dt.Columns.Count, schema.Rows.Count); Assert.Equal(_dt.Columns[1].DataType.ToString(), schema.Rows[1]["DataType"].ToString()); reader.NextResult(); //schema should change here schema = reader.GetSchemaTable(); Assert.Equal(another.Columns.Count, schema.Rows.Count); Assert.Equal(another.Columns[0].DataType.ToString(), schema.Rows[0]["DataType"].ToString()); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void MultipleResultSetsTest() { DataTable dt1 = new DataTable("test2"); dt1.Columns.Add("x", typeof(string)); dt1.Rows.Add(new object[] { "test" }); dt1.Rows.Add(new object[] { "test1" }); dt1.AcceptChanges(); DataTable[] collection = new DataTable[] { _dt, dt1 }; DataTableReader reader = new DataTableReader(collection); try { int i = 0; do { while (reader.Read()) i++; } while (reader.NextResult()); Assert.Equal(5, i); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void GetTest() { _dt.Columns.Add("nullint", typeof(int)); _dt.Rows[0]["nullint"] = 333; DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); int ordinal = reader.GetOrdinal("nullint"); // Get by name Assert.Equal(1, (int)reader["id"]); Assert.Equal(333, reader.GetInt32(ordinal)); Assert.Equal("Int32", reader.GetDataTypeName(ordinal)); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void CloseTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { int i = 0; while (reader.Read() && i < 1) i++; reader.Close(); reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void GetOrdinalTest() { DataTableReader reader = new DataTableReader(_dt); try { Assert.Equal(1, reader.GetOrdinal("name")); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } #endregion // Positive Tests #region Negative Tests [Fact] public void NoRowsTest() { _dt.Rows.Clear(); _dt.AcceptChanges(); DataTableReader reader = new DataTableReader(_dt); try { Assert.False(reader.Read()); Assert.False(reader.NextResult()); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void NoTablesTest() { Assert.Throws<ArgumentException>(() => { DataTableReader reader = new DataTableReader(new DataTable[] { }); try { reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void ReadAfterClosedTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Close(); reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void AccessAfterClosedTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Close(); int i = (int)reader[0]; i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void AccessBeforeReadTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { int i = (int)reader[0]; i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void InvalidIndexTest() { Assert.Throws<ArgumentOutOfRangeException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); int i = (int)reader[90]; // kidding, ;-) i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void DontSeeTheEarlierRowsTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row // insert a row at position 0 DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "adhi bagavan"; _dt.Rows.InsertAt(r, 0); Assert.Equal(2, reader.GetInt32(0)); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void AddBeforePointTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "adhi bagavan"; _dt.Rows.InsertAt(r, 0); _dt.Rows.Add(new object[] { 4, "mono 4" }); // should not affect the counter Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void AddAtPointTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "same point"; _dt.Rows.InsertAt(r, 1); _dt.Rows.Add(new object[] { 4, "mono 4" }); // should not affect the counter Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeletePreviousAndAcceptChangesTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row _dt.Rows[0].Delete(); _dt.AcceptChanges(); Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeleteCurrentAndAcceptChangesTest2() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row _dt.Rows[1].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(1, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeleteFirstCurrentAndAcceptChangesTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[0].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void DeleteLastAndAcceptChangesTest2() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row reader.Read(); // third row _dt.Rows[2].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void ClearTest() { DataTableReader reader = null; try { reader = new DataTableReader(_dt); reader.Read(); // first row reader.Read(); // second row _dt.Clear(); try { int i = (int)reader[0]; i++; // suppress warning Assert.False(true); } catch (RowNotInTableException) { } // clear and add test reader.Close(); reader = new DataTableReader(_dt); reader.Read(); // first row reader.Read(); // second row _dt.Clear(); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); bool success = reader.Read(); Assert.False(success); // clear when reader is not read yet reader.Close(); reader = new DataTableReader(_dt); _dt.Clear(); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); success = reader.Read(); Assert.True(success); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void MultipleDeleteTest() { _dt.Rows.Add(new object[] { 4, "mono 4" }); _dt.Rows.Add(new object[] { 5, "mono 5" }); _dt.Rows.Add(new object[] { 6, "mono 6" }); _dt.Rows.Add(new object[] { 7, "mono 7" }); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); reader.Read(); reader.Read(); reader.Read(); _dt.Rows[3].Delete(); _dt.Rows[1].Delete(); _dt.Rows[2].Delete(); _dt.Rows[0].Delete(); _dt.Rows[6].Delete(); _dt.AcceptChanges(); Assert.Equal(5, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } #endregion // Negative Tests [Fact] public void TestSchemaTable() { var ds = new DataSet(); DataTable testTable = new DataTable("TestTable1"); DataTable testTable1 = new DataTable(); testTable.Namespace = "TableNamespace"; testTable1.Columns.Add("col1", typeof(int)); testTable1.Columns.Add("col2", typeof(int)); ds.Tables.Add(testTable); ds.Tables.Add(testTable1); //create a col for standard datatype testTable.Columns.Add("col_string"); testTable.Columns.Add("col_string_fixed"); testTable.Columns["col_string_fixed"].MaxLength = 10; testTable.Columns.Add("col_int", typeof(int)); testTable.Columns.Add("col_decimal", typeof(decimal)); testTable.Columns.Add("col_datetime", typeof(DateTime)); testTable.Columns.Add("col_float", typeof(float)); // Check for col constraints/properties testTable.Columns.Add("col_readonly").ReadOnly = true; testTable.Columns.Add("col_autoincrement", typeof(long)).AutoIncrement = true; testTable.Columns["col_autoincrement"].AutoIncrementStep = 5; testTable.Columns["col_autoincrement"].AutoIncrementSeed = 10; testTable.Columns.Add("col_pk"); testTable.PrimaryKey = new DataColumn[] { testTable.Columns["col_pk"] }; testTable.Columns.Add("col_unique"); testTable.Columns["col_unique"].Unique = true; testTable.Columns.Add("col_defaultvalue"); testTable.Columns["col_defaultvalue"].DefaultValue = "DefaultValue"; testTable.Columns.Add("col_expression_local", typeof(int)); testTable.Columns["col_expression_local"].Expression = "col_int*5"; ds.Relations.Add("rel", new DataColumn[] { testTable1.Columns["col1"] }, new DataColumn[] { testTable.Columns["col_int"] }, false); testTable.Columns.Add("col_expression_ext"); testTable.Columns["col_expression_ext"].Expression = "parent.col2"; testTable.Columns.Add("col_namespace"); testTable.Columns["col_namespace"].Namespace = "ColumnNamespace"; testTable.Columns.Add("col_mapping"); testTable.Columns["col_mapping"].ColumnMapping = MappingType.Attribute; DataTable schemaTable = testTable.CreateDataReader().GetSchemaTable(); Assert.Equal(25, schemaTable.Columns.Count); Assert.Equal(testTable.Columns.Count, schemaTable.Rows.Count); //True for all rows for (int i = 0; i < schemaTable.Rows.Count; ++i) { Assert.Equal(testTable.TableName, schemaTable.Rows[i]["BaseTableName"]); Assert.Equal(ds.DataSetName, schemaTable.Rows[i]["BaseCatalogName"]); Assert.Equal(DBNull.Value, schemaTable.Rows[i]["BaseSchemaName"]); Assert.Equal(schemaTable.Rows[i]["BaseColumnName"], schemaTable.Rows[i]["ColumnName"]); Assert.False((bool)schemaTable.Rows[i]["IsRowVersion"]); } Assert.Equal("col_string", schemaTable.Rows[0]["ColumnName"]); Assert.Equal(typeof(string), schemaTable.Rows[0]["DataType"]); Assert.Equal(-1, schemaTable.Rows[0]["ColumnSize"]); Assert.Equal(0, schemaTable.Rows[0]["ColumnOrdinal"]); // ms.net contradicts documented behavior Assert.False((bool)schemaTable.Rows[0]["IsLong"]); Assert.Equal("col_string_fixed", schemaTable.Rows[1]["ColumnName"]); Assert.Equal(typeof(string), schemaTable.Rows[1]["DataType"]); Assert.Equal(10, schemaTable.Rows[1]["ColumnSize"]); Assert.Equal(1, schemaTable.Rows[1]["ColumnOrdinal"]); Assert.False((bool)schemaTable.Rows[1]["IsLong"]); Assert.Equal("col_int", schemaTable.Rows[2]["ColumnName"]); Assert.Equal(typeof(int), schemaTable.Rows[2]["DataType"]); Assert.Equal(DBNull.Value, schemaTable.Rows[2]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[2]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[2]["ColumnSize"]); Assert.Equal(2, schemaTable.Rows[2]["ColumnOrdinal"]); Assert.Equal("col_decimal", schemaTable.Rows[3]["ColumnName"]); Assert.Equal(typeof(decimal), schemaTable.Rows[3]["DataType"]); // When are the Precision and Scale Values set ? Assert.Equal(DBNull.Value, schemaTable.Rows[3]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[3]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[3]["ColumnSize"]); Assert.Equal(3, schemaTable.Rows[3]["ColumnOrdinal"]); Assert.Equal("col_datetime", schemaTable.Rows[4]["ColumnName"]); Assert.Equal(typeof(DateTime), schemaTable.Rows[4]["DataType"]); Assert.Equal(4, schemaTable.Rows[4]["ColumnOrdinal"]); Assert.Equal("col_float", schemaTable.Rows[5]["ColumnName"]); Assert.Equal(typeof(float), schemaTable.Rows[5]["DataType"]); Assert.Equal(5, schemaTable.Rows[5]["ColumnOrdinal"]); Assert.Equal(DBNull.Value, schemaTable.Rows[5]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[5]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[5]["ColumnSize"]); Assert.Equal("col_readonly", schemaTable.Rows[6]["ColumnName"]); Assert.True((bool)schemaTable.Rows[6]["IsReadOnly"]); Assert.Equal("col_autoincrement", schemaTable.Rows[7]["ColumnName"]); Assert.True((bool)schemaTable.Rows[7]["IsAutoIncrement"]); Assert.Equal(10L, schemaTable.Rows[7]["AutoIncrementSeed"]); Assert.Equal(5L, schemaTable.Rows[7]["AutoIncrementStep"]); Assert.False((bool)schemaTable.Rows[7]["IsReadOnly"]); Assert.Equal("col_pk", schemaTable.Rows[8]["ColumnName"]); Assert.True((bool)schemaTable.Rows[8]["IsKey"]); Assert.True((bool)schemaTable.Rows[8]["IsUnique"]); Assert.Equal("col_unique", schemaTable.Rows[9]["ColumnName"]); Assert.True((bool)schemaTable.Rows[9]["IsUnique"]); Assert.Equal("col_defaultvalue", schemaTable.Rows[10]["ColumnName"]); Assert.Equal("DefaultValue", schemaTable.Rows[10]["DefaultValue"]); Assert.Equal("col_expression_local", schemaTable.Rows[11]["ColumnName"]); Assert.Equal("col_int*5", schemaTable.Rows[11]["Expression"]); Assert.True((bool)schemaTable.Rows[11]["IsReadOnly"]); // if expression depends on a external col, then set Expression as null.. Assert.Equal("col_expression_ext", schemaTable.Rows[12]["ColumnName"]); Assert.Equal(DBNull.Value, schemaTable.Rows[12]["Expression"]); Assert.True((bool)schemaTable.Rows[12]["IsReadOnly"]); Assert.Equal("col_namespace", schemaTable.Rows[13]["ColumnName"]); Assert.Equal("TableNamespace", schemaTable.Rows[13]["BaseTableNamespace"]); Assert.Equal("TableNamespace", schemaTable.Rows[12]["BaseColumnNamespace"]); Assert.Equal("ColumnNamespace", schemaTable.Rows[13]["BaseColumnNamespace"]); Assert.Equal("col_mapping", schemaTable.Rows[14]["ColumnName"]); Assert.Equal(MappingType.Element, (MappingType)schemaTable.Rows[13]["ColumnMapping"]); Assert.Equal(MappingType.Attribute, (MappingType)schemaTable.Rows[14]["ColumnMapping"]); } [Fact] public void TestExceptionIfSchemaChanges() { DataTable table = new DataTable(); table.Columns.Add("col1"); DataTableReader rdr = table.CreateDataReader(); Assert.Equal(1, rdr.GetSchemaTable().Rows.Count); table.Columns[0].ColumnName = "newcol1"; try { rdr.GetSchemaTable(); Assert.False(true); } catch (InvalidOperationException) { // Never premise English. //Assert.Equal ("Schema of current DataTable '" + table.TableName + // "' in DataTableReader has changed, DataTableReader is invalid.", e.Message, "#1"); } rdr = table.CreateDataReader(); rdr.GetSchemaTable(); //no exception table.Columns.Add("col2"); try { rdr.GetSchemaTable(); Assert.False(true); } catch (InvalidOperationException) { // Never premise English. //Assert.Equal ("Schema of current DataTable '" + table.TableName + // "' in DataTableReader has changed, DataTableReader is invalid.", e.Message, "#1"); } } [Fact] public void EnumeratorTest() { DataTable table = new DataTable(); table.Columns.Add("col1", typeof(int)); table.Rows.Add(new object[] { 0 }); table.Rows.Add(new object[] { 1 }); DataTableReader rdr = table.CreateDataReader(); IEnumerator enmr = rdr.GetEnumerator(); table.Rows.Add(new object[] { 2 }); table.Rows.RemoveAt(0); //Test if the Enumerator is stable int i = 1; while (enmr.MoveNext()) { DbDataRecord rec = (DbDataRecord)enmr.Current; Assert.Equal(i, rec.GetInt32(0)); i++; } } [Fact] public void GetCharsTest() { _dt.Columns.Add("col2", typeof(char[])); _dt.Rows.Clear(); _dt.Rows.Add(new object[] { 1, "string", "string".ToCharArray() }); _dt.Rows.Add(new object[] { 2, "string1", null }); DataTableReader rdr = _dt.CreateDataReader(); rdr.Read(); try { rdr.GetChars(1, 0, null, 0, 10); Assert.False(true); } catch (InvalidCastException e) { // Never premise English. //Assert.Equal ("Unable to cast object of type 'System.String'" + // " to type 'System.Char[]'.", e.Message, "#1"); } char[] char_arr = null; long len = 0; len = rdr.GetChars(2, 0, null, 0, 0); Assert.Equal(6, len); char_arr = new char[len]; len = rdr.GetChars(2, 0, char_arr, 0, 0); Assert.Equal(0, len); len = rdr.GetChars(2, 0, null, 0, 0); char_arr = new char[len + 2]; len = rdr.GetChars(2, 0, char_arr, 2, 100); Assert.Equal(6, len); char[] val = (char[])rdr.GetValue(2); for (int i = 0; i < len; ++i) Assert.Equal(val[i], char_arr[i + 2]); } [Fact] public void GetProviderSpecificTests() { DataTableReader rdr = _dt.CreateDataReader(); while (rdr.Read()) { object[] values = new object[rdr.FieldCount]; object[] pvalues = new object[rdr.FieldCount]; rdr.GetValues(values); rdr.GetProviderSpecificValues(pvalues); for (int i = 0; i < rdr.FieldCount; ++i) { Assert.Equal(values[i], pvalues[i]); Assert.Equal(rdr.GetValue(i), rdr.GetProviderSpecificValue(i)); Assert.Equal(rdr.GetFieldType(i), rdr.GetProviderSpecificFieldType(i)); } } } [Fact] public void GetNameTest() { DataTableReader rdr = _dt.CreateDataReader(); for (int i = 0; i < _dt.Columns.Count; ++i) Assert.Equal(_dt.Columns[i].ColumnName, rdr.GetName(i)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Rikrop.Core.Framework; namespace Rikrop.Core.Wpf.Mvvm.Validation { public abstract class DataValidationInfo : ChangeNotifier//Unsupported in 4.0,, INotifyDataErrorInfo { private readonly Dictionary<string, Validator> _propertyValidators; private readonly Validator _objectValidator; public IEnumerable GetErrors(string propertyName) { if (string.IsNullOrWhiteSpace(propertyName)) { return _objectValidator.GetErrors(); } Validator validator; return _propertyValidators.TryGetValue(propertyName, out validator) ? validator.GetErrors() : null; } private bool _hasErrors; public bool HasErrors { get { return _hasErrors; } private set { if (_hasErrors == value) { return; } _hasErrors = value; NotifyPropertyChanged(() => HasErrors); } } private void UpdateHasErrors() { HasErrors = _propertyValidators.Values.Any(pv => pv.HasErrors) || _objectValidator.HasErrors; } //Unsupported in 4.0, //public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; //public void RaiseErrorsChanged(string propertyName) //{ // var handler = ErrorsChanged; // if (handler == null) // { // return; // } // var args = new DataErrorsChangedEventArgs(propertyName); // handler(this, args); //} protected DataValidationInfo() { _propertyValidators = new Dictionary<string, Validator>(); _objectValidator = CreateNewValidator(null); } protected IValidationRuleAdder ForProperty(Expression<Func<object>> property) { Contract.Requires<ArgumentNullException>(property != null); AfterNotify(property) .Execute(() => Validate(property)); return new ValidationRuleAdder(this, property); } protected IObjectValidationRuleAdder ForObject() { return new ObjectValidationRuleAdder(this); } protected void Validate(Expression<Func<object>> property) { Contract.Requires<ArgumentNullException>(property != null); var propertyName = property.GetName(); Validate(propertyName); } protected void Validate() { _objectValidator.BeginValidation(); } private void Validate(string propertyName) { Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(propertyName)); Validator validator; if (!_propertyValidators.TryGetValue(propertyName, out validator)) { return; } validator.BeginValidation(); } private void AddRule(string propertyName, Func<object> rule) { var validator = GetOrCreatePropertyValidator(propertyName); validator.AddRule(rule); validator.BeginValidation(); } private void AddRule(string propertyName, Func<CancellationToken, Task<object>> rule) { var validator = GetOrCreatePropertyValidator(propertyName); validator.AddRule(rule); validator.BeginValidation(); } private void AddObjectRule(Func<object> rule) { _objectValidator.AddRule(rule); _objectValidator.BeginValidation(); } private void AddObjectRule(Func<CancellationToken, Task<object>> rule) { _objectValidator.AddRule(rule); _objectValidator.BeginValidation(); } private void AlsoValidate(Expression<Func<object>> forProperty, Expression<Func<object>> alsoValidateProperty) { AfterNotify(forProperty) .Execute(() => Validate(alsoValidateProperty)); } private Validator GetOrCreatePropertyValidator(string propertyName) { Contract.Requires<ArgumentNullException>(propertyName != null); Validator validator; if (!_propertyValidators.TryGetValue(propertyName, out validator)) { validator = CreateNewValidator(propertyName); _propertyValidators.Add(propertyName, validator); } return validator; } private Validator CreateNewValidator(string propertyName) { var validator = new Validator(); validator.ValidationChanged += () => RaisePropertyErrorChanged(propertyName); return validator; } private void RaisePropertyErrorChanged(string propertyName) { UpdateHasErrors(); // Unsupported in 4.0 RaiseErrorsChanged(propertyName); } private class ValidationRuleAdder : IValidationRuleAdder { private readonly DataValidationInfo _dataValidationInfo; private readonly Expression<Func<object>> _property; private readonly string _propertyName; public ValidationRuleAdder(DataValidationInfo dataValidationInfo, Expression<Func<object>> property) { Contract.Requires<ArgumentNullException>(dataValidationInfo != null); Contract.Requires<ArgumentNullException>(property != null); _dataValidationInfo = dataValidationInfo; _property = property; _propertyName = _property.GetName(); Contract.Assume(!string.IsNullOrWhiteSpace(_propertyName)); } public IValidationRuleAdder AddValidationRule(Func<object> rule) { _dataValidationInfo.AddRule(_propertyName, rule); return this; } public IValidationRuleAdder AddAsyncValidationRule(Func<CancellationToken, Task<object>> asyncRule) { _dataValidationInfo.AddRule(_propertyName, asyncRule); return this; } public IValidationRuleAdder AlsoValidate(Expression<Func<object>> propertyName) { _dataValidationInfo.AlsoValidate(_property, propertyName); return this; } } private class ObjectValidationRuleAdder : IObjectValidationRuleAdder { private readonly DataValidationInfo _dataValidationInfo; public ObjectValidationRuleAdder(DataValidationInfo dataValidationInfo) { Contract.Requires<ArgumentNullException>(dataValidationInfo != null); _dataValidationInfo = dataValidationInfo; } public IObjectValidationRuleAdder AddValidationRule(Func<object> rule) { _dataValidationInfo.AddObjectRule(rule); return this; } public IObjectValidationRuleAdder AddAsyncValidationRule(Func<CancellationToken, Task<object>> asyncRule) { _dataValidationInfo.AddObjectRule(asyncRule); return this; } } [ContractClass(typeof(ContractValidationRuleAdder))] protected interface IValidationRuleAdder { IValidationRuleAdder AddValidationRule(Func<object> rule); IValidationRuleAdder AddAsyncValidationRule(Func<CancellationToken, Task<object>> asyncRule); IValidationRuleAdder AlsoValidate(Expression<Func<object>> propertyName); } [ContractClassFor(typeof(IValidationRuleAdder))] protected abstract class ContractValidationRuleAdder : IValidationRuleAdder { public IValidationRuleAdder AddValidationRule(Func<object> rule) { Contract.Requires<ArgumentNullException>(rule != null); Contract.Ensures(Contract.Result<IValidationRuleAdder>() != null); return default(IValidationRuleAdder); } public IValidationRuleAdder AddAsyncValidationRule(Func<CancellationToken, Task<object>> asyncRule) { Contract.Requires<ArgumentNullException>(asyncRule != null); Contract.Ensures(Contract.Result<IValidationRuleAdder>() != null); return default(IValidationRuleAdder); } public IValidationRuleAdder AlsoValidate(Expression<Func<object>> propertyName) { Contract.Requires<ArgumentNullException>(propertyName != null); Contract.Ensures(Contract.Result<IValidationRuleAdder>() != null); return default(IValidationRuleAdder); } } [ContractClass(typeof(ContractObjectValidationRuleAdder))] protected interface IObjectValidationRuleAdder { IObjectValidationRuleAdder AddValidationRule(Func<object> rule); IObjectValidationRuleAdder AddAsyncValidationRule(Func<CancellationToken, Task<object>> asyncRule); } [ContractClassFor(typeof(IObjectValidationRuleAdder))] protected abstract class ContractObjectValidationRuleAdder : IObjectValidationRuleAdder { public IObjectValidationRuleAdder AddValidationRule(Func<object> rule) { Contract.Requires<ArgumentNullException>(rule != null); Contract.Ensures(Contract.Result<IObjectValidationRuleAdder>() != null); return default(IObjectValidationRuleAdder); } public IObjectValidationRuleAdder AddAsyncValidationRule(Func<CancellationToken, Task<object>> asyncRule) { Contract.Requires<ArgumentNullException>(asyncRule != null); Contract.Ensures(Contract.Result<IObjectValidationRuleAdder>() != null); return default(IObjectValidationRuleAdder); } } private class Validator { private readonly List<Func<object>> _validateRules; private readonly List<Func<CancellationToken, Task<object>>> _asyncValidateRules; private CancellationTokenSource _cts; public event Action ValidationChanged; private void RaiseValidationChanged() { var handler = ValidationChanged; if (handler != null) { handler(); } } private void Cancel() { _cts.Cancel(); _cts = new CancellationTokenSource(); } private readonly List<object> _errors; public void AddRule(Func<object> rule) { Contract.Requires<ArgumentNullException>(rule != null); _validateRules.Add(rule); } public void AddRule(Func<CancellationToken, Task<object>> rule) { Contract.Requires<ArgumentNullException>(rule != null); _asyncValidateRules.Add(rule); } public bool HasErrors { get { return _errors.Any(); } } public IEnumerable GetErrors() { return _errors.Any() ? _errors : null; } public async void BeginValidation() { Cancel(); _errors.Clear(); ValidateSyncRules(); RaiseValidationChanged(); try { await ValidateAsyncRules(_cts.Token); } catch (OperationCanceledException) { } } private async Task ValidateAsyncRules(CancellationToken ct) { foreach (var rule in _asyncValidateRules) { var validationResult = await rule(ct); ct.ThrowIfCancellationRequested(); if (validationResult != null) { _errors.Add(validationResult); RaiseValidationChanged(); } } } private void ValidateSyncRules() { foreach (var rule in _validateRules) { var validationResult = rule(); if (validationResult != null) { _errors.Add(validationResult); } } } public Validator() { _validateRules = new List<Func<object>>(); _asyncValidateRules = new List<Func<CancellationToken, Task<object>>>(); _errors = new List<object>(); _cts = new CancellationTokenSource(); } } } }
using System; using System.Text; #if PSM using psmVector3 = Sce.PlayStation.Core.Vector3; #endif #if BEPU using BEPUphysics; using bepuVector3 = BEPUphysics.MathExtensions.Vector3D; #endif namespace CrossGraph.Math { public struct Vector3 : IEquatable<Vector3> { #region Private Fields private static Vector3 zero = new Vector3(0f, 0f, 0f); private static Vector3 one = new Vector3(1f, 1f, 1f); private static Vector3 unitX = new Vector3(1f, 0f, 0f); private static Vector3 unitY = new Vector3(0f, 1f, 0f); private static Vector3 unitZ = new Vector3(0f, 0f, 1f); private static Vector3 up = new Vector3(0f, 1f, 0f); private static Vector3 down = new Vector3(0f, -1f, 0f); private static Vector3 right = new Vector3(1f, 0f, 0f); private static Vector3 left = new Vector3(-1f, 0f, 0f); private static Vector3 forward = new Vector3(0f, 0f, -1f); private static Vector3 backward = new Vector3(0f, 0f, 1f); #endregion Private Fields #region Public Fields public float X; public float Y; public float Z; #endregion Public Fields #region Properties public static Vector3 Zero { get { return zero; } } public static Vector3 One { get { return one; } } public static Vector3 UnitX { get { return unitX; } } public static Vector3 UnitY { get { return unitY; } } public static Vector3 UnitZ { get { return unitZ; } } public static Vector3 Up { get { return up; } } public static Vector3 Down { get { return down; } } public static Vector3 Right { get { return right; } } public static Vector3 Left { get { return left; } } public static Vector3 Forward { get { return forward; } } public static Vector3 Backward { get { return backward; } } #endregion Properties #region Constructors public Vector3(float x, float y, float z) { this.X = x; this.Y = y; this.Z = z; } public Vector3(float value) { this.X = value; this.Y = value; this.Z = value; } public Vector3(Vector2 value, float z) { this.X = value.X; this.Y = value.Y; this.Z = z; } #endregion Constructors #region Public Methods public static Vector3 Add(Vector3 value1, Vector3 value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static void Add(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; result.Z = value1.Z + value2.Z; } public static Vector3 Barycentric(Vector3 value1, Vector3 value2, Vector3 value3, float amount1, float amount2) { return new Vector3( MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2), MathHelper.Barycentric(value1.Z, value2.Z, value3.Z, amount1, amount2)); } public static void Barycentric(ref Vector3 value1, ref Vector3 value2, ref Vector3 value3, float amount1, float amount2, out Vector3 result) { result = new Vector3( MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2), MathHelper.Barycentric(value1.Z, value2.Z, value3.Z, amount1, amount2)); } public static Vector3 CatmullRom(Vector3 value1, Vector3 value2, Vector3 value3, Vector3 value4, float amount) { return new Vector3( MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount), MathHelper.CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount)); } public static void CatmullRom(ref Vector3 value1, ref Vector3 value2, ref Vector3 value3, ref Vector3 value4, float amount, out Vector3 result) { result = new Vector3( MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount), MathHelper.CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount)); } public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) { return new Vector3( MathHelper.Clamp(value1.X, min.X, max.X), MathHelper.Clamp(value1.Y, min.Y, max.Y), MathHelper.Clamp(value1.Z, min.Z, max.Z)); } public static void Clamp(ref Vector3 value1, ref Vector3 min, ref Vector3 max, out Vector3 result) { result = new Vector3( MathHelper.Clamp(value1.X, min.X, max.X), MathHelper.Clamp(value1.Y, min.Y, max.Y), MathHelper.Clamp(value1.Z, min.Z, max.Z)); } public static Vector3 Cross(Vector3 vector1, Vector3 vector2) { Cross(ref vector1, ref vector2, out vector1); return vector1; } public static void Cross(ref Vector3 vector1, ref Vector3 vector2, out Vector3 result) { result = new Vector3(vector1.Y * vector2.Z - vector2.Y * vector1.Z, -(vector1.X * vector2.Z - vector2.X * vector1.Z), vector1.X * vector2.Y - vector2.X * vector1.Y); } public static float Distance(Vector3 vector1, Vector3 vector2) { float result; DistanceSquared(ref vector1, ref vector2, out result); return (float)System.Math.Sqrt(result); } public static void Distance(ref Vector3 value1, ref Vector3 value2, out float result) { DistanceSquared(ref value1, ref value2, out result); result = (float)System.Math.Sqrt(result); } public static float DistanceSquared(Vector3 value1, Vector3 value2) { float result; DistanceSquared(ref value1, ref value2, out result); return result; } public static void DistanceSquared(ref Vector3 value1, ref Vector3 value2, out float result) { result = (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } public static Vector3 Divide(Vector3 value1, Vector3 value2) { value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector3 Divide(Vector3 value1, float value2) { float factor = 1 / value2; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } public static void Divide(ref Vector3 value1, float divisor, out Vector3 result) { float factor = 1 / divisor; result.X = value1.X * factor; result.Y = value1.Y * factor; result.Z = value1.Z * factor; } public static void Divide(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result.X = value1.X / value2.X; result.Y = value1.Y / value2.Y; result.Z = value1.Z / value2.Z; } public static float Dot(Vector3 vector1, Vector3 vector2) { return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z; } public static void Dot(ref Vector3 vector1, ref Vector3 vector2, out float result) { result = vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z; } public override bool Equals(object obj) { if (!(obj is Vector3)) return false; var other = (Vector3)obj; return X == other.X && Y == other.Y && Z == other.Z; } public bool Equals(Vector3 other) { return X == other.X && Y == other.Y && Z == other.Z; } public override int GetHashCode() { return (int)(this.X + this.Y + this.Z); } public static Vector3 Hermite(Vector3 value1, Vector3 tangent1, Vector3 value2, Vector3 tangent2, float amount) { Vector3 result = new Vector3(); Hermite(ref value1, ref tangent1, ref value2, ref tangent2, amount, out result); return result; } public static void Hermite(ref Vector3 value1, ref Vector3 tangent1, ref Vector3 value2, ref Vector3 tangent2, float amount, out Vector3 result) { result.X = MathHelper.Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); result.Y = MathHelper.Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); result.Z = MathHelper.Hermite(value1.Z, tangent1.Z, value2.Z, tangent2.Z, amount); } public float Length() { float result; DistanceSquared(ref this, ref zero, out result); return (float)System.Math.Sqrt(result); } public float LengthSquared() { float result; DistanceSquared(ref this, ref zero, out result); return result; } public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) { return new Vector3( MathHelper.Lerp(value1.X, value2.X, amount), MathHelper.Lerp(value1.Y, value2.Y, amount), MathHelper.Lerp(value1.Z, value2.Z, amount)); } public static void Lerp(ref Vector3 value1, ref Vector3 value2, float amount, out Vector3 result) { result = new Vector3( MathHelper.Lerp(value1.X, value2.X, amount), MathHelper.Lerp(value1.Y, value2.Y, amount), MathHelper.Lerp(value1.Z, value2.Z, amount)); } public static Vector3 Max(Vector3 value1, Vector3 value2) { return new Vector3( MathHelper.Max(value1.X, value2.X), MathHelper.Max(value1.Y, value2.Y), MathHelper.Max(value1.Z, value2.Z)); } public static void Max(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result = new Vector3( MathHelper.Max(value1.X, value2.X), MathHelper.Max(value1.Y, value2.Y), MathHelper.Max(value1.Z, value2.Z)); } public static Vector3 Min(Vector3 value1, Vector3 value2) { return new Vector3( MathHelper.Min(value1.X, value2.X), MathHelper.Min(value1.Y, value2.Y), MathHelper.Min(value1.Z, value2.Z)); } public static void Min(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result = new Vector3( MathHelper.Min(value1.X, value2.X), MathHelper.Min(value1.Y, value2.Y), MathHelper.Min(value1.Z, value2.Z)); } public static Vector3 Multiply(Vector3 value1, Vector3 value2) { value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector3 Multiply(Vector3 value1, float scaleFactor) { value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static void Multiply(ref Vector3 value1, float scaleFactor, out Vector3 result) { result.X = value1.X * scaleFactor; result.Y = value1.Y * scaleFactor; result.Z = value1.Z * scaleFactor; } public static void Multiply(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result.X = value1.X * value2.X; result.Y = value1.Y * value2.Y; result.Z = value1.Z * value2.Z; } public static Vector3 Negate(Vector3 value) { value = new Vector3(-value.X, -value.Y, -value.Z); return value; } public static void Negate(ref Vector3 value, out Vector3 result) { result = new Vector3(-value.X, -value.Y, -value.Z); } public void Normalize() { Normalize(ref this, out this); } public static Vector3 Normalize(Vector3 vector) { Normalize(ref vector, out vector); return vector; } public static void Normalize(ref Vector3 value, out Vector3 result) { float factor; Distance(ref value, ref zero, out factor); factor = 1f / factor; result.X = value.X * factor; result.Y = value.Y * factor; result.Z = value.Z * factor; } public static Vector3 Reflect(Vector3 vector, Vector3 normal) { // I is the original array // N is the normal of the incident plane // R = I - (2 * N * ( DotProduct[ I,N] )) Vector3 reflectedVector; // inline the dotProduct here instead of calling method float dotProduct = ((vector.X * normal.X) + (vector.Y * normal.Y)) + (vector.Z * normal.Z); reflectedVector.X = vector.X - (2.0f * normal.X) * dotProduct; reflectedVector.Y = vector.Y - (2.0f * normal.Y) * dotProduct; reflectedVector.Z = vector.Z - (2.0f * normal.Z) * dotProduct; return reflectedVector; } public static void Reflect(ref Vector3 vector, ref Vector3 normal, out Vector3 result) { // I is the original array // N is the normal of the incident plane // R = I - (2 * N * ( DotProduct[ I,N] )) // inline the dotProduct here instead of calling method float dotProduct = ((vector.X * normal.X) + (vector.Y * normal.Y)) + (vector.Z * normal.Z); result.X = vector.X - (2.0f * normal.X) * dotProduct; result.Y = vector.Y - (2.0f * normal.Y) * dotProduct; result.Z = vector.Z - (2.0f * normal.Z) * dotProduct; } public static Vector3 SmoothStep(Vector3 value1, Vector3 value2, float amount) { return new Vector3( MathHelper.SmoothStep(value1.X, value2.X, amount), MathHelper.SmoothStep(value1.Y, value2.Y, amount), MathHelper.SmoothStep(value1.Z, value2.Z, amount)); } public static void SmoothStep(ref Vector3 value1, ref Vector3 value2, float amount, out Vector3 result) { result = new Vector3( MathHelper.SmoothStep(value1.X, value2.X, amount), MathHelper.SmoothStep(value1.Y, value2.Y, amount), MathHelper.SmoothStep(value1.Z, value2.Z, amount)); } public static Vector3 Subtract(Vector3 value1, Vector3 value2) { value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static void Subtract(ref Vector3 value1, ref Vector3 value2, out Vector3 result) { result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; result.Z = value1.Z - value2.Z; } public override string ToString() { StringBuilder sb = new StringBuilder(32); sb.Append("{X:"); sb.Append(this.X); sb.Append(" Y:"); sb.Append(this.Y); sb.Append(" Z:"); sb.Append(this.Z); sb.Append("}"); return sb.ToString(); } public static Vector3 Transform(Vector3 position, Matrix matrix) { Transform(ref position, ref matrix, out position); return position; } public static void Transform(ref Vector3 position, ref Matrix matrix, out Vector3 result) { result = new Vector3((position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43); } public static void Transform(Vector3[] sourceArray, ref Matrix matrix, Vector3[] destinationArray) { ////Debug.Assert(destinationArray.Length >= sourceArray.Length, "The destination array is smaller than the source array."); // TODO: Are there options on some platforms to implement a vectorized version of this? for (var i = 0; i < sourceArray.Length; i++) { var position = sourceArray[i]; destinationArray[i] = new Vector3( (position.X*matrix.M11) + (position.Y*matrix.M21) + (position.Z*matrix.M31) + matrix.M41, (position.X*matrix.M12) + (position.Y*matrix.M22) + (position.Z*matrix.M32) + matrix.M42, (position.X*matrix.M13) + (position.Y*matrix.M23) + (position.Z*matrix.M33) + matrix.M43); } } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector3 Transform(Vector3 vec, Quaternion quat) { Vector3 result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> // public static void Transform(ref Vector3 vec, ref Quaternion quat, out Vector3 result) // { // // Taken from the OpentTK implementation of Vector3 // // Since vec.W == 0, we can optimize quat * vec * quat^-1 as follows: // // vec + 2.0 * cross(quat.xyz, cross(quat.xyz, vec) + quat.w * vec) // Vector3 xyz = quat.Xyz, temp, temp2; // Vector3.Cross(ref xyz, ref vec, out temp); // Vector3.Multiply(ref vec, quat.W, out temp2); // Vector3.Add(ref temp, ref temp2, out temp); // Vector3.Cross(ref xyz, ref temp, out temp); // Vector3.Multiply(ref temp, 2, out temp); // Vector3.Add(ref vec, ref temp, out result); // } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector3 value, ref Quaternion rotation, out Vector3 result) { float x = 2 * (rotation.Y * value.Z - rotation.Z * value.Y); float y = 2 * (rotation.Z * value.X - rotation.X * value.Z); float z = 2 * (rotation.X * value.Y - rotation.Y * value.X); result.X = value.X + x * rotation.W + (rotation.Y * z - rotation.Z * y); result.Y = value.Y + y * rotation.W + (rotation.Z * x - rotation.X * z); result.Z = value.Z + z * rotation.W + (rotation.X * y - rotation.Y * x); } /// <summary> /// Transforms an array of vectors by a quaternion rotation. /// </summary> /// <param name="sourceArray">The vectors to transform</param> /// <param name="rotation">The quaternion to rotate the vector by.</param> /// <param name="destinationArray">The result of the operation.</param> public static void Transform(Vector3[] sourceArray, ref Quaternion rotation, Vector3[] destinationArray) { //Debug.Assert(destinationArray.Length >= sourceArray.Length, "The destination array is smaller than the source array."); // TODO: Are there options on some platforms to implement a vectorized version of this? for (var i = 0; i < sourceArray.Length; i++) { var position = sourceArray[i]; float x = 2 * (rotation.Y * position.Z - rotation.Z * position.Y); float y = 2 * (rotation.Z * position.X - rotation.X * position.Z); float z = 2 * (rotation.X * position.Y - rotation.Y * position.X); destinationArray[i] = new Vector3( position.X + x * rotation.W + (rotation.Y * z - rotation.Z * y), position.Y + y * rotation.W + (rotation.Z * x - rotation.X * z), position.Z + z * rotation.W + (rotation.X * y - rotation.Y * x)); } } public static Vector3 TransformNormal(Vector3 normal, Matrix matrix) { TransformNormal(ref normal, ref matrix, out normal); return normal; } public static void TransformNormal(ref Vector3 normal, ref Matrix matrix, out Vector3 result) { result = new Vector3((normal.X * matrix.M11) + (normal.Y * matrix.M21) + (normal.Z * matrix.M31), (normal.X * matrix.M12) + (normal.Y * matrix.M22) + (normal.Z * matrix.M32), (normal.X * matrix.M13) + (normal.Y * matrix.M23) + (normal.Z * matrix.M33)); } #endregion Public methods #region Operators public static bool operator ==(Vector3 value1, Vector3 value2) { return value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z; } public static bool operator !=(Vector3 value1, Vector3 value2) { return !(value1 == value2); } public static Vector3 operator +(Vector3 value1, Vector3 value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector3 operator -(Vector3 value) { value = new Vector3(-value.X, -value.Y, -value.Z); return value; } public static Vector3 operator -(Vector3 value1, Vector3 value2) { value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector3 operator *(Vector3 value1, Vector3 value2) { value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector3 operator *(Vector3 value, float scaleFactor) { value.X *= scaleFactor; value.Y *= scaleFactor; value.Z *= scaleFactor; return value; } public static Vector3 operator *(float scaleFactor, Vector3 value) { value.X *= scaleFactor; value.Y *= scaleFactor; value.Z *= scaleFactor; return value; } public static Vector3 operator /(Vector3 value1, Vector3 value2) { value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector3 operator /(Vector3 value, float divider) { float factor = 1 / divider; value.X *= factor; value.Y *= factor; value.Z *= factor; return value; } #if PSM public static implicit operator psmVector3 (Vector3 a) { return new psmVector3(a.X, a.Y, a.Z); } public static implicit operator Vector3 (psmVector3 a) { return new Vector3(a.X, a.Y, a.Z); } #elif OPENTK public static implicit operator OpenTK.Vector3(Vector3 a) { return new OpenTK.Vector3(a.X, a.Y, a.Z); } public static implicit operator Vector3(OpenTK.Vector3 a) { return new Vector3(a.X, a.Y, a.Z); } #endif #if BEPU public static implicit operator bepuVector3 (Vector3 a) { return new bepuVector3(a.X, a.Y, a.Z); } public static implicit operator Vector3 (bepuVector3 a) { return new Vector3(a.X, a.Y, a.Z); } #endif #endregion } }
using System; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Streams; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace UnitTests.StreamingTests { [TestCategory("Streaming")] public class SampleSmsStreamingTests : OrleansTestingBase, IClassFixture<SampleSmsStreamingTests.Fixture> { private readonly Fixture fixture; private Logger logger; public class Fixture : BaseTestClusterFixture { protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(2); options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore"); options.ClusterConfiguration.AddSimpleMessageStreamProvider(StreamProvider, false); options.ClientConfiguration.AddSimpleMessageStreamProvider(StreamProvider, false); return new TestCluster(options); } } private const string StreamProvider = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; public SampleSmsStreamingTests(Fixture fixture) { this.fixture = fixture; logger = this.fixture.Logger; } [Fact, TestCategory("BVT"), TestCategory("Functional")] public void SampleStreamingTests_StreamTypeMismatch_ShouldThrowOrleansException() { var streamId = Guid.NewGuid(); var streamNameSpace = "SmsStream"; var stream = this.fixture.Client.GetStreamProvider(StreamProvider).GetStream<int>(streamId, streamNameSpace); Assert.Throws<Orleans.Runtime.OrleansException>(() => { this.fixture.Client.GetStreamProvider(StreamProvider).GetStream<string>(streamId, streamNameSpace); }); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task SampleStreamingTests_1() { this.logger.Info("************************ SampleStreamingTests_1 *********************************"); var runner = new SampleStreamingTests(StreamProvider, this.logger, this.fixture.HostedCluster); await runner.StreamingTests_Consumer_Producer(Guid.NewGuid()); } [Fact, TestCategory("Functional")] public async Task SampleStreamingTests_2() { this.logger.Info("************************ SampleStreamingTests_2 *********************************"); var runner = new SampleStreamingTests(StreamProvider, this.logger, this.fixture.HostedCluster); await runner.StreamingTests_Producer_Consumer(Guid.NewGuid()); } [Fact, TestCategory("Functional")] public async Task SampleStreamingTests_3() { this.logger.Info("************************ SampleStreamingTests_3 *********************************"); var runner = new SampleStreamingTests(StreamProvider, this.logger, this.fixture.HostedCluster); await runner.StreamingTests_Producer_InlineConsumer(Guid.NewGuid()); } [Fact, TestCategory("Functional")] public async Task MultipleImplicitSubscriptionTest() { this.logger.Info("************************ MultipleImplicitSubscriptionTest *********************************"); var streamId = Guid.NewGuid(); const int nRedEvents = 5, nBlueEvents = 3; var provider = this.fixture.HostedCluster.StreamProviderManager.GetStreamProvider(StreamTestsConstants.SMS_STREAM_PROVIDER_NAME); var redStream = provider.GetStream<int>(streamId, "red"); var blueStream = provider.GetStream<int>(streamId, "blue"); for (int i = 0; i < nRedEvents; i++) await redStream.OnNextAsync(i); for (int i = 0; i < nBlueEvents; i++) await blueStream.OnNextAsync(i); var grain = this.fixture.GrainFactory.GetGrain<IMultipleImplicitSubscriptionGrain>(streamId); var counters = await grain.GetCounters(); Assert.Equal(nRedEvents, counters.Item1); Assert.Equal(nBlueEvents, counters.Item2); } [Fact, TestCategory("Functional")] public async Task FilteredImplicitSubscriptionGrainTest() { this.logger.Info($"************************ {nameof(FilteredImplicitSubscriptionGrainTest)} *********************************"); var streamNamespaces = new[] { "red1", "red2", "blue3", "blue4" }; var events = new[] { 3, 5, 2, 4 }; var testData = streamNamespaces.Zip(events, (s, e) => new { Namespace = s, Events = e, StreamId = Guid.NewGuid() }).ToList(); var provider = fixture.HostedCluster.StreamProviderManager.GetStreamProvider(StreamTestsConstants.SMS_STREAM_PROVIDER_NAME); foreach (var item in testData) { var stream = provider.GetStream<int>(item.StreamId, item.Namespace); for (int i = 0; i < item.Events; i++) await stream.OnNextAsync(i); } foreach (var item in testData) { var grain = this.fixture.GrainFactory.GetGrain<IFilteredImplicitSubscriptionGrain>(item.StreamId); var actual = await grain.GetCounter(item.Namespace); var expected = item.Namespace.StartsWith("red") ? item.Events : 0; Assert.Equal(expected, actual); } } [Fact, TestCategory("Functional")] public async Task FilteredImplicitSubscriptionWithExtensionGrainTest() { logger.Info($"************************ {nameof(FilteredImplicitSubscriptionWithExtensionGrainTest)} *********************************"); var redEvents = new[] { 3, 5, 2, 4 }; var blueEvents = new[] { 7, 3, 6 }; var streamId = Guid.NewGuid(); var provider = fixture.HostedCluster.StreamProviderManager.GetStreamProvider(StreamTestsConstants.SMS_STREAM_PROVIDER_NAME); for (int i = 0; i < redEvents.Length; i++) { var stream = provider.GetStream<int>(streamId, "red" + i); for (int j = 0; j < redEvents[i]; j++) await stream.OnNextAsync(j); } for (int i = 0; i < blueEvents.Length; i++) { var stream = provider.GetStream<int>(streamId, "blue" + i); for (int j = 0; j < blueEvents[i]; j++) await stream.OnNextAsync(j); } for (int i = 0; i < redEvents.Length; i++) { var grain = this.fixture.GrainFactory.GetGrain<IFilteredImplicitSubscriptionWithExtensionGrain>( streamId, "red" + i, null); var actual = await grain.GetCounter(); Assert.Equal(redEvents[i], actual); } for (int i = 0; i < blueEvents.Length; i++) { var grain = this.fixture.GrainFactory.GetGrain<IFilteredImplicitSubscriptionWithExtensionGrain>( streamId, "blue" + i, null); var actual = await grain.GetCounter(); Assert.Equal(0, actual); } } } public class SampleStreamingTests { private const string StreamNamespace = "SampleStreamNamespace"; private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30); private readonly string streamProvider; private readonly Logger logger; private readonly TestCluster cluster; public SampleStreamingTests(string streamProvider, Logger logger, TestCluster cluster) { this.streamProvider = streamProvider; this.logger = logger; this.cluster = cluster; } public async Task StreamingTests_Consumer_Producer(Guid streamId) { // consumer joins first, producer later var consumer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid()); await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider); var producer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamId, StreamNamespace, streamProvider); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout); await consumer.StopConsuming(); } public async Task StreamingTests_Producer_Consumer(Guid streamId) { // producer joins first, consumer later var producer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamId, StreamNamespace, streamProvider); var consumer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid()); await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); //int numProduced = await producer.NumberProduced; await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout); await consumer.StopConsuming(); } public async Task StreamingTests_Producer_InlineConsumer(Guid streamId) { // producer joins first, consumer later var producer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamId, StreamNamespace, streamProvider); var consumer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_InlineConsumerGrain>(Guid.NewGuid()); await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); //int numProduced = await producer.NumberProduced; await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout); await consumer.StopConsuming(); } private async Task<bool> CheckCounters(ISampleStreaming_ProducerGrain producer, ISampleStreaming_ConsumerGrain consumer, bool assertIsTrue) { var numProduced = await producer.GetNumberProduced(); var numConsumed = await consumer.GetNumberConsumed(); this.logger.Info("CheckCounters: numProduced = {0}, numConsumed = {1}", numProduced, numConsumed); if (assertIsTrue) { Assert.Equal(numProduced, numConsumed); return true; } else { return numProduced == numConsumed; } } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { internal interface IContentFocusManager { void Activate(IDockContent content); void GiveUpFocus(IDockContent content); void AddToList(IDockContent content); void RemoveFromList(IDockContent content); } partial class DockPanel { private interface IFocusManager { void SuspendFocusTracking(); void ResumeFocusTracking(); bool IsFocusTrackingSuspended { get; } IDockContent ActiveContent { get; } DockPane ActivePane { get; } IDockContent ActiveDocument { get; } DockPane ActiveDocumentPane { get; } } private class FocusManagerImpl : Component, IContentFocusManager, IFocusManager { private class HookEventArgs : EventArgs { [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] public int HookCode; [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] public IntPtr wParam; public IntPtr lParam; } private class LocalWindowsHook : IDisposable { // Internal properties private IntPtr m_hHook = IntPtr.Zero; private NativeMethods.HookProc m_filterFunc = null; private Win32.HookType m_hookType; // Event delegate public delegate void HookEventHandler(object sender, HookEventArgs e); // Event: HookInvoked public event HookEventHandler HookInvoked; protected void OnHookInvoked(HookEventArgs e) { if (HookInvoked != null) HookInvoked(this, e); } public LocalWindowsHook(Win32.HookType hook) { m_hookType = hook; m_filterFunc = new NativeMethods.HookProc(this.CoreHookProc); } // Default filter function public IntPtr CoreHookProc(int code, IntPtr wParam, IntPtr lParam) { if (code < 0) return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam); // Let clients determine what to do HookEventArgs e = new HookEventArgs(); e.HookCode = code; e.wParam = wParam; e.lParam = lParam; OnHookInvoked(e); // Yield to the next hook in the chain return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam); } // Install the hook public void Install() { if (m_hHook != IntPtr.Zero) Uninstall(); int threadId = NativeMethods.GetCurrentThreadId(); m_hHook = NativeMethods.SetWindowsHookEx(m_hookType, m_filterFunc, IntPtr.Zero, threadId); } // Uninstall the hook public void Uninstall() { if (m_hHook != IntPtr.Zero) { NativeMethods.UnhookWindowsHookEx(m_hHook); m_hHook = IntPtr.Zero; } } ~LocalWindowsHook() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Uninstall(); } } private LocalWindowsHook m_localWindowsHook; private LocalWindowsHook.HookEventHandler m_hookEventHandler; public FocusManagerImpl(DockPanel dockPanel) { m_dockPanel = dockPanel; m_localWindowsHook = new LocalWindowsHook(Win32.HookType.WH_CALLWNDPROCRET); m_hookEventHandler = new LocalWindowsHook.HookEventHandler(HookEventHandler); m_localWindowsHook.HookInvoked += m_hookEventHandler; m_localWindowsHook.Install(); } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } private bool m_disposed = false; protected override void Dispose(bool disposing) { lock (this) { if (!m_disposed && disposing) { m_localWindowsHook.Dispose(); m_disposed = true; } base.Dispose(disposing); } } private IDockContent m_contentActivating = null; private IDockContent ContentActivating { get { return m_contentActivating; } set { m_contentActivating = value; } } public void Activate(IDockContent content) { if (IsFocusTrackingSuspended) { ContentActivating = content; return; } DockContentHandler handler = content.DockHandler; if (ContentContains(content, handler.ActiveWindowHandle)) NativeMethods.SetFocus(handler.ActiveWindowHandle); if (!handler.Form.ContainsFocus && handler.Form.ActiveControl != null) { if (!handler.Form.SelectNextControl(handler.Form.ActiveControl, true, true, true, true)) // Since DockContent Form is not selectalbe, use Win32 SetFocus instead NativeMethods.SetFocus(handler.Form.Handle); } } private List<IDockContent> m_listContent = new List<IDockContent>(); private List<IDockContent> ListContent { get { return m_listContent; } } public void AddToList(IDockContent content) { if (ListContent.Contains(content) || IsInActiveList(content)) return; ListContent.Add(content); } public void RemoveFromList(IDockContent content) { if (IsInActiveList(content)) RemoveFromActiveList(content); if (ListContent.Contains(content)) ListContent.Remove(content); } private IDockContent m_lastActiveContent = null; private IDockContent LastActiveContent { get { return m_lastActiveContent; } set { m_lastActiveContent = value; } } private bool IsInActiveList(IDockContent content) { return !(content.DockHandler.NextActive == null && LastActiveContent != content); } private void AddLastToActiveList(IDockContent content) { IDockContent last = LastActiveContent; if (last == content) return; DockContentHandler handler = content.DockHandler; if (IsInActiveList(content)) RemoveFromActiveList(content); handler.PreviousActive = last; handler.NextActive = null; LastActiveContent = content; if (last != null) last.DockHandler.NextActive = LastActiveContent; } private void RemoveFromActiveList(IDockContent content) { if (LastActiveContent == content) LastActiveContent = content.DockHandler.PreviousActive; IDockContent prev = content.DockHandler.PreviousActive; IDockContent next = content.DockHandler.NextActive; if (prev != null) prev.DockHandler.NextActive = next; if (next != null) next.DockHandler.PreviousActive = prev; content.DockHandler.PreviousActive = null; content.DockHandler.NextActive = null; } public void GiveUpFocus(IDockContent content) { DockContentHandler handler = content.DockHandler; if (!handler.Form.ContainsFocus) return; if (IsFocusTrackingSuspended) DockPanel.DummyControl.Focus(); if (LastActiveContent == content) { IDockContent prev = handler.PreviousActive; if (prev != null) prev.DockHandler.Activate(); else if (ListContent.Count > 0) ListContent[ListContent.Count - 1].DockHandler.Activate(); } else if (LastActiveContent != null) LastActiveContent.DockHandler.Activate(); else if (ListContent.Count > 0) ListContent[ListContent.Count - 1].DockHandler.Activate(); } private static bool ContentContains(IDockContent content, IntPtr hWnd) { Control control = Control.FromChildHandle(hWnd); for (Control parent = control; parent != null; parent = parent.Parent) if (parent == content.DockHandler.Form) return true; return false; } private int m_countSuspendFocusTracking = 0; public void SuspendFocusTracking() { m_countSuspendFocusTracking++; m_localWindowsHook.HookInvoked -= m_hookEventHandler; } public void ResumeFocusTracking() { if (m_countSuspendFocusTracking > 0) m_countSuspendFocusTracking--; if (m_countSuspendFocusTracking == 0) { if (ContentActivating != null) { Activate(ContentActivating); ContentActivating = null; } m_localWindowsHook.HookInvoked += m_hookEventHandler; if (!InRefreshActiveWindow) RefreshActiveWindow(); } } public bool IsFocusTrackingSuspended { get { return m_countSuspendFocusTracking != 0; } } // Windows hook event handler private void HookEventHandler(object sender, HookEventArgs e) { Win32.Msgs msg = (Win32.Msgs)Marshal.ReadInt32(e.lParam, IntPtr.Size * 3); if (msg == Win32.Msgs.WM_KILLFOCUS) { IntPtr wParam = Marshal.ReadIntPtr(e.lParam, IntPtr.Size * 2); DockPane pane = GetPaneFromHandle(wParam); if (pane == null) RefreshActiveWindow(); } else if (msg == Win32.Msgs.WM_SETFOCUS) RefreshActiveWindow(); } private DockPane GetPaneFromHandle(IntPtr hWnd) { Control control = Control.FromChildHandle(hWnd); IDockContent content = null; DockPane pane = null; for (; control != null; control = control.Parent) { content = control as IDockContent; if (content != null) content.DockHandler.ActiveWindowHandle = hWnd; if (content != null && content.DockHandler.DockPanel == DockPanel) return content.DockHandler.Pane; pane = control as DockPane; if (pane != null && pane.DockPanel == DockPanel) break; } return pane; } private bool m_inRefreshActiveWindow = false; private bool InRefreshActiveWindow { get { return m_inRefreshActiveWindow; } } private void RefreshActiveWindow() { SuspendFocusTracking(); m_inRefreshActiveWindow = true; DockPane oldActivePane = ActivePane; IDockContent oldActiveContent = ActiveContent; IDockContent oldActiveDocument = ActiveDocument; SetActivePane(); SetActiveContent(); SetActiveDocumentPane(); SetActiveDocument(); DockPanel.AutoHideWindow.RefreshActivePane(); ResumeFocusTracking(); m_inRefreshActiveWindow = false; if (oldActiveContent != ActiveContent) DockPanel.OnActiveContentChanged(EventArgs.Empty); if (oldActiveDocument != ActiveDocument) DockPanel.OnActiveDocumentChanged(EventArgs.Empty); if (oldActivePane != ActivePane) DockPanel.OnActivePaneChanged(EventArgs.Empty); } private DockPane m_activePane = null; public DockPane ActivePane { get { return m_activePane; } } private void SetActivePane() { DockPane value = GetPaneFromHandle(NativeMethods.GetFocus()); if (m_activePane == value) return; if (m_activePane != null) m_activePane.SetIsActivated(false); m_activePane = value; if (m_activePane != null) m_activePane.SetIsActivated(true); } private IDockContent m_activeContent = null; public IDockContent ActiveContent { get { return m_activeContent; } } internal void SetActiveContent() { IDockContent value = ActivePane == null ? null : ActivePane.ActiveContent; if (m_activeContent == value) return; if (m_activeContent != null) m_activeContent.DockHandler.IsActivated = false; m_activeContent = value; if (m_activeContent != null) { m_activeContent.DockHandler.IsActivated = true; if (!DockHelper.IsDockStateAutoHide((m_activeContent.DockHandler.DockState))) AddLastToActiveList(m_activeContent); } } private DockPane m_activeDocumentPane = null; public DockPane ActiveDocumentPane { get { return m_activeDocumentPane; } } private void SetActiveDocumentPane() { DockPane value = null; if (ActivePane != null && ActivePane.DockState == DockState.Document) value = ActivePane; if (value == null) { if (ActiveDocumentPane == null) value = DockPanel.DockWindows[DockState.Document].DefaultPane; else if (ActiveDocumentPane.DockPanel != DockPanel || ActiveDocumentPane.DockState != DockState.Document) value = DockPanel.DockWindows[DockState.Document].DefaultPane; else value = ActiveDocumentPane; } if (m_activeDocumentPane == value) return; if (m_activeDocumentPane != null) m_activeDocumentPane.SetIsActiveDocumentPane(false); m_activeDocumentPane = value; if (m_activeDocumentPane != null) m_activeDocumentPane.SetIsActiveDocumentPane(true); } private IDockContent m_activeDocument = null; public IDockContent ActiveDocument { get { return m_activeDocument; } } private void SetActiveDocument() { IDockContent value = ActiveDocumentPane == null ? null : ActiveDocumentPane.ActiveContent; if (m_activeDocument == value) return; m_activeDocument = value; } } private IFocusManager FocusManager { get { return m_focusManager; } } internal IContentFocusManager ContentFocusManager { get { return m_focusManager; } } internal void SaveFocus() { DummyControl.Focus(); } [Browsable(false)] public IDockContent ActiveContent { get { return FocusManager.ActiveContent; } } [Browsable(false)] public DockPane ActivePane { get { return FocusManager.ActivePane; } } [Browsable(false)] public IDockContent ActiveDocument { get { return FocusManager.ActiveDocument; } } [Browsable(false)] public DockPane ActiveDocumentPane { get { return FocusManager.ActiveDocumentPane; } } private static readonly object ActiveDocumentChangedEvent = new object(); [LocalizedCategory("Category_PropertyChanged")] [LocalizedDescription("DockPanel_ActiveDocumentChanged_Description")] public event EventHandler ActiveDocumentChanged { add { Events.AddHandler(ActiveDocumentChangedEvent, value); } remove { Events.RemoveHandler(ActiveDocumentChangedEvent, value); } } protected virtual void OnActiveDocumentChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[ActiveDocumentChangedEvent]; if (handler != null) handler(this, e); } private static readonly object ActiveContentChangedEvent = new object(); [LocalizedCategory("Category_PropertyChanged")] [LocalizedDescription("DockPanel_ActiveContentChanged_Description")] public event EventHandler ActiveContentChanged { add { Events.AddHandler(ActiveContentChangedEvent, value); } remove { Events.RemoveHandler(ActiveContentChangedEvent, value); } } protected void OnActiveContentChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent]; if (handler != null) handler(this, e); } private static readonly object ActivePaneChangedEvent = new object(); [LocalizedCategory("Category_PropertyChanged")] [LocalizedDescription("DockPanel_ActivePaneChanged_Description")] public event EventHandler ActivePaneChanged { add { Events.AddHandler(ActivePaneChangedEvent, value); } remove { Events.RemoveHandler(ActivePaneChangedEvent, value); } } protected virtual void OnActivePaneChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[ActivePaneChangedEvent]; if (handler != null) handler(this, e); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; using NLog.Targets; namespace NLog.UnitTests.LogReceiverService { using System.Collections.Generic; using System.Linq; using System.Threading; using System; using System.IO; using Xunit; using System.Data; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Description; using System.Xml; using System.Xml.Serialization; using NLog.Layouts; using NLog.LogReceiverService; public class LogReceiverServiceTests : NLogTestBase { private const string logRecieverUrl = "http://localhost:8080/logrecievertest"; #if !NETSTANDARD || WCF_SUPPORTED [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] [InlineData("message1")] public void TranslateEventAndBack(string message) { // Arrange var service = new LogReceiverWebServiceTarget {IncludeEventProperties = true}; var logEvent = new LogEventInfo(LogLevel.Debug, "logger1", message); var nLogEvents = new NLogEvents { Strings = new StringCollection(), LayoutNames = new StringCollection(), BaseTimeUtc = DateTime.UtcNow.Ticks, ClientName = "client1", Events = new NLogEvent[0] }; var dict2 = new Dictionary<string, int>(); // Act var translateEvent = service.TranslateEvent(logEvent, nLogEvents, dict2); var result = translateEvent.ToEventInfo(nLogEvents, ""); // Assert Assert.Equal("logger1", result.LoggerName); Assert.Equal(message, result.Message); } #endif [Fact] public void ToLogEventInfoTest() { var events = new NLogEvents { BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks, ClientName = "foo", LayoutNames = new StringCollection { "foo", "bar", "baz" }, Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 30000000, MessageOrdinal = 4, Values = "0|1|2" }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, MessageOrdinal = 4, TimeDelta = 30050000, Values = "0|1|3", } } }; var converted = events.ToEventInfo(); Assert.Equal(2, converted.Count); Assert.Equal("message1", converted[0].FormattedMessage); Assert.Equal("message1", converted[1].FormattedMessage); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime()); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime()); Assert.Equal("logger1", converted[0].LoggerName); Assert.Equal("logger3", converted[1].LoggerName); Assert.Equal(LogLevel.Info, converted[0].Level); Assert.Equal(LogLevel.Warn, converted[1].Level); Layout fooLayout = "${event-context:foo}"; Layout barLayout = "${event-context:bar}"; Layout bazLayout = "${event-context:baz}"; Assert.Equal("logger1", fooLayout.Render(converted[0])); Assert.Equal("logger1", fooLayout.Render(converted[1])); Assert.Equal("logger2", barLayout.Render(converted[0])); Assert.Equal("logger2", barLayout.Render(converted[1])); Assert.Equal("logger3", bazLayout.Render(converted[0])); Assert.Equal("zzz", bazLayout.Render(converted[1])); } [Fact] public void NoLayoutsTest() { var events = new NLogEvents { BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks, ClientName = "foo", LayoutNames = new StringCollection(), Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 30000000, MessageOrdinal = 4, Values = null, }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, MessageOrdinal = 4, TimeDelta = 30050000, Values = null, } } }; var converted = events.ToEventInfo(); Assert.Equal(2, converted.Count); Assert.Equal("message1", converted[0].FormattedMessage); Assert.Equal("message1", converted[1].FormattedMessage); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime()); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime()); Assert.Equal("logger1", converted[0].LoggerName); Assert.Equal("logger3", converted[1].LoggerName); Assert.Equal(LogLevel.Info, converted[0].Level); Assert.Equal(LogLevel.Warn, converted[1].Level); } /// <summary> /// Ensures that serialization formats of DataContractSerializer and XmlSerializer are the same /// on the same <see cref="NLogEvents"/> object. /// </summary> [Fact] public void CompareSerializationFormats() { var events = new NLogEvents { BaseTimeUtc = DateTime.UtcNow.Ticks, ClientName = "foo", LayoutNames = new StringCollection { "foo", "bar", "baz" }, Strings = new StringCollection { "logger1", "logger2", "logger3" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 34, Values = "1|2|3" }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, TimeDelta = 345, Values = "1|2|3", } } }; var serializer1 = new XmlSerializer(typeof(NLogEvents)); var sw1 = new StringWriter(); using (var writer1 = XmlWriter.Create(sw1, new XmlWriterSettings { Indent = true })) { var namespaces = new XmlSerializerNamespaces(); namespaces.Add("i", "http://www.w3.org/2001/XMLSchema-instance"); serializer1.Serialize(writer1, events, namespaces); } var serializer2 = new DataContractSerializer(typeof(NLogEvents)); var sw2 = new StringWriter(); using (var writer2 = XmlWriter.Create(sw2, new XmlWriterSettings { Indent = true })) { serializer2.WriteObject(writer2, events); } var xml1 = sw1.ToString(); var xml2 = sw2.ToString(); Assert.Equal(xml1, xml2); } #if !NETSTANDARD #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void RealTestLogReciever_two_way() { RealTestLogReciever(false, false); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void RealTestLogReciever_one_way() { RealTestLogReciever(true, false); } [Fact(Skip = "unit test should listen to non-http for this")] public void RealTestLogReciever_two_way_binary() { RealTestLogReciever(false, true); } [Fact(Skip = "unit test should listen to non-http for this")] public void RealTestLogReciever_one_way_binary() { RealTestLogReciever(true, true); } private void RealTestLogReciever(bool useOneWayContract, bool binaryEncode) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString($@" <nlog throwExceptions='true'> <targets> <target type='LogReceiverService' name='s1' endpointAddress='{logRecieverUrl}' useOneWayContract='{useOneWayContract.ToString().ToLower()}' useBinaryEncoding='{binaryEncode.ToString().ToLower()}' includeEventProperties='false'> <!-- <parameter name='key1' layout='testparam1' type='String'/> --> </target> </targets> <rules> <logger name='logger1' minlevel='Trace' writeTo='s1' /> </rules> </nlog>"); ExecLogRecieverAndCheck(ExecLogging1, CheckReceived1, 2); } /// <summary> /// Create WCF service, logs and listen to the events /// </summary> /// <param name="logFunc">function for logging the messages</param> /// <param name="logCheckFunc">function for checking the received messages</param> /// <param name="messageCount">message count for wait for listen and checking</param> private void ExecLogRecieverAndCheck(Action<Logger> logFunc, Action<List<NLogEvents>> logCheckFunc, int messageCount) { Uri baseAddress = new Uri(logRecieverUrl); // Create the ServiceHost. var countdownEvent = new CountdownEvent(messageCount); var logReceiverMock = new LogReceiverMock(countdownEvent); using (ServiceHost host = new ServiceHost(logReceiverMock, baseAddress)) { var behaviour = host.Description.Behaviors.Find<ServiceBehaviorAttribute>(); behaviour.InstanceContextMode = InstanceContextMode.Single; // Enable metadata publishing. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; #if !MONO smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; #endif host.Description.Behaviors.Add(smb); // Open the ServiceHost to start listening for messages. Since // no endpoints are explicitly configured, the runtime will create // one endpoint per base address for each service contract implemented // by the service. host.Open(); //wait for 2 events var logger1 = LogManager.GetLogger("logger1"); logFunc(logger1); countdownEvent.Wait(20000); var received = logReceiverMock.ReceivedEvents; Assert.Equal(messageCount, received.Count); logCheckFunc(received); // Close the ServiceHost. host.Close(); } } private static void CheckReceived1(List<NLogEvents> received) { //in some case the messages aren't retrieved in the right order when invoked in the same sec. //more important is that both are retrieved with the correct info Assert.Equal(2, received.Count); var logmessages = new HashSet<string> { received[0].ToEventInfo().First().Message, received[1].ToEventInfo().First().Message }; Assert.True(logmessages.Contains("test 1"), "message 1 is missing"); Assert.True(logmessages.Contains("test 2"), "message 2 is missing"); } private static void ExecLogging1(Logger logger) { logger.Info("test 1"); //we wait 10 ms, because after a cold boot, the messages are arrived in the same moment and the order can change. Thread.Sleep(10); logger.Info(new InvalidConstraintException("boo"), "test 2"); } public class LogReceiverMock : ILogReceiverServer, ILogReceiverOneWayServer { public CountdownEvent CountdownEvent { get; } /// <inheritdoc /> public LogReceiverMock(CountdownEvent countdownEvent) { CountdownEvent = countdownEvent; } public List<NLogEvents> ReceivedEvents { get; } = new List<NLogEvents>(); /// <summary> /// Processes the log messages. /// </summary> /// <param name="events">The events.</param> public void ProcessLogMessages(NLogEvents events) { if (CountdownEvent == null) { throw new Exception("test not prepared well"); } ReceivedEvents.Add(events); CountdownEvent.Signal(); } } #endif // !NETSTANDARD } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.Core.TestFramework.Models; using NUnit.Framework; namespace Azure.Data.Tables.Tests { /// <summary> /// The suite of tests for the <see cref="TableServiceClient"/> class. /// </summary> /// <remarks> /// These tests have a dependency on live Azure services and may incur costs for the associated /// Azure subscription. /// </remarks> [ClientTestFixture( serviceVersions: default, additionalParameters: new object[] { TableEndpointType.Storage, TableEndpointType.CosmosTable, TableEndpointType.StorageAAD })] public class TableServiceLiveTestsBase : RecordedTestBase<TablesTestEnvironment> { public TableServiceLiveTestsBase(bool isAsync, TableEndpointType endpointType, RecordedTestMode? recordedTestMode = default) : base(isAsync, recordedTestMode) { _endpointType = endpointType; SanitizedHeaders.Add("My-Custom-Auth-Header"); UriRegexSanitizers.Add( new UriRegexSanitizer(@"([\x0026|&|?]sig=)(?<group>[\w\d%]+)", SanitizeValue) { GroupForReplace = "group" }); } protected TableServiceClient service { get; private set; } protected TableClient client { get; private set; } protected TableClient connectionStringClient { get; private set; } protected string ConnectionString { get; private set; } protected string tableName { get; private set; } protected const string PartitionKeyValue = "somPartition"; protected const string PartitionKeyValueWithSingleQuotes = "partition'key''with'''singlequotes'"; protected const string PartitionKeyValue2 = "somPartition2"; protected const string StringTypePropertyName = "SomeStringProperty"; protected const string DateTypePropertyName = "SomeDateProperty"; protected const string GuidTypePropertyName = "SomeGuidProperty"; protected const string BinaryTypePropertyName = "SomeBinaryProperty"; protected const string Int64TypePropertyName = "SomeInt64Property"; protected const string DoubleTypePropertyName = "SomeDoubleProperty0"; protected const string DoubleDecimalTypePropertyName = "SomeDoubleProperty1"; protected const string IntTypePropertyName = "SomeIntProperty"; protected readonly TableEndpointType _endpointType; protected string ServiceUri; protected string AccountName; protected string AccountKey; private readonly Dictionary<string, string> _cosmosIgnoreTests = new() { { "GetAccessPoliciesReturnsPolicies", "GetAccessPolicy is currently not supported by Cosmos endpoints." }, { "GetPropertiesReturnsProperties", "GetProperties is currently not supported by Cosmos endpoints." }, { "GetTableServiceStatsReturnsStats", "GetStatistics is currently not supported by Cosmos endpoints." }, { "ValidateSasCredentialsWithRowKeyAndPartitionKeyRanges", "Shared access signature with PartitionKey or RowKey are not supported" }, { "ValidateAccountSasCredentialsWithPermissions", "SAS for account operations not supported" }, { "ValidateAccountSasCredentialsWithPermissionsWithSasDuplicatedInUri", "SAS for account operations not supported" }, { "ValidateAccountSasCredentialsWithResourceTypes", "SAS for account operations not supported" }, { "ValidateSasCredentialsWithGenerateSasUri", "https://github.com/Azure/azure-sdk-for-net/issues/13578" }, { "CreateEntityWithETagProperty", "https://github.com/Azure/azure-sdk-for-net/issues/21405" }, { "ValidateSasCredentialsWithGenerateSasUriAndUpperCaseTableName", "https://github.com/Azure/azure-sdk-for-net/issues/26800" } }; private readonly Dictionary<string, string> _AadIgnoreTests = new() { { "GetAccessPoliciesReturnsPolicies", "https://github.com/Azure/azure-sdk-for-net/issues/21913" } }; /// <summary> /// Creates a <see cref="TableServiceClient" /> with the endpoint and API key provided via environment /// variables and instruments it to make use of the Azure Core Test Framework functionalities. /// </summary> [SetUp] public async Task TablesTestSetup() { // Bail out before attempting the setup if this test is in the CosmosIgnoreTests set. if (_endpointType == TableEndpointType.CosmosTable && _cosmosIgnoreTests.TryGetValue(TestContext.CurrentContext.Test.Name, out var ignoreReason) || _endpointType == TableEndpointType.StorageAAD && _AadIgnoreTests.TryGetValue(TestContext.CurrentContext.Test.Name, out ignoreReason)) { Assert.Ignore(ignoreReason); } ServiceUri = _endpointType switch { TableEndpointType.CosmosTable => TestEnvironment.CosmosUri, _ => TestEnvironment.StorageUri, }; AccountName = _endpointType switch { TableEndpointType.CosmosTable => TestEnvironment.CosmosAccountName, _ => TestEnvironment.StorageAccountName, }; AccountKey = _endpointType switch { TableEndpointType.CosmosTable => TestEnvironment.PrimaryCosmosAccountKey, _ => TestEnvironment.PrimaryStorageAccountKey, }; ConnectionString = _endpointType switch { TableEndpointType.CosmosTable => TestEnvironment.CosmosConnectionString, _ => TestEnvironment.StorageConnectionString, }; var options = InstrumentClientOptions(new TableClientOptions()); service = CreateService(ServiceUri, options); tableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); await CosmosThrottleWrapper(async () => await service.CreateTableAsync(tableName).ConfigureAwait(false)); client = InstrumentClient(service.GetTableClient(tableName)); connectionStringClient = InstrumentClient(new TableClient(ConnectionString, tableName, options)); } internal TableServiceClient CreateService(string serviceUri, TableClientOptions options) { return _endpointType switch { TableEndpointType.StorageAAD => InstrumentClient( new TableServiceClient( new Uri(serviceUri), TestEnvironment.Credential, options)), _ => InstrumentClient( new TableServiceClient( new Uri(serviceUri), new TableSharedKeyCredential(AccountName, AccountKey), options)) }; } [TearDown] public async Task TablesTeardown() { try { if (service != null) { await service.DeleteTableAsync(tableName); } } catch { } } /// <summary> /// Creates a list of table entities. /// </summary> /// <param name="partitionKeyValue">The partition key to create for the entity.</param> /// <param name="count">The number of entities to create</param> /// <returns></returns> internal static List<TableEntity> CreateTableEntities(string partitionKeyValue, int count) { // Create some entities. return Enumerable.Range(1, count) .Select( n => { string number = n.ToString(); return new TableEntity { { "PartitionKey", partitionKeyValue }, { "RowKey", n.ToString("D2") }, { StringTypePropertyName, $"This is table entity number {n:D2}" }, { DateTypePropertyName, new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n) }, { GuidTypePropertyName, new Guid($"0d391d16-97f1-4b9a-be68-4cc871f9{n:D4}") }, { BinaryTypePropertyName, new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 } }, { Int64TypePropertyName, long.Parse(number) }, { DoubleTypePropertyName, double.Parse($"{number}.0") }, { DoubleDecimalTypePropertyName, n + 0.5 }, { IntTypePropertyName, n }, }; }) .ToList(); } /// <summary> /// Creates a list of Dictionary table entities. /// </summary> /// <param name="partitionKeyValue">The partition key to create for the entity.</param> /// <param name="count">The number of entities to create</param> /// <returns></returns> internal static List<TableEntity> CreateDictionaryTableEntities(string partitionKeyValue, int count) { // Create some entities. return Enumerable.Range(1, count) .Select( n => { string number = n.ToString(); return new TableEntity( new TableEntity { { "PartitionKey", partitionKeyValue }, { "RowKey", n.ToString("D2") }, { StringTypePropertyName, $"This is table entity number {n:D2}" }, { DateTypePropertyName, new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n) }, { GuidTypePropertyName, new Guid($"0d391d16-97f1-4b9a-be68-4cc871f9{n:D4}") }, { BinaryTypePropertyName, new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 } }, { Int64TypePropertyName, long.Parse(number) }, { DoubleTypePropertyName, (double)n }, { DoubleDecimalTypePropertyName, n + 0.5 }, { IntTypePropertyName, n }, }); }) .ToList(); } /// <summary> /// Creates a list of strongly typed table entities. /// </summary> /// <param name="partitionKeyValue">The partition key to create for the entity.</param> /// <param name="count">The number of entities to create</param> /// <returns></returns> internal static List<TestEntity> CreateCustomTableEntities(string partitionKeyValue, int count) { // Create some entities. return Enumerable.Range(1, count) .Select( n => { string number = n.ToString(); return new TestEntity { PartitionKey = partitionKeyValue, RowKey = n.ToString("D2"), StringTypeProperty = $"This is table entity number {n:D2}", DatetimeTypeProperty = new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n), DatetimeOffsetTypeProperty = new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n), GuidTypeProperty = new Guid($"0d391d16-97f1-4b9a-be68-4cc871f9{n:D4}"), BinaryTypeProperty = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 }, Int64TypeProperty = long.Parse(number), UInt64TypeProperty = ulong.Parse(number), DoubleTypeProperty = double.Parse($"{number}.0"), IntTypeProperty = n, }; }) .ToList(); } /// <summary> /// Creates a list of strongly typed table entities. /// </summary> /// <param name="partitionKeyValue">The partition key to create for the entity.</param> /// <param name="count">The number of entities to create</param> /// <returns></returns> internal static List<ComplexEntity> CreateComplexTableEntities(string partitionKeyValue, int count) { // Create some entities. return Enumerable.Range(1, count) .Select( n => { return new ComplexEntity(partitionKeyValue, string.Format("{0:0000}", n)) { String = string.Format("{0:0000}", n), Binary = new BinaryData(new byte[] { 0x01, 0x02, (byte)n }), BinaryPrimitive = new byte[] { 0x01, 0x02, (byte)n }, Bool = n % 2 == 0, BoolPrimitive = n % 2 == 0, DateTime = new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n), DateTimeOffset = new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n), DateTimeAsString = new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n).ToString("o"), DateTimeN = new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n), DateTimeOffsetN = new DateTime(2020, 1, 1, 1, 1, 0, DateTimeKind.Utc).AddMinutes(n), Double = n + 0.5, DoubleInteger = double.Parse($"{n.ToString()}.0"), DoubleN = n + 0.5, DoublePrimitive = n + 0.5, DoublePrimitiveN = n + 0.5, Guid = new Guid($"0d391d16-97f1-4b9a-be68-4cc871f9{n:D4}"), GuidN = new Guid($"0d391d16-97f1-4b9a-be68-4cc871f9{n:D4}"), Int32 = n, Int32N = n, IntegerPrimitive = n, IntegerPrimitiveN = n, Int64 = (long)int.MaxValue + n, LongPrimitive = (long)int.MaxValue + n, LongPrimitiveN = (long)int.MaxValue + n, }; }) .ToList(); } // This is needed to prevent Live nightly test runs from failing due to 429 response failures. // TODO: Remove after addressing https://github.com/Azure/azure-sdk-for-net/issues/13554 protected async Task<TResult> CosmosThrottleWrapper<TResult>(Func<Task<TResult>> action) { int retryCount = 0; int delay = 1500; while (true) { try { return await action().ConfigureAwait(false); } catch (RequestFailedException ex) when (ex.Status == 429) { if (++retryCount > 6) { throw; } // Disable retry throttling in Playback mode. if (Mode != RecordedTestMode.Playback) { await Task.Delay(delay); delay *= 2; } } } } protected async Task<TResult> RetryUntilExpectedResponse<TResult>(Func<Task<TResult>> action, Func<TResult, bool> equalityAction, int initialDelay) { int retryCount = 0; int delay = initialDelay; while (true) { var actual = await action().ConfigureAwait(false); if (++retryCount > 3 || equalityAction(actual)) { return actual; } // Disable retry throttling in Playback mode. if (Mode != RecordedTestMode.Playback) { await Task.Delay(delay); delay *= 2; } } } protected async Task CreateTestEntities<T>(List<T> entitiesToCreate) where T : class, ITableEntity, new() { foreach (var entity in entitiesToCreate) { await CosmosThrottleWrapper(async () => await client.AddEntityAsync<T>(entity).ConfigureAwait(false)); } } protected async Task CreateTestEntities(List<TableEntity> entitiesToCreate) { foreach (var entity in entitiesToCreate) { await CosmosThrottleWrapper(async () => await client.AddEntityAsync(entity).ConfigureAwait(false)); } } protected async Task UpsertTestEntities<T>(List<T> entitiesToCreate, TableUpdateMode updateMode) where T : class, ITableEntity, new() { foreach (var entity in entitiesToCreate) { await CosmosThrottleWrapper(async () => await client.UpsertEntityAsync(entity, updateMode).ConfigureAwait(false)); } } public class TestEntity : ITableEntity { public string StringTypeProperty { get; set; } public DateTime DatetimeTypeProperty { get; set; } public DateTimeOffset DatetimeOffsetTypeProperty { get; set; } public Guid GuidTypeProperty { get; set; } public byte[] BinaryTypeProperty { get; set; } public long Int64TypeProperty { get; set; } public ulong UInt64TypeProperty { get; set; } public double DoubleTypeProperty { get; set; } public int IntTypeProperty { get; set; } public string PartitionKey { get; set; } public string RowKey { get; set; } public DateTimeOffset? Timestamp { get; set; } public ETag ETag { get; set; } } public class SimpleTestEntity : ITableEntity { public string StringTypeProperty { get; set; } public string PartitionKey { get; set; } public string RowKey { get; set; } public DateTimeOffset? Timestamp { get; set; } public ETag ETag { get; set; } } public class ComplexEntity : ITableEntity { public const int NumberOfNonNullProperties = 28; public ComplexEntity() { } public ComplexEntity(string pk, string rk) { PartitionKey = pk; RowKey = rk; } private DateTimeOffset? dateTimeOffsetNull = null; public DateTimeOffset? DateTimeOffsetNull { get { return dateTimeOffsetNull; } set { dateTimeOffsetNull = value; } } private DateTimeOffset? dateTimeOffsetN = DateTimeOffset.Now; public DateTimeOffset? DateTimeOffsetN { get { return dateTimeOffsetN; } set { dateTimeOffsetN = value; } } private DateTimeOffset dateTimeOffset = DateTimeOffset.Now; public DateTimeOffset DateTimeOffset { get { return dateTimeOffset; } set { dateTimeOffset = value; } } public DateTime? DateTimeNull { get; set; } = null; public DateTime? DateTimeN { get; set; } = DateTime.UtcNow; public DateTime DateTime { get; set; } = DateTime.UtcNow; public string DateTimeAsString { get; set; } = DateTime.UtcNow.ToString("o"); public Boolean? BoolNull { get; set; } = null; public Boolean? BoolN { get; set; } = false; public Boolean Bool { get; set; } = false; public bool? BoolPrimitiveNull { get; set; } = null; public bool? BoolPrimitiveN { get; set; } = false; public bool BoolPrimitive { get; set; } = false; public BinaryData Binary { get; set; } = new BinaryData(new byte[] { 1, 2, 3, 4 }); public BinaryData BinaryNull { get; set; } = null; public byte[] BinaryPrimitive { get; set; } = new byte[] { 1, 2, 3, 4 }; public double? DoublePrimitiveNull { get; set; } = null; public double? DoublePrimitiveN { get; set; } = (double)1234.1234; public double DoublePrimitive { get; set; } = (double)1234.1234; public Double? DoubleNull { get; set; } = null; public Double? DoubleN { get; set; } = (Double)1234.1234; public Double Double { get; set; } = (Double)1234.1234; public Double DoubleInteger { get; set; } = (Double)1234; private Guid? guidNull = null; public Guid? GuidNull { get { return guidNull; } set { guidNull = value; } } private Guid? guidN = Guid.NewGuid(); public Guid? GuidN { get { return guidN; } set { guidN = value; } } private Guid guid = Guid.NewGuid(); public Guid Guid { get { return guid; } set { guid = value; } } public int? IntegerPrimitiveNull { get; set; } = null; public int? IntegerPrimitiveN { get; set; } = 1234; public int IntegerPrimitive { get; set; } = 1234; public Int32? Int32Null { get; set; } = null; public Int32? Int32N { get; set; } = 1234; public Int32 Int32 { get; set; } = 1234; public long? LongPrimitiveNull { get; set; } = null; public long? LongPrimitiveN { get; set; } = 123456789012; public long LongPrimitive { get; set; } = 123456789012; public Int64? Int64Null { get; set; } = null; public Int64? Int64N { get; set; } = 123456789012; public Int64 Int64 { get; set; } = 123456789012; public string String { get; set; } = "test"; public string PartitionKey { get; set; } public string RowKey { get; set; } public DateTimeOffset? Timestamp { get; set; } public ETag ETag { get; set; } public static void AssertEquality(ComplexEntity a, ComplexEntity b) { Assert.AreEqual(a.String, b.String); Assert.AreEqual(a.Int64, b.Int64); Assert.AreEqual(a.Int64N, b.Int64N); Assert.AreEqual(a.Int64Null, b.Int64Null); Assert.AreEqual(a.LongPrimitive, b.LongPrimitive); Assert.AreEqual(a.LongPrimitiveN, b.LongPrimitiveN); Assert.AreEqual(a.LongPrimitiveNull, b.LongPrimitiveNull); Assert.AreEqual(a.Int32, b.Int32); Assert.AreEqual(a.Int32N, b.Int32N); Assert.AreEqual(a.Int32Null, b.Int32Null); Assert.AreEqual(a.IntegerPrimitive, b.IntegerPrimitive); Assert.AreEqual(a.IntegerPrimitiveN, b.IntegerPrimitiveN); Assert.AreEqual(a.IntegerPrimitiveNull, b.IntegerPrimitiveNull); Assert.AreEqual(a.Guid, b.Guid); Assert.AreEqual(a.GuidN, b.GuidN); Assert.AreEqual(a.GuidNull, b.GuidNull); Assert.AreEqual(a.Double, b.Double); Assert.AreEqual(a.DoubleN, b.DoubleN); Assert.AreEqual(a.DoubleNull, b.DoubleNull); Assert.AreEqual(a.DoublePrimitive, b.DoublePrimitive); Assert.AreEqual(a.DoublePrimitiveN, b.DoublePrimitiveN); Assert.AreEqual(a.DoublePrimitiveNull, b.DoublePrimitiveNull); Assert.AreEqual(a.BinaryPrimitive.GetValue(0), b.BinaryPrimitive.GetValue(0)); Assert.AreEqual(a.BinaryPrimitive.GetValue(1), b.BinaryPrimitive.GetValue(1)); Assert.AreEqual(a.BinaryPrimitive.GetValue(2), b.BinaryPrimitive.GetValue(2)); Assert.AreEqual(a.Binary.ToArray().GetValue(0), b.Binary.ToArray().GetValue(0)); Assert.AreEqual(a.Binary.ToArray().GetValue(1), b.Binary.ToArray().GetValue(1)); Assert.AreEqual(a.Binary.ToArray().GetValue(2), b.Binary.ToArray().GetValue(2)); Assert.AreEqual(a.BoolPrimitive, b.BoolPrimitive); Assert.AreEqual(a.BoolPrimitiveN, b.BoolPrimitiveN); Assert.AreEqual(a.BoolPrimitiveNull, b.BoolPrimitiveNull); Assert.AreEqual(a.Bool, b.Bool); Assert.AreEqual(a.BoolN, b.BoolN); Assert.AreEqual(a.BoolNull, b.BoolNull); Assert.AreEqual(a.DateTimeOffsetN, b.DateTimeOffsetN); Assert.AreEqual(a.DateTimeOffset, b.DateTimeOffset); Assert.AreEqual(a.DateTimeOffsetNull, b.DateTimeOffsetNull); Assert.AreEqual(a.DateTime, b.DateTime); Assert.AreEqual(a.DateTimeN, b.DateTimeN); Assert.AreEqual(a.DateTimeNull, b.DateTimeNull); } } public class EnumEntity : ITableEntity { public string PartitionKey { get; set; } public string RowKey { get; set; } public DateTimeOffset? Timestamp { get; set; } public ETag ETag { get; set; } public Foo MyFoo { get; set; } public NullableFoo? MyNullableFoo { get; set; } } public enum Foo { One, Two } public enum NullableFoo { One, Two } public class CustomizeSerializationEntity : ITableEntity { public string PartitionKey { get; set; } public string RowKey { get; set; } public DateTimeOffset? Timestamp { get; set; } public ETag ETag { get; set; } public int CurrentCount { get; set; } public int LastCount { get; set; } [IgnoreDataMember] public int CountDiff { get => CurrentCount - LastCount; } [DataMember(Name = "renamed_property")] public string NamedProperty { get; set; } } } }
/* Generated SBE (Simple Binary Encoding) message codec */ #pragma warning disable 1591 // disable warning on missing comments using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.Ir.Generated { public sealed partial class FrameCodec { public const ushort BlockLength = (ushort)12; public const ushort TemplateId = (ushort)1; public const ushort SchemaId = (ushort)0; public const ushort Schema_Version = (ushort)0; public const string SemanticType = ""; private readonly FrameCodec _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public FrameCodec() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = Schema_Version; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(value); _limit = value; } } public const int IrIdId = 1; public static string IrIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int IrIdNullValue = -2147483648; public const int IrIdMinValue = -2147483647; public const int IrIdMaxValue = 2147483647; public int IrId { get { return _buffer.Int32GetLittleEndian(_offset + 0); } set { _buffer.Int32PutLittleEndian(_offset + 0, value); } } public const int IrVersionId = 2; public static string IrVersionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int IrVersionNullValue = -2147483648; public const int IrVersionMinValue = -2147483647; public const int IrVersionMaxValue = 2147483647; public int IrVersion { get { return _buffer.Int32GetLittleEndian(_offset + 4); } set { _buffer.Int32PutLittleEndian(_offset + 4, value); } } public const int SchemaVersionId = 3; public static string SchemaVersionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int SchemaVersionNullValue = -2147483648; public const int SchemaVersionMinValue = -2147483647; public const int SchemaVersionMaxValue = 2147483647; public int SchemaVersion { get { return _buffer.Int32GetLittleEndian(_offset + 8); } set { _buffer.Int32PutLittleEndian(_offset + 8, value); } } public const int PackageNameId = 4; public const string PackageNameCharacterEncoding = "UTF-8"; public static string PackageNameMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int PackageNameHeaderSize = 1; public int GetPackageName(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetPackageName(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int NamespaceNameId = 5; public const string NamespaceNameCharacterEncoding = "UTF-8"; public static string NamespaceNameMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int NamespaceNameHeaderSize = 1; public int GetNamespaceName(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetNamespaceName(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int SemanticVersionId = 6; public const string SemanticVersionCharacterEncoding = "UTF-8"; public static string SemanticVersionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int SemanticVersionHeaderSize = 1; public int GetSemanticVersion(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetSemanticVersion(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } } }
// 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.Threading.Tasks; using Xunit; namespace System.Threading.Channels.Tests { public abstract class UnboundedChannelTests : ChannelTestBase { protected override Channel<T> CreateChannel<T>() => Channel.CreateUnbounded<T>( new UnboundedChannelOptions { SingleReader = RequiresSingleReader, AllowSynchronousContinuations = AllowSynchronousContinuations }); protected override Channel<T> CreateFullChannel<T>() => null; [Fact] public async Task Complete_BeforeEmpty_NoWaiters_TriggersCompletion() { Channel<int> c = CreateChannel(); Assert.True(c.Writer.TryWrite(42)); c.Writer.Complete(); Assert.False(c.Reader.Completion.IsCompleted); Assert.Equal(42, await c.Reader.ReadAsync()); await c.Reader.Completion; } [Fact] public void TryWrite_TryRead_Many() { Channel<int> c = CreateChannel(); const int NumItems = 100000; for (int i = 0; i < NumItems; i++) { Assert.True(c.Writer.TryWrite(i)); } for (int i = 0; i < NumItems; i++) { Assert.True(c.Reader.TryRead(out int result)); Assert.Equal(i, result); } } [Fact] public void TryWrite_TryRead_OneAtATime() { Channel<int> c = CreateChannel(); for (int i = 0; i < 10; i++) { Assert.True(c.Writer.TryWrite(i)); Assert.True(c.Reader.TryRead(out int result)); Assert.Equal(i, result); } } [Fact] public void WaitForReadAsync_DataAvailable_CompletesSynchronously() { Channel<int> c = CreateChannel(); Assert.True(c.Writer.TryWrite(42)); AssertSynchronousTrue(c.Reader.WaitToReadAsync()); } [Theory] [InlineData(0)] [InlineData(1)] public async Task WriteMany_ThenComplete_SuccessfullyReadAll(int readMode) { Channel<int> c = CreateChannel(); for (int i = 0; i < 10; i++) { Assert.True(c.Writer.TryWrite(i)); } c.Writer.Complete(); Assert.False(c.Reader.Completion.IsCompleted); for (int i = 0; i < 10; i++) { Assert.False(c.Reader.Completion.IsCompleted); switch (readMode) { case 0: int result; Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); break; case 1: Assert.Equal(i, await c.Reader.ReadAsync()); break; } } await c.Reader.Completion; } [Fact] public void AllowSynchronousContinuations_WaitToReadAsync_ContinuationsInvokedAccordingToSetting() { Channel<int> c = CreateChannel(); int expectedId = Environment.CurrentManagedThreadId; Task r = c.Reader.WaitToReadAsync().AsTask().ContinueWith(_ => { Assert.Equal(AllowSynchronousContinuations, expectedId == Environment.CurrentManagedThreadId); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Assert.True(c.Writer.WriteAsync(42).IsCompletedSuccessfully); ((IAsyncResult)r).AsyncWaitHandle.WaitOne(); // avoid inlining the continuation r.GetAwaiter().GetResult(); } [Fact] public void AllowSynchronousContinuations_CompletionTask_ContinuationsInvokedAccordingToSetting() { Channel<int> c = CreateChannel(); int expectedId = Environment.CurrentManagedThreadId; Task r = c.Reader.Completion.ContinueWith(_ => { Assert.Equal(AllowSynchronousContinuations, expectedId == Environment.CurrentManagedThreadId); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Assert.True(c.Writer.TryComplete()); ((IAsyncResult)r).AsyncWaitHandle.WaitOne(); // avoid inlining the continuation r.GetAwaiter().GetResult(); } } public abstract class SingleReaderUnboundedChannelTests : UnboundedChannelTests { protected override bool RequiresSingleReader => true; [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Requires internal reflection on framework types.")] [Fact] public void ValidateInternalDebuggerAttributes() { Channel<int> c = CreateChannel(); Assert.True(c.Writer.TryWrite(1)); Assert.True(c.Writer.TryWrite(2)); object queue = DebuggerAttributes.GetFieldValue(c, "_items"); DebuggerAttributes.ValidateDebuggerDisplayReferences(queue); DebuggerAttributes.InvokeDebuggerTypeProxyProperties(queue); } [Fact] public async Task MultipleWaiters_CancelsPreviousWaiter() { Channel<int> c = CreateChannel(); ValueTask<bool> t1 = c.Reader.WaitToReadAsync(); ValueTask<bool> t2 = c.Reader.WaitToReadAsync(); await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await t1); Assert.True(c.Writer.TryWrite(42)); Assert.True(await t2); } [Fact] public async Task MultipleReaders_CancelsPreviousReader() { Channel<int> c = CreateChannel(); ValueTask<int> t1 = c.Reader.ReadAsync(); ValueTask<int> t2 = c.Reader.ReadAsync(); await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await t1); Assert.True(c.Writer.TryWrite(42)); Assert.Equal(42, await t2); } [Fact] public void Stress_TryWrite_TryRead() { const int NumItems = 3000000; Channel<int> c = CreateChannel(); Task.WaitAll( Task.Run(async () => { int received = 0; while (await c.Reader.WaitToReadAsync()) { while (c.Reader.TryRead(out int i)) { Assert.Equal(received, i); received++; } } }), Task.Run(() => { for (int i = 0; i < NumItems; i++) { Assert.True(c.Writer.TryWrite(i)); } c.Writer.Complete(); })); } } public sealed class SyncMultiReaderUnboundedChannelTests : UnboundedChannelTests { protected override bool AllowSynchronousContinuations => true; } public sealed class AsyncMultiReaderUnboundedChannelTests : UnboundedChannelTests { protected override bool AllowSynchronousContinuations => false; } public sealed class SyncSingleReaderUnboundedChannelTests : SingleReaderUnboundedChannelTests { protected override bool AllowSynchronousContinuations => true; } public sealed class AsyncSingleReaderUnboundedChannelTests : SingleReaderUnboundedChannelTests { protected override bool AllowSynchronousContinuations => false; } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; using System.Runtime.InteropServices; // ERROR: Not supported in C#: OptionDeclaration using VB = Microsoft.VisualBasic; namespace _4PosBackOffice.NET { static class modEmails { [DllImport("ODBCCP32.DLL", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] // Registry API functions private static extern int SQLConfigDataSource(int hwndParent, int fRequest, string lpszDriver, string lpszAttributes); // Add data source const short ODBC_ADD_DSN = 1; // Delete data source const short ODBC_REMOVE_DSN = 3; private struct STARTUPINFO { public int cb; public string lpReserved; public string lpDesktop; public string lpTitle; public int dwX; public int dwY; public int dwXSize; public int dwYSize; public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public int dwFlags; public short wShowWindow; public short cbReserved2; public int lpReserved2; public int hStdInput; public int hStdOutput; public int hStdError; } private struct PROCESS_INFORMATION { public int hProcess; public int hThread; public int dwProcessID; public int dwThreadID; } [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int WaitForSingleObject(int hHandle, int dwMilliseconds); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] //UPGRADE_WARNING: Structure PROCESS_INFORMATION may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' //UPGRADE_WARNING: Structure STARTUPINFO may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' private static extern int CreateProcessA(string lpApplicationName, string lpCommandLine, int lpProcessAttributes, int lpThreadAttributes, int bInheritHandles, int dwCreationFlags, int lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int CloseHandle(int hObject); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int GetExitCodeProcess(int hProcess, ref int lpExitCode); private const int NORMAL_PRIORITY_CLASS = 0x20; private const short INFINITE = -1; public static object ExecCmd(ref string cmdline) { int ret = 0; PROCESS_INFORMATION proc = default(PROCESS_INFORMATION); STARTUPINFO start = default(STARTUPINFO); //Initialize the STARTUPINFO structure: start.cb = Strings.Len(start); //Start the shelled application: ret = CreateProcessA(Constants.vbNullString, cmdline, 0, 0, 1, NORMAL_PRIORITY_CLASS, 0, Constants.vbNullString, ref start, ref proc); //Wait for the shelled application to finish: ret = WaitForSingleObject(proc.hProcess, INFINITE); GetExitCodeProcess(proc.hProcess, ref ret); CloseHandle(proc.hThread); CloseHandle(proc.hProcess); //UPGRADE_WARNING: Couldn't resolve default property of object ExecCmd. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' return ret; } public static void SendSaleMail(ref string stEmail_d, ref string stAttchFile, ref string compID) { short id = 0; string stFileName = null; stFileName = modRecordSet.serverPath + "HQSales\\HQSales" + id + ".zip"; stFileName = "HQSales" + compID + ".zip"; // MSAPISession calls now need to be using System.Net.Mail //frmDayEnd.MAPISession1.SignOn() //frmDayEnd.MAPIMessages1.SessionID = frmDayEnd.MAPISession1.SessionID //frmDayEnd.MAPIMessages1.Compose() //frmDayEnd.MAPIMessages1.RecipIndex = 0 //frmDayEnd.MAPIMessages1.RecipDisplayName = stEmail_d //frmDayEnd.MAPIMessages1.ResolveName() //frmDayEnd.MAPIMessages1.AddressResolveUI = True //frmDayEnd.MAPIMessages1.ResolveName() //frmDayEnd.MAPIMessages1.RecipAddress = "smtp:" & Trim(stEmail_d) //frmDayEnd.MAPIMessages1.MsgSubject = "4POS Sales" //frmDayEnd.MAPIMessages1.MsgNoteText = "Store Sales as at " & Format(Now, "ddd, dd-mmm-yyyy hh:nn") //frmDayEnd.MAPIMessages1.AttachmentType = MSMAPI.AttachTypeConstants.mapData //frmDayEnd.MAPIMessages1.AttachmentName = stFileName '"HQSales.zip" //'frmDayEnd.MAPIMessages1.AttachmentPathName = serverPath & "HQSales\HQSales.zip" //frmDayEnd.MAPIMessages1.AttachmentPathName = stAttchFile 'Identifying company ID //frmDayEnd.MAPIMessages1.Send(False) //frmDayEnd.MAPISession1.SignOff() } public static void CollectSalesHQ() { string dateSeril = null; string ldir1 = null; string f_File = null; bool sFiles = false; string strFile = null; ADODB.Recordset rs = default(ADODB.Recordset); Scripting.FileSystemObject FSO = new Scripting.FileSystemObject(); // ERROR: Not supported in C#: OnErrorStatement rs = modRecordSet.getRS(ref "SELECT * FROM CompanyEmails"); if (rs.RecordCount) strFile = modRecordSet.serverPath + "HQSales\\HQSales" + rs.Fields("Comp_ID").Value + ".zip "; string stEmail = null; short k = 0; bool v_Email = false; if (copyFilesFromPoints() == true) { //ExecCmd serverPath & "wzzip.exe " & serverPath & "HQSales\HQSales.zip " & serverPath & "HQSales\*.*" //now it will look "c:\4POSServer\" ExecCmd serverPath & "wzzip.exe " & strFile & serverPath & "HQSales\*.*" ExecCmd(ref "c:\\4POSServer\\" + "wzzip.exe " + strFile + modRecordSet.serverPath + "HQSales\\*.*"); //On Local Error Resume Next //UPGRADE_WARNING: Couldn't resolve default property of object dateSeril. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' dateSeril = Strings.Trim(Strings.Replace(Convert.ToString(DateAndTime.Now), ":", "")); //UPGRADE_WARNING: Couldn't resolve default property of object dateSeril. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' dateSeril = Strings.Trim(Strings.Replace(dateSeril, "/", "")); //UPGRADE_WARNING: Couldn't resolve default property of object dateSeril. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' dateSeril = Strings.Trim(Strings.Replace(dateSeril, " ", "")); rs = modRecordSet.getRS(ref "SELECT * FROM CompanyEmails"); if (rs.RecordCount) { for (k = 1; k <= 7; k++) { stEmail = rs.Fields("Comp_Email" + k).Value; if (Strings.InStr(stEmail, "@") > 0) v_Email = true; if (Strings.InStr(stEmail, ":\\") > 0) v_Email = true; if (Strings.InStr(stEmail, "\\\\") > 0) v_Email = true; } if (v_Email == false) return; //No valid email for (k = 1; k <= 7; k++) { stEmail = rs.Fields("Comp_Email" + k).Value; //Validate email string... if (Strings.InStr(stEmail, "@") > 0) { //SendSaleMail stEmail, rs("Comp_ID") SendSaleMail(ref stEmail, ref modRecordSet.serverPath + "HQSales\\HQSales" + rs.Fields("Comp_ID").Value + ".zip", ref rs.Fields("Comp_ID").Value); //Validate Netword Path string... } else if (Strings.InStr(stEmail, "\\\\") > 0) { System.Windows.Forms.Application.DoEvents(); if (Strings.Right(stEmail, 1) == "\\") { } else { stEmail = stEmail + "\\"; } if (FSO.FolderExists(stEmail)) { System.Windows.Forms.Application.DoEvents(); if (FSO.FileExists(stEmail + "HQSales" + rs.Fields("Comp_ID").Value + ".zip")) { //UPGRADE_WARNING: Couldn't resolve default property of object dateSeril. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' FSO.CopyFile(modRecordSet.serverPath + "HQSales\\HQSales" + rs.Fields("Comp_ID").Value + ".zip", stEmail + "HQSales" + rs.Fields("Comp_ID").Value + "_" + dateSeril + ".zip", true); } else { FSO.CopyFile(modRecordSet.serverPath + "HQSales\\HQSales" + rs.Fields("Comp_ID").Value + ".zip", stEmail + "HQSales" + rs.Fields("Comp_ID").Value + ".zip", true); } } else { } //Validate Local Path string... } else if (Strings.InStr(stEmail, ":\\") > 0) { if (Strings.Right(stEmail, 1) == "\\") { } else { stEmail = stEmail + "\\"; } if (FSO.FolderExists(stEmail)) { } else { FSO.CreateFolder(stEmail); } System.Windows.Forms.Application.DoEvents(); if (FSO.FileExists(stEmail + "HQSales" + rs.Fields("Comp_ID").Value + ".zip")) { //UPGRADE_WARNING: Couldn't resolve default property of object dateSeril. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' FSO.CopyFile(modRecordSet.serverPath + "HQSales\\HQSales" + rs.Fields("Comp_ID").Value + ".zip", stEmail + "HQSales" + rs.Fields("Comp_ID").Value + "_" + dateSeril + ".zip", true); } else { FSO.CopyFile(modRecordSet.serverPath + "HQSales\\HQSales" + rs.Fields("Comp_ID").Value + ".zip", stEmail + "HQSales" + rs.Fields("Comp_ID").Value + ".zip", true); } } } } } return; ErrHQ: Interaction.MsgBox(Err().Number + " : " + Err().Description + " : Path = " + stEmail); // ERROR: Not supported in C#: ResumeStatement } private static bool copyFilesFromPoints() { bool functionReturnValue = false; bool sFiles = false; string f_File = null; string ldir1 = null; ADODB.Recordset rj = default(ADODB.Recordset); Scripting.FileSystemObject FSO = new Scripting.FileSystemObject(); sFiles = false; f_File = Strings.Trim(Conversion.Str(DateAndTime.Year(DateAndTime.Today))) + "\\" + Strings.Trim(Conversion.Str(DateAndTime.Month(DateAndTime.Today))) + "\\" + Strings.Trim(Conversion.Str(DateAndTime.Day(DateAndTime.Today))); rj = modRecordSet.getRS(ref "SELECT POS_Name FROM POS WHERE POS_Disabled = False AND POS_KitchenMonitor = False;"); if (rj.RecordCount) { if (FSO.FolderExists(modRecordSet.serverPath + "HQSales")) { } else { FSO.CreateFolder(modRecordSet.serverPath + "HQSales"); } //Make sure the HQSales file is empty... //UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' ldir1 = FileSystem.Dir(modRecordSet.serverPath + "HQSales\\*.*"); while (!(string.IsNullOrEmpty(ldir1))) { FSO.DeleteFile(modRecordSet.serverPath + "HQSales\\" + ldir1, true); //UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' ldir1 = FileSystem.Dir(); } while (rj.EOF == false) { if (Strings.LCase(rj.Fields("POS_Name").Value) == "localhost") { if (FSO.FolderExists(modRecordSet.serverPath + "data\\Server\\" + f_File)) { //UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' ldir1 = FileSystem.Dir(modRecordSet.serverPath + "data\\Server\\" + f_File + "\\*.*"); while (!(string.IsNullOrEmpty(ldir1))) { FSO.CopyFile(modRecordSet.serverPath + "data\\Server\\" + f_File + "\\" + ldir1, modRecordSet.serverPath + "HQSales\\" + ldir1, true); //UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' ldir1 = FileSystem.Dir(); sFiles = true; } } } else { if (FSO.FolderExists(modRecordSet.serverPath + "data\\" + rj.Fields("POS_Name").Value + "\\" + f_File)) { //UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' ldir1 = FileSystem.Dir(modRecordSet.serverPath + "data\\" + rj.Fields("POS_Name").Value + "\\" + f_File + "\\*.*"); while (!(string.IsNullOrEmpty(ldir1))) { FSO.CopyFile(modRecordSet.serverPath + "data\\" + rj.Fields("POS_Name").Value + "\\" + f_File + "\\" + ldir1, modRecordSet.serverPath + "HQSales\\" + ldir1, true); //UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' ldir1 = FileSystem.Dir(); sFiles = true; } } } rj.moveNext(); } } if (sFiles == true) { functionReturnValue = true; } else { functionReturnValue = false; } return functionReturnValue; } } }
using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Replicator { /* * 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. */ public class LocalReplicatorTest : ReplicatorTestCase { private const string VERSION_ID = "version"; private LocalReplicator replicator; private Directory sourceDirectory; private IndexWriter sourceWriter; public override void SetUp() { base.SetUp(); sourceDirectory = NewDirectory(); IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, null); conf.IndexDeletionPolicy = new SnapshotDeletionPolicy(conf.IndexDeletionPolicy); sourceWriter = new IndexWriter(sourceDirectory, conf); replicator = new LocalReplicator(); } public override void TearDown() { IOUtils.Dispose(replicator, sourceWriter, sourceDirectory); base.TearDown(); } private IRevision CreateRevision(int id) { sourceWriter.AddDocument(new Document()); sourceWriter.SetCommitData(new Dictionary<string, string> { { VERSION_ID, id.ToString() } }); sourceWriter.Commit(); return new IndexRevision(sourceWriter); } [Test] public void TestCheckForUpdateNoRevisions() { assertNull(replicator.CheckForUpdate(null)); } [Test] public void TestObtainFileAlreadyClosed() { replicator.Publish(CreateRevision(1)); SessionToken res = replicator.CheckForUpdate(null); assertNotNull(res); assertEquals(1, res.SourceFiles.Count); System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IList<RevisionFile>> entry = res.SourceFiles.First(); replicator.Dispose(); try { replicator.ObtainFile(res.Id, entry.Key, entry.Value.First().FileName); fail("should have failed on AlreadyClosedException"); } catch (ObjectDisposedException) { // expected } } [Test] public void TestPublishAlreadyClosed() { replicator.Dispose(); try { replicator.Publish(CreateRevision(2)); fail("should have failed on AlreadyClosedException"); } catch (ObjectDisposedException) { // expected } } [Test] public void TestUpdateAlreadyClosed() { replicator.Dispose(); try { replicator.CheckForUpdate(null); fail("should have failed on AlreadyClosedException"); } catch (ObjectDisposedException) { // expected } } [Test] public void TestPublishSameRevision() { IRevision rev = CreateRevision(1); replicator.Publish(rev); SessionToken res = replicator.CheckForUpdate(null); assertNotNull(res); assertEquals(rev.Version, res.Version); replicator.Release(res.Id); replicator.Publish(new IndexRevision(sourceWriter)); res = replicator.CheckForUpdate(res.Version); assertNull(res); // now make sure that publishing same revision doesn't leave revisions // "locked", i.e. that replicator releases revisions even when they are not // kept replicator.Publish(CreateRevision(2)); assertEquals(1, DirectoryReader.ListCommits(sourceDirectory).size()); } [Test] public void TestPublishOlderRev() { replicator.Publish(CreateRevision(1)); IRevision old = new IndexRevision(sourceWriter); replicator.Publish(CreateRevision(2)); try { replicator.Publish(old); fail("should have failed to publish an older revision"); } catch (ArgumentException) { // expected } assertEquals(1, DirectoryReader.ListCommits(sourceDirectory).size()); } [Test] public void TestObtainMissingFile() { replicator.Publish(CreateRevision(1)); SessionToken res = replicator.CheckForUpdate(null); try { replicator.ObtainFile(res.Id, res.SourceFiles.Keys.First(), "madeUpFile"); fail("should have failed obtaining an unrecognized file"); } #pragma warning disable 168 catch (FileNotFoundException e) #pragma warning restore 168 { // expected } #pragma warning disable 168 catch (DirectoryNotFoundException e) // LUCENENET specific: In Java, a FileNotFound exception is thrown when there is no directory, so we need to cover this case as well #pragma warning restore 168 { // expected } } [Test] public void TestSessionExpiration() { replicator.Publish(CreateRevision(1)); SessionToken session = replicator.CheckForUpdate(null); replicator.ExpirationThreshold = 5; // expire quickly Thread.Sleep(50); // sufficient for expiration try { replicator.ObtainFile(session.Id, session.SourceFiles.Keys.First(), session.SourceFiles.Values.First().First().FileName); fail("should have failed to obtain a file for an expired session"); } catch (SessionExpiredException) { // expected } } [Test] public void TestUpdateToLatest() { replicator.Publish(CreateRevision(1)); IRevision rev = CreateRevision(2); replicator.Publish(rev); SessionToken res = replicator.CheckForUpdate(null); assertNotNull(res); assertEquals(0, rev.CompareTo(res.Version)); } [Test] public void TestRevisionRelease() { replicator.Publish(CreateRevision(1)); assertTrue(SlowFileExists(sourceDirectory, IndexFileNames.SEGMENTS + "_1")); replicator.Publish(CreateRevision(2)); // now the files of revision 1 can be deleted assertTrue(SlowFileExists(sourceDirectory, IndexFileNames.SEGMENTS + "_2")); assertFalse("segments_1 should not be found in index directory after revision is released", SlowFileExists(sourceDirectory, IndexFileNames.SEGMENTS + "_1")); } } }
// // Copyright (C) DataStax 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. // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using Cassandra.DataStax.Graph; using Cassandra.Geometry; using Cassandra.Serialization.Graph.GraphSON1; using Newtonsoft.Json; using NUnit.Framework; namespace Cassandra.Tests.DataStax.Graph { public class GraphNodeGraphSON1Tests : BaseUnitTest { [Test] public void Constructor_Should_Throw_When_Json_Is_Null() { // ReSharper disable once ObjectCreationAsStatement Assert.Throws<ArgumentNullException>(() => new GraphNode((string)null)); } [Test] public void Constructor_Should_Parse_Json() { var result = new GraphNode("{\"result\": \"something\"}"); Assert.AreEqual("something", result.ToString()); Assert.False(result.IsObjectTree); Assert.True(result.IsScalar); Assert.False(result.IsArray); result = new GraphNode("{\"result\": {\"something\": 1.2 }}"); Assert.AreEqual(1.2D, result.Get<double>("something")); Assert.True(result.IsObjectTree); Assert.False(result.IsScalar); Assert.False(result.IsArray); result = new GraphNode("{\"result\": [] }"); Assert.False(result.IsObjectTree); Assert.False(result.IsScalar); Assert.True(result.IsArray); } [Test] public void Should_Throw_For_Trying_To_Access_Properties_When_The_Node_Is_Not_An_Object_Tree() { var result = new GraphNode("{\"result\": {\"something\": 1.2 }}"); Assert.True(result.IsObjectTree); Assert.True(result.HasProperty("something")); Assert.False(result.HasProperty("other")); //result is a scalar value result = new GraphNode("{\"result\": 1.2}"); Assert.True(result.IsScalar); Assert.False(result.HasProperty("whatever")); Assert.Throws<InvalidOperationException>(() => result.GetProperties()); } [Test] public void Get_T_Should_Allow_Serializable_Types() { GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": 1.2 }}", "something", 1.2M); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": 12 }}", "something", 12); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": 12 }}", "something", 12L); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": 1.2 }}", "something", 1.2D); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": 1.2 }}", "something", 1.2F); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": 1.2 }}", "something", "1.2"); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": \"123e4567-e89b-12d3-a456-426655440000\" }}", "something", Guid.Parse("123e4567-e89b-12d3-a456-426655440000")); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": 12 }}", "something", BigInteger.Parse("12")); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": \"92d4a960-1cf3-11e6-9417-bd9ef43c1c95\" }}", "something", (TimeUuid)Guid.Parse("92d4a960-1cf3-11e6-9417-bd9ef43c1c95")); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": [1, 2, 3] }}", "something", new[] { 1, 2, 3 }); GraphNodeGraphSON1Tests.TestGet<IEnumerable<int>>("{\"result\": {\"something\": [1, 2, 3] }}", "something", new[] { 1, 2, 3 }); } [Test] public void Get_T_Should_Allow_Geometry_Types() { GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": \"POINT (1.0 2.0)\" }}", "something", new Point(1, 2)); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": \"LINESTRING (1 2, 3 4.1234)\" }}", "something", new LineString(new Point(1, 2), new Point(3, 4.1234))); GraphNodeGraphSON1Tests.TestGet("{\"result\": {\"something\": \"POLYGON ((1 3, 3 1, 3 6, 1 3))\" }}", "something", new Polygon(new Point(1, 3), new Point(3, 1), new Point(3, 6), new Point(1, 3))); } [Test] public void To_T_Should_Allow_Serializable_Types() { GraphNodeGraphSON1Tests.TestTo("{\"result\": 2.2}", 2.2M); GraphNodeGraphSON1Tests.TestTo("{\"result\": 2.2}", 2.2D); GraphNodeGraphSON1Tests.TestTo("{\"result\": 2.2}", 2.2F); GraphNodeGraphSON1Tests.TestTo("{\"result\": 22}", 22); GraphNodeGraphSON1Tests.TestTo("{\"result\": 22}", (int?)22); GraphNodeGraphSON1Tests.TestTo("{\"result\": 22}", 22L); GraphNodeGraphSON1Tests.TestTo("{\"result\": 22}", BigInteger.Parse("22")); GraphNodeGraphSON1Tests.TestTo("{\"result\": 22}", "22"); GraphNodeGraphSON1Tests.TestTo("{\"result\": \"92d4a960-1cf3-11e6-9417-bd9ef43c1c95\"}", Guid.Parse("92d4a960-1cf3-11e6-9417-bd9ef43c1c95")); GraphNodeGraphSON1Tests.TestTo("{\"result\": \"92d4a960-1cf3-11e6-9417-bd9ef43c1c95\"}", (Guid?) Guid.Parse("92d4a960-1cf3-11e6-9417-bd9ef43c1c95")); GraphNodeGraphSON1Tests.TestTo("{\"result\": \"92d4a960-1cf3-11e6-9417-bd9ef43c1c95\"}", (TimeUuid)Guid.Parse("92d4a960-1cf3-11e6-9417-bd9ef43c1c95")); } [Test] public void To_Should_Throw_For_Not_Supported_Types() { const string json = "{\"result\": \"123\"}"; var types = new [] { typeof(UIntPtr), typeof(IntPtr), typeof(StringBuilder) }; foreach (var t in types) { Assert.Throws<NotSupportedException>(() => new GraphNode(json).To(t)); } } [Test] public void To_T_Should_Throw_For_Not_Supported_Types() { const string json = "{\"result\": \"123\"}"; GraphNodeGraphSON1Tests.TestToThrows<IntPtr, NotSupportedException>(json); GraphNodeGraphSON1Tests.TestToThrows<UIntPtr, NotSupportedException>(json); GraphNodeGraphSON1Tests.TestToThrows<StringBuilder, NotSupportedException>(json); } [Test] public void Get_T_Should_Throw_For_Not_Supported_Types() { const string json = "{\"result\": {\"something\": \"123\" }}"; GraphNodeGraphSON1Tests.TestGetThrows<IntPtr, NotSupportedException>(json, "something"); GraphNodeGraphSON1Tests.TestGetThrows<UIntPtr, NotSupportedException>(json, "something"); GraphNodeGraphSON1Tests.TestGetThrows<StringBuilder, NotSupportedException>(json, "something"); } private static void TestGet<T>(string json, string property, T expectedValue) { var result = new GraphNode(json); if (expectedValue is IEnumerable) { CollectionAssert.AreEqual((IEnumerable)expectedValue, (IEnumerable)result.Get<T>(property)); return; } Assert.AreEqual(expectedValue, result.Get<T>(property)); } private static void TestGetThrows<T, TException>(string json, string property) where TException : Exception { Assert.Throws<TException>(() => new GraphNode(json).Get<T>(property)); } private static void TestTo<T>(string json, T expectedValue) { var result = new GraphNode(json); Assert.AreEqual(expectedValue, result.To<T>()); } private static void TestToThrows<T, TException>(string json) where TException : Exception { Assert.Throws<TException>(() => new GraphNode(json).To<T>()); } [Test] public void Should_Allow_Nested_Properties_For_Object_Trees() { dynamic result = new GraphNode("{\"result\": " + "{" + "\"something\": {\"inTheAir\": 1}," + "\"everything\": {\"isAwesome\": [1, 2, \"zeta\"]}, " + "\"a\": {\"b\": {\"c\": 0.6}} " + "}}"); Assert.AreEqual(1, result.something.inTheAir); IEnumerable<GraphNode> values = result.everything.isAwesome; CollectionAssert.AreEqual(new [] { "1", "2", "zeta" }, values.Select(x => x.ToString())); Assert.AreEqual(0.6D, result.a.b.c); } [Test] public void ToString_Should_Return_The_Json_Representation_Of_Result_Property() { var result = new GraphNode("{\"result\": 1.9}"); Assert.AreEqual("1.9", result.ToString()); result = new GraphNode("{\"result\": [ 1, 2]}"); Assert.AreEqual(string.Format("[{0} 1,{0} 2{0}]", Environment.NewLine), result.ToString()); result = new GraphNode("{\"result\": \"a\"}"); Assert.AreEqual("a", result.ToString()); } [Test] public void ToDouble_Should_Convert_To_Double() { var result = new GraphNode("{\"result\": 1.9}"); Assert.AreEqual(1.9, result.ToDouble()); } [Test] public void ToDouble_Should_Throw_For_Non_Scalar_Values() { var result = new GraphNode("{\"result\": {\"something\": 0 }}"); Assert.Throws<InvalidOperationException>(() => result.ToDouble()); } [Test] public void Get_T_Should_Get_A_Typed_Value_By_Name() { var result = new GraphNode("{\"result\": {\"some\": \"value1\" }}"); Assert.AreEqual("value1", result.Get<string>("some")); } [Test] public void Get_T_Should_Allow_Dynamic_For_Object_Trees() { var result = new GraphNode("{\"result\": {\"something\": {\"is_awesome\": true} }}"); Assert.AreEqual(true, result.Get<dynamic>("something").is_awesome); } [Test] public void Get_T_Should_Allow_Dynamic_For_Nested_Object_Trees() { var result = new GraphNode("{\"result\": {\"everything\": {\"is_awesome\": {\"when\": {" + " \"we\": \"are together\"} }} }}"); var everything = result.Get<dynamic>("everything"); Assert.AreEqual("are together", everything.is_awesome.when.we); } [Test] public void Get_T_Should_Allow_GraphNode_For_Object_Trees() { var result = new GraphNode("{\"result\": {\"something\": {\"is_awesome\": {\"it\": \"maybe\" }} }}"); var node = result.Get<GraphNode>("something"); Assert.NotNull(node); Assert.NotNull(node.Get<GraphNode>("is_awesome")); Assert.AreEqual("maybe", node.Get<GraphNode>("is_awesome").Get<string>("it")); } [Test] public void Get_T_Should_Not_Throw_For_Non_Existent_Dynamic_Property_Name() { var result = new GraphNode("{\"result\": {\"everything\": {\"is_awesome\": true} }}"); Assert.DoesNotThrow(() => result.Get<dynamic>("what")); } [Test] public void Equals_Should_Return_True_For_The_Same_Json() { var result1 = new GraphNode("{\"result\": {\"something\": {\"in_the_way\": true}}}"); var result2 = new GraphNode("{\"result\": {\"something\": {\"in_the_way\": true}}}"); var result3 = new GraphNode("{\"result\": {\"other\": \"value\"}}"); Assert.True(result1.Equals(result2)); Assert.True(result2.Equals(result1)); Assert.False(result1.Equals(result3)); //operator Assert.True(result1 == result2); Assert.AreEqual(result1.GetHashCode(), result1.GetHashCode()); Assert.AreEqual(result1.GetHashCode(), result2.GetHashCode()); Assert.AreNotEqual(result1.GetHashCode(), result3.GetHashCode()); } [Test] public void ToVertex_Should_Convert_To_Vertex() { var result = new GraphNode("{" + "\"result\": {" + "\"id\":{\"member_id\":0,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}," + "\"label\":\"vertex\"," + "\"type\":\"vertex\"," + "\"properties\":{" + "\"name\":[{\"id\":{\"local_id\":\"00000000-0000-8007-0000-000000000000\",\"~type\":\"name\",\"out_vertex\":{\"member_id\":0,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}},\"value\":\"j\",\"label\":\"name\"}]," + "\"age\":[{\"id\":{\"local_id\":\"00000000-0000-8008-0000-000000000000\",\"~type\":\"age\",\"out_vertex\":{\"member_id\":0,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}},\"value\":34,\"label\":\"age\"}]}" + "}}"); var vertex = result.ToVertex(); Assert.AreEqual("vertex", vertex.Label); dynamic id = vertex.Id; Assert.AreEqual(586910, id.community_id); Assert.AreEqual(586910, vertex.Id.Get<long>("community_id")); Assert.AreEqual(2, vertex.Properties.Count); dynamic nameProp = vertex.Properties["name"].ToArray(); Assert.NotNull(nameProp); Assert.NotNull(nameProp[0].id); // Validate properties var properties = vertex.GetProperties(); CollectionAssert.AreEquivalent(new[] {"name", "age"}, properties.Select(p => p.Name)); var nameProperty = vertex.GetProperty("name"); Assert.NotNull(nameProperty); Assert.AreEqual("j", nameProperty.Value.ToString()); Assert.AreEqual(0, nameProperty.GetProperties().Count()); var ageProperty = vertex.GetProperty("age"); Assert.NotNull(ageProperty); Assert.AreEqual(34, ageProperty.Value.To<int>()); Assert.AreEqual(0, ageProperty.GetProperties().Count()); //Is convertible Assert.NotNull((Vertex)result); //Any enumeration of graph result can be casted to vertex IEnumerable<GraphNode> results = new[] { result, result, result }; foreach (Vertex v in results) { Assert.NotNull(v); } } [Test, TestCase(true)] [TestCase(false)] public void GraphNode_Should_Be_Serializable(bool useConverter) { var settings = new JsonSerializerSettings(); if (useConverter) { settings = GraphSON1ContractResolver.Settings; } const string json = "{" + "\"id\":{\"member_id\":0,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}," + "\"label\":\"vertex\"," + "\"type\":\"vertex\"," + "\"properties\":{" + "\"name\":[{\"id\":{\"local_id\":\"00000000-0000-8007-0000-000000000000\",\"~type\":\"name\",\"out_vertex\":{\"member_id\":0,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}},\"value\":\"j\",\"label\":\"name\"}]," + "\"age\":[{\"id\":{\"local_id\":\"00000000-0000-8008-0000-000000000000\",\"~type\":\"age\",\"out_vertex\":{\"member_id\":0,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}},\"value\":34,\"label\":\"age\"}]}" + "}"; IGraphNode node = new GraphNode("{\"result\":" + json + "}"); var serialized = JsonConvert.SerializeObject(node, settings); Assert.AreEqual(json, serialized); } [Test] public void ToVertex_Should_Throw_For_Scalar_Values() { var result = new GraphNode("{" + "\"result\": 1 }"); Assert.Throws<InvalidOperationException>(() => result.ToVertex()); } [Test] public void ToVertex_Should_Not_Throw_When_The_Properties_Is_Not_Present() { var vertex = GraphNodeGraphSON1Tests.GetGraphNode( "{" + "\"id\":{\"member_id\":0,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}," + "\"label\":\"vertex1\"," + "\"type\":\"vertex\"" + "}").ToVertex(); Assert.AreEqual("vertex1", vertex.Label); Assert.NotNull(vertex.Id); } [Test] public void ToVertex_Should_Throw_When_Required_Attributes_Are_Not_Present() { Assert.Throws<InvalidOperationException>(() => GraphNodeGraphSON1Tests.GetGraphNode( "{" + "\"label\":\"vertex1\"," + "\"type\":\"vertex\"" + "}").ToVertex()); Assert.Throws<InvalidOperationException>(() => GraphNodeGraphSON1Tests.GetGraphNode( "{" + "\"id\":{\"member_id\":0,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}," + "\"type\":\"vertex\"" + "}").ToVertex()); } [Test] public void ToEdge_Should_Convert() { var result = new GraphNode("{" + "\"result\":{" + "\"id\":{" + "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + "\"local_id\":\"4e78f871-c5c8-11e5-a449-130aecf8e504\",\"in_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":5},\"~type\":\"knows\"}," + "\"label\":\"knows\"," + "\"type\":\"edge\"," + "\"inVLabel\":\"in-vertex\"," + "\"outVLabel\":\"vertex\"," + "\"inV\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":5}," + "\"outV\":{\"member_id\":0,\"community_id\":680140,\"~label\":\"vertex\",\"group_id\":3}," + "\"properties\":{\"weight\":1.5}" + "}}"); var edge = result.ToEdge(); Assert.AreEqual("knows", edge.Label); Assert.AreEqual("in-vertex", edge.InVLabel); dynamic id = edge.Id; Assert.AreEqual("4e78f871-c5c8-11e5-a449-130aecf8e504", id.local_id); Assert.AreEqual(680140, edge.OutV.Get<long>("community_id")); Assert.AreEqual(1, edge.Properties.Count); var weightProp = edge.Properties["weight"]; Assert.NotNull(weightProp); Assert.AreEqual(1.5D, weightProp.ToDouble()); var property = edge.GetProperty("weight"); Assert.NotNull(property); Assert.AreEqual("weight", property.Name); Assert.AreEqual(1.5D, property.Value.To<double>()); Assert.Null(edge.GetProperty("nonExistentProperty")); //Is convertible Assert.NotNull((Edge)result); //Any enumeration of graph result can be casted to edge IEnumerable<GraphNode> results = new[] { result, result, result }; foreach (Edge v in results) { Assert.NotNull(v); } } [Test] public void ToEdge_Should_Throw_For_Scalar_Values() { var result = new GraphNode("{" + "\"result\": 1 }"); Assert.Throws<InvalidOperationException>(() => result.ToEdge()); } [Test] public void ToEdge_Should_Not_Throw_When_The_Properties_Is_Not_Present() { var edge = GraphNodeGraphSON1Tests.GetGraphNode("{" + "\"id\":{" + "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + "\"local_id\":\"4e78f871-c5c8-11e5-a449-130aecf8e504\",\"in_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":5},\"~type\":\"knows\"}," + "\"label\":\"knows\"," + "\"type\":\"edge\"," + "\"inVLabel\":\"in-vertex\"" + "}").ToEdge(); Assert.AreEqual("knows", edge.Label); Assert.AreEqual("in-vertex", edge.InVLabel); Assert.Null(edge.OutVLabel); } [Test] public void ToEdge_Should_Throw_When_Required_Attributes_Are_Not_Present() { Assert.Throws<InvalidOperationException>(() => GraphNodeGraphSON1Tests.GetGraphNode( "{" + "\"label\":\"knows\"," + "\"type\":\"edge\"," + "\"inVLabel\":\"in-vertex\"" + "}").ToEdge()); Assert.Throws<InvalidOperationException>(() => GraphNodeGraphSON1Tests.GetGraphNode( "{" + "\"id\":{" + "\"out_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":3}," + "\"local_id\":\"4e78f871-c5c8-11e5-a449-130aecf8e504\",\"in_vertex\":{\"member_id\":0,\"community_id\":680148,\"~label\":\"vertex\",\"group_id\":5},\"~type\":\"knows\"}," + "\"type\":\"edge\"," + "\"inVLabel\":\"in-vertex\"" + "}").ToEdge()); } [Test] public void ToPath_Should_Convert() { const string pathJson = "{\"result\":" + "{" + " \"labels\": [" + " [\"a\"]," + " []," + " [\"c\", \"d\"]," + " [\"e\", \"f\", \"g\"]," + " []" + " ]," + " \"objects\": [" + " {" + " \"id\": {" + " \"member_id\": 0, " + " \"community_id\": 214210, " + " \"~label\": \"person\", " + " \"group_id\": 3 " + " }," + " \"label\": \"person\", " + " \"type\": \"vertex\", " + " \"properties\": { " + " \"name\": [" + " {" + " \"id\": { " + " \"local_id\": \"00000000-0000-7fff-0000-000000000000\", " + " \"~type\": \"name\", " + " \"out_vertex\": { " + " \"member_id\": 0, " + " \"community_id\": 214210, " + " \"~label\": \"person\", " + " \"group_id\": 3 " + " } " + " }, " + " \"value\": \"marko\" " + " }" + " ]," + " \"age\": [ " + " { " + " \"id\": { " + " \"local_id\": \"00000000-0000-8000-0000-000000000000\", " + " \"~type\": \"age\", " + " \"out_vertex\": { " + " \"member_id\": 0, " + " \"community_id\": 214210, " + " \"~label\": \"person\", " + " \"group_id\": 3 " + " } " + " }, " + " \"value\": 29 " + " }" + " ]" + " }" + " }," + " {" + " \"id\": {" + " \"out_vertex\": {" + " \"member_id\": 0, " + " \"community_id\": 214210, " + " \"~label\": \"person\", " + " \"group_id\": 3 " + " }, " + " \"local_id\": \"77cd1b50-ffcc-11e5-aa66-231205ad38c3\", " + " \"in_vertex\": {" + " \"member_id\": 0, " + " \"community_id\": 214210, " + " \"~label\": \"person\", " + " \"group_id\": 5 " + " }, " + " \"~type\": \"knows\" " + " }," + " \"label\": \"knows\", " + " \"type\": \"edge\", " + " \"inVLabel\": \"person\", " + " \"outVLabel\": \"person\", " + " \"inV\": {" + " \"member_id\": 0," + " \"community_id\": 214210," + " \"~label\": \"person\"," + " \"group_id\": 5" + " }," + " \"outV\": {" + " \"member_id\": 0," + " \"community_id\": 214210," + " \"~label\": \"person\"," + " \"group_id\": 3" + " }," + " \"properties\": {" + " \"weight\": 1.0" + " }" + " }" + " ]" + "}}"; var result = new GraphNode(pathJson); var path = result.ToPath(); CollectionAssert.AreEqual( new string[][] { new [] { "a" }, new string[0], new[] { "c", "d" }, new[] { "e", "f", "g" }, new string[0] }, path.Labels); Assert.AreEqual(2, path.Objects.Count); Assert.AreEqual("person", path.Objects.First().ToVertex().Label); Assert.AreEqual("knows", path.Objects.Skip(1).First().ToEdge().Label); //Verify implicit result var path2 = (Path) result; CollectionAssert.AreEqual(path.Labels, path2.Labels); Assert.AreEqual(path.Objects.Count, path2.Objects.Count); var path3 = (IPath) path; Assert.AreEqual(path.Objects.Count, path3.Objects.Count); var path4 = result.To<IPath>(); Assert.AreEqual(path.Objects.Count, path4.Objects.Count); } [Test] public void Should_Be_Serializable() { var json = "{\"something\":true}"; var result = JsonConvert.DeserializeObject<GraphNode>(json); Assert.True(result.Get<bool>("something")); Assert.AreEqual(json, JsonConvert.SerializeObject(result)); json = "{\"something\":{\"val\":1}}"; result = JsonConvert.DeserializeObject<GraphNode>(json); var objectTree = result.Get<GraphNode>("something"); Assert.NotNull(objectTree); Assert.AreEqual(1D, objectTree.Get<double>("val")); Assert.AreEqual(json, JsonConvert.SerializeObject(result)); } private static GraphNode GetGraphNode(string json) { return new GraphNode("{\"result\": " + json + "}"); } } }
using System; using Server; using Server.Misc; using Server.Items; namespace Server.Mobiles { [CorpseName("a chaos dragoon elite corpse")] public class ChaosDragoonElite : BaseCreature { [Constructable] public ChaosDragoonElite() : base(AIType.AI_Mage, FightMode.Closest, 10, 1, 0.15, 0.4) { Name = "a chaos dragoon elite"; Body = 0x190; Hue = Utility.RandomSkinHue(); SetStr(276, 350); SetDex(66, 90); SetInt(126, 150); SetHits(276, 350); SetDamage(29, 34); SetDamageType(ResistanceType.Physical, 100); /*SetResistance(ResistanceType.Physical, 45, 55); SetResistance(ResistanceType.Fire, 15, 25); SetResistance(ResistanceType.Cold, 50); SetResistance(ResistanceType.Poison, 25, 35); SetResistance(ResistanceType.Energy, 25, 35);*/ SetSkill(SkillName.Tactics, 80.1, 100.0); SetSkill(SkillName.MagicResist, 100.1, 110.0); SetSkill(SkillName.Anatomy, 80.1, 100.0); SetSkill(SkillName.Magery, 85.1, 100.0); SetSkill(SkillName.EvalInt, 85.1, 100.0); SetSkill(SkillName.Swords, 72.5, 95.0); SetSkill(SkillName.Fencing, 85.1, 100); SetSkill(SkillName.Macing, 85.1, 100); Fame = 8000; Karma = -8000; CraftResource res = CraftResource.None;; switch (Utility.Random(6)) { case 0: res = CraftResource.BlackScales; break; case 1: res = CraftResource.RedScales; break; case 2: res = CraftResource.BlueScales; break; case 3: res = CraftResource.YellowScales; break; case 4: res = CraftResource.GreenScales; break; case 5: res = CraftResource.WhiteScales; break; } BaseWeapon melee = null; switch (Utility.Random(3)) { case 0: melee = new Kryss(); break; case 1: melee = new Broadsword(); break; case 2: melee = new Katana(); break; } melee.Movable = false; AddItem(melee); DragonChest Tunic = new DragonChest(); Tunic.Resource = res; Tunic.Movable = false; AddItem(Tunic); DragonLegs Legs = new DragonLegs(); Legs.Resource = res; Legs.Movable = false; AddItem(Legs); DragonArms Arms = new DragonArms(); Arms.Resource = res; Arms.Movable = false; AddItem(Arms); DragonGloves Gloves = new DragonGloves(); Gloves.Resource = res; Gloves.Movable = false; AddItem(Gloves); DragonHelm Helm = new DragonHelm(); Helm.Resource = res; Helm.Movable = false; AddItem(Helm); ChaosShield shield = new ChaosShield(); shield.Movable = false; AddItem(shield); AddItem(new Boots(0x455)); AddItem(new Shirt(Utility.RandomMetalHue())); int amount = Utility.RandomMinMax(1, 3); switch (res) { case CraftResource.BlackScales: AddItem(new BlackScales(amount)); break; case CraftResource.RedScales: AddItem(new RedScales(amount)); break; case CraftResource.BlueScales: AddItem(new BlueScales(amount)); break; case CraftResource.YellowScales: AddItem(new YellowScales(amount)); break; case CraftResource.GreenScales: AddItem(new GreenScales(amount)); break; case CraftResource.WhiteScales: AddItem(new WhiteScales(amount)); break; } switch (Utility.Random(9)) { case 0: res = CraftResource.MDullcopper; break; case 1: res = CraftResource.MShadow; break; case 2: res = CraftResource.MCopper; break; case 3: res = CraftResource.MBronze; break; case 4: res = CraftResource.MGold; break; case 5: res = CraftResource.MAgapite; break; case 6: res = CraftResource.MVerite; break; case 7: res = CraftResource.MValorite; break; case 8: res = CraftResource.MIron; break; } SwampDragon mt = new SwampDragon(); mt.HasBarding = true; mt.BardingResource = res; mt.BardingHP = mt.BardingMaxHP; mt.Rider = this; } public override int GetIdleSound() { return 0x2CE; } public override int GetDeathSound() { return 0x2CC; } public override int GetHurtSound() { return 0x2D1; } public override int GetAttackSound() { return 0x2C8; } public override void GenerateLoot() { AddLoot(LootPack.Rich); AddLoot(LootPack.Gems); } public override bool HasBreath { get { return true; } } public override bool AutoDispel { get { return true; } } public override bool BardImmune { get { return !Core.AOS; } } public override bool CanRummageCorpses { get { return true; } } public override bool AlwaysMurderer { get { return true; } } public override bool ShowFameTitle { get { return false; } } public override bool OnBeforeDeath() { IMount mount = this.Mount; if ( mount != null ) { if ( mount is SwampDragon ) ((SwampDragon)mount).HasBarding = false; mount.Rider = null; } return base.OnBeforeDeath(); } public override void AlterMeleeDamageTo(Mobile to, ref int damage) { if ( to is Dragon || to is WhiteWyrm || to is SwampDragon || to is Drake || to is Nightmare || to is Hiryu || to is LesserHiryu || to is Daemon ) damage *= 3; } public ChaosDragoonElite(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
// // TrackEditorDialog.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Mono.Addins; using Gtk; using Hyena.Gui; using Hyena.Widgets; using Banshee.Base; using Banshee.Kernel; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration.Schema; using Banshee.Widgets; using Banshee.Gui.Dialogs; using Banshee.Collection.Gui; using Hyena.Data; using Selection=Hyena.Collections.Selection; namespace Banshee.Gui.TrackEditor { public class TrackEditorDialog : BansheeDialog { public delegate void EditorTrackOperationClosure (EditorTrackInfo track); private VBox main_vbox; private Frame header_image_frame; private Image header_image; private Label header_title_label; private Label header_artist_label; private Label header_album_label; private Label edit_notif_label; private object tooltip_host; private DateTime dialog_launch_datetime = DateTime.Now; private Notebook notebook; public Notebook Notebook { get { return notebook; } } private Button nav_backward_button; private Button nav_forward_button; private PulsingButton sync_all_button; private EditorMode mode; internal EditorMode Mode { get { return mode; } } private bool readonly_tabs = false; private List<ITrackEditorPage> pages = new List<ITrackEditorPage> (); public event EventHandler Navigated; private TrackEditorDialog (TrackListModel model, Selection selection, EditorMode mode) : this (model, selection, mode, false) { } private TrackEditorDialog (TrackListModel model, Selection selection, EditorMode mode, bool readonlyTabs) : base ( mode == EditorMode.Edit ? Catalog.GetString ("Track Editor") : Catalog.GetString ("Track Properties")) { readonly_tabs = readonlyTabs; this.mode = mode; LoadTrackModel (model, selection); if (mode == EditorMode.Edit || readonly_tabs) { WidthRequest = 525; if (mode == EditorMode.Edit) { AddStockButton (Stock.Cancel, ResponseType.Cancel); AddStockButton (Stock.Save, ResponseType.Ok); } } else { SetSizeRequest (400, 500); } if (mode == EditorMode.View) { AddStockButton (Stock.Close, ResponseType.Close, true); } tooltip_host = TooltipSetter.CreateHost (); AddNavigationButtons (); main_vbox = new VBox (); main_vbox.Spacing = 12; main_vbox.BorderWidth = 0; main_vbox.Show (); VBox.PackStart (main_vbox, true, true, 0); BuildHeader (); BuildNotebook (); BuildFooter (); LoadModifiers (); LoadTrackToEditor (); } #region UI Building private void AddNavigationButtons () { if (TrackCount <= 1) { return; } nav_backward_button = new Button (Stock.GoBack); nav_backward_button.UseStock = true; nav_backward_button.Clicked += delegate { NavigateBackward (); }; nav_backward_button.Show (); TooltipSetter.Set (tooltip_host, nav_backward_button, Catalog.GetString ("Show the previous track")); nav_forward_button = new Button (Stock.GoForward); nav_forward_button.UseStock = true; nav_forward_button.Clicked += delegate { NavigateForward (); }; nav_forward_button.Show (); TooltipSetter.Set (tooltip_host, nav_forward_button, Catalog.GetString ("Show the next track")); ActionArea.PackStart (nav_backward_button, false, false, 0); ActionArea.PackStart (nav_forward_button, false, false, 0); ActionArea.SetChildSecondary (nav_backward_button, true); ActionArea.SetChildSecondary (nav_forward_button, true); } private void BuildHeader () { Table header = new Table (3, 3, false); header.ColumnSpacing = 5; header_image_frame = new Frame (); header_image = new Image (); header_image.IconName = "media-optical"; header_image.PixelSize = 64; header_image_frame.Add ( CoverArtEditor.For (header_image, (x, y) => true, () => CurrentTrack, () => LoadCoverArt (CurrentTrack) ) ); header.Attach (header_image_frame, 0, 1, 0, 3, AttachOptions.Fill, AttachOptions.Expand, 0, 0); AddHeaderRow (header, 0, Catalog.GetString ("Title:"), out header_title_label); AddHeaderRow (header, 1, Catalog.GetString ("Artist:"), out header_artist_label); AddHeaderRow (header, 2, Catalog.GetString ("Album:"), out header_album_label); header.ShowAll (); main_vbox.PackStart (header, false, false, 0); } private TrackInfo CurrentTrack { get { return TrackCount == 0 ? null : GetTrack (CurrentTrackIndex); } } private void AddHeaderRow (Table header, uint row, string title, out Label label) { Label title_label = new Label (); title_label.Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (title)); title_label.Xalign = 0.0f; header.Attach (title_label, 1, 2, row, row + 1, AttachOptions.Fill, AttachOptions.Expand, 0, 0); label = new Label (); label.Xalign = 0.0f; label.Ellipsize = Pango.EllipsizeMode.End; header.Attach (label, 2, 3, row, row + 1, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Expand, 0, 0); } private void BuildNotebook () { notebook = new Notebook (); notebook.Show (); Gtk.Widget page_to_focus = null; foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Gui/TrackEditor/NotebookPage")) { try { ITrackEditorPage page = (ITrackEditorPage)node.CreateInstance (); bool show = false; if (mode == EditorMode.Edit && (page.PageType != PageType.ViewOnly)) { show = true; } else if (mode == EditorMode.View) { if (readonly_tabs) { show = page.PageType != PageType.EditOnly; } else { show = page.PageType == PageType.View || page.PageType == PageType.ViewOnly; } } if (show) { if (page is StatisticsPage && mode == EditorMode.View) { page_to_focus = (StatisticsPage)page; } pages.Add (page); page.Initialize (this); page.Widget.Show (); } } catch (Exception e) { Hyena.Log.Exception ("Failed to initialize NotebookPage extension node. Ensure it implements ITrackEditorPage.", e); } } pages.Sort (delegate (ITrackEditorPage a, ITrackEditorPage b) { return a.Order.CompareTo (b.Order); }); foreach (ITrackEditorPage page in pages) { Container container = page.Widget as Container; if (container == null) { VBox box = new VBox (); box.PackStart (page.Widget, true, true, 0); container = box; } container.BorderWidth = 12; notebook.AppendPage (container, page.TabWidget == null ? new Label (page.Title) : page.TabWidget); } main_vbox.PackStart (notebook, true, true, 0); if (page_to_focus != null) { notebook.CurrentPage = notebook.PageNum (page_to_focus); } } private void BuildFooter () { if (mode == EditorMode.View || TrackCount < 2) { return; } HBox button_box = new HBox (); button_box.Spacing = 6; if (TrackCount > 1) { sync_all_button = new PulsingButton (); sync_all_button.FocusInEvent += delegate { ForeachWidget<SyncButton> (delegate (SyncButton button) { button.StartPulsing (); }); }; sync_all_button.FocusOutEvent += delegate { if (sync_all_button.State == StateType.Prelight) { return; } ForeachWidget<SyncButton> (delegate (SyncButton button) { button.StopPulsing (); }); }; sync_all_button.StateChanged += delegate { if (sync_all_button.HasFocus) { return; } ForeachWidget<SyncButton> (delegate (SyncButton button) { if (sync_all_button.State == StateType.Prelight) { button.StartPulsing (); } else { button.StopPulsing (); } }); }; sync_all_button.Clicked += delegate { InvokeFieldSync (); }; Alignment alignment = new Alignment (0.5f, 0.5f, 0.0f, 0.0f); HBox box = new HBox (); box.Spacing = 2; box.PackStart (new Image (Stock.Copy, IconSize.Button), false, false, 0); box.PackStart (new Label (Catalog.GetString ("Sync all field _values")), false, false, 0); alignment.Add (box); sync_all_button.Add (alignment); TooltipSetter.Set (tooltip_host, sync_all_button, Catalog.GetString ( "Apply the values of all common fields set for this track to all of the tracks selected in this editor")); button_box.PackStart (sync_all_button, false, false, 0); foreach (Widget child in ActionArea.Children) { child.SizeAllocated += OnActionAreaChildSizeAllocated; } edit_notif_label = new Label (); edit_notif_label.Xalign = 1.0f; button_box.PackEnd (edit_notif_label, false, false, 0); } main_vbox.PackStart (button_box, false, false, 0); button_box.ShowAll (); } private void LoadModifiers () { foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Gui/TrackEditor/Modifier")) { try { ITrackEditorModifier mod = (ITrackEditorModifier)node.CreateInstance (); mod.Modify (this); } catch (Exception e) { Hyena.Log.Exception ("Failed to initialize TrackEditor/Modifier extension node. Ensure it implements ITrackEditorModifier.", e); } } } public void ForeachWidget<T> (WidgetAction<T> action) where T : class { for (int i = 0; i < notebook.NPages; i++) { GtkUtilities.ForeachWidget (notebook.GetNthPage (i) as Container, action); } } private void InvokeFieldSync () { for (int i = 0; i < notebook.NPages; i++) { var field_page = notebook.GetNthPage (i) as FieldPage; if (field_page != null) { foreach (var slot in field_page.FieldSlots) { if (slot.Sync != null && (slot.SyncButton == null || slot.SyncButton.Sensitive)) { slot.Sync (); } } } } } private int action_area_children_allocated = 0; private void OnActionAreaChildSizeAllocated (object o, SizeAllocatedArgs args) { Widget [] children = ActionArea.Children; if (++action_area_children_allocated != children.Length) { return; } sync_all_button.WidthRequest = Math.Max (sync_all_button.Allocation.Width, (children[1].Allocation.X + children[1].Allocation.Width) - children[0].Allocation.X - 1); } #endregion #region Track Model/Changes API private CachedList<DatabaseTrackInfo> db_selection; private List<TrackInfo> memory_selection; private Dictionary<TrackInfo, EditorTrackInfo> edit_map = new Dictionary<TrackInfo, EditorTrackInfo> (); private int current_track_index; protected void LoadTrackModel (TrackListModel model, Selection selection) { DatabaseTrackListModel db_model = model as DatabaseTrackListModel; if (db_model != null) { db_selection = CachedList<DatabaseTrackInfo>.CreateFromModelAndSelection (db_model, selection); } else { memory_selection = new List<TrackInfo> (); var items = new ModelSelection<TrackInfo> (model, selection); foreach (TrackInfo track in items) { memory_selection.Add (track); } } } public void LoadTrackToEditor () { TrackInfo current_track = null; EditorTrackInfo editor_track = LoadTrack (current_track_index, out current_track); if (editor_track == null) { return; } // Update the Header header_title_label.Text = current_track.DisplayTrackTitle; header_artist_label.Text = current_track.DisplayArtistName; header_album_label.Text = current_track.DisplayAlbumTitle; if (edit_notif_label != null) { edit_notif_label.Markup = String.Format (Catalog.GetString ("<i>Editing {0} of {1} items</i>"), CurrentTrackIndex + 1, TrackCount); } LoadCoverArt (current_track); // Disconnect all the undo adapters ForeachWidget<ICanUndo> (delegate (ICanUndo undoable) { undoable.DisconnectUndo (); }); foreach (ITrackEditorPage page in pages) { page.LoadTrack (editor_track); } // Connect all the undo adapters ForeachWidget<ICanUndo> (delegate (ICanUndo undoable) { undoable.ConnectUndo (editor_track); }); // Update Navigation if (TrackCount > 0 && nav_backward_button != null && nav_forward_button != null) { nav_backward_button.Sensitive = CanGoBackward; nav_forward_button.Sensitive = CanGoForward; } // If there was a widget focused already (eg the Title entry), GrabFocus on it, // which causes its text to be selected, ready for editing. Widget child = FocusChild; while (child != null) { Container container = child as Container; if (container != null) { child = container.FocusChild; } else if (child != null) { child.GrabFocus (); child = null; } } } private void LoadCoverArt (TrackInfo current_track) { if (current_track == null) return; var artwork = ServiceManager.Get<ArtworkManager> (); var cover_art = artwork.LookupScalePixbuf (current_track.ArtworkId, 64); header_image.Clear (); header_image.Pixbuf = cover_art; if (cover_art == null) { header_image.IconName = "media-optical"; header_image.PixelSize = 64; header_image_frame.ShadowType = ShadowType.None; } else { header_image_frame.ShadowType = ShadowType.In; } header_image.QueueDraw (); } public void ForeachNonCurrentTrack (EditorTrackOperationClosure closure) { for (int i = 0; i < TrackCount; i++) { if (i == current_track_index) { continue; } EditorTrackInfo track = LoadTrack (i); if (track != null) { closure (track); } } } public EditorTrackInfo LoadTrack (int index) { return LoadTrack (index, true); } public EditorTrackInfo LoadTrack (int index, bool alwaysLoad) { TrackInfo source_track; return LoadTrack (index, alwaysLoad, out source_track); } private EditorTrackInfo LoadTrack (int index, out TrackInfo sourceTrack) { return LoadTrack (index, true, out sourceTrack); } private EditorTrackInfo LoadTrack (int index, bool alwaysLoad, out TrackInfo sourceTrack) { sourceTrack = GetTrack (index); EditorTrackInfo editor_track = null; if (sourceTrack == null) { // Something bad happened here return null; } if (!edit_map.TryGetValue (sourceTrack, out editor_track) && alwaysLoad) { editor_track = new EditorTrackInfo (sourceTrack); editor_track.EditorIndex = index; editor_track.EditorCount = TrackCount; edit_map.Add (sourceTrack, editor_track); } return editor_track; } private TrackInfo GetTrack (int index) { return db_selection != null ? db_selection[index] : memory_selection[index]; } protected virtual void OnNavigated () { EventHandler handler = Navigated; if (handler != null) { handler (this, EventArgs.Empty); } } public void NavigateForward () { if (current_track_index < TrackCount - 1) { current_track_index++; LoadTrackToEditor (); OnNavigated (); } } public void NavigateBackward () { if (current_track_index > 0) { current_track_index--; LoadTrackToEditor (); OnNavigated (); } } public int TrackCount { get { return db_selection != null ? db_selection.Count : memory_selection.Count; } } public int CurrentTrackIndex { get { return current_track_index; } } public bool CanGoBackward { get { return current_track_index > 0; } } public bool CanGoForward { get { return current_track_index >= 0 && current_track_index < TrackCount - 1; } } #endregion #region Saving public void Save () { List<int> primary_sources = new List<int> (); // TODO: wrap in db transaction try { DatabaseTrackInfo.NotifySaved = false; for (int i = 0; i < TrackCount; i++) { // Save any tracks that were actually loaded into the editor EditorTrackInfo track = LoadTrack (i, false); if (track == null || track.SourceTrack == null) { continue; } SaveTrack (track); if (track.SourceTrack is DatabaseTrackInfo) { // If the source track is from the database, save its parent for notification later int id = (track.SourceTrack as DatabaseTrackInfo).PrimarySourceId; if (!primary_sources.Contains (id)) { primary_sources.Add (id); } } } // Finally, notify the affected primary sources foreach (int id in primary_sources) { PrimarySource psrc = PrimarySource.GetById (id); if (psrc != null) { psrc.NotifyTracksChanged (); } } } finally { DatabaseTrackInfo.NotifySaved = true; } } private void SaveTrack (EditorTrackInfo track) { TrackInfo.ExportableMerge (track, track.SourceTrack); track.SourceTrack.Update (); if (track.SourceTrack.TrackEqual (ServiceManager.PlayerEngine.CurrentTrack)) { TrackInfo.ExportableMerge (track, ServiceManager.PlayerEngine.CurrentTrack); ServiceManager.PlayerEngine.TrackInfoUpdated (); } } #endregion #region Static Helpers public static void RunEdit (TrackListModel model, Selection selection) { Run (model, selection, EditorMode.Edit); } public static void RunView (TrackListModel model, Selection selection, bool readonlyTabs) { Run (model, selection, EditorMode.View, readonlyTabs); } public static void Run (TrackListModel model, Selection selection, EditorMode mode) { Run (new TrackEditorDialog (model, selection, mode)); } private static void Run (TrackListModel model, Selection selection, EditorMode mode, bool readonlyTabs) { Run (new TrackEditorDialog (model, selection, mode, readonlyTabs)); } private static void Run (TrackEditorDialog track_editor) { track_editor.Response += delegate (object o, ResponseArgs args) { if (args.ResponseId == ResponseType.Ok) { track_editor.Save (); } else { int changed_count = 0; for (int i = 0; i < track_editor.TrackCount; i++) { EditorTrackInfo track = track_editor.LoadTrack (i, false); if (track != null) { track.GenerateDiff (); if (track.DiffCount > 0) { changed_count++; } } } if (changed_count == 0) { track_editor.Destroy (); return; } HigMessageDialog message_dialog = new HigMessageDialog ( track_editor, DialogFlags.Modal, MessageType.Warning, ButtonsType.None, String.Format (Catalog.GetPluralString ( "Save the changes made to the open track?", "Save the changes made to {0} of {1} open tracks?", track_editor.TrackCount), changed_count, track_editor.TrackCount), String.Empty ); UpdateCancelMessage (track_editor, message_dialog); uint timeout = 0; timeout = GLib.Timeout.Add (1000, delegate { bool result = UpdateCancelMessage (track_editor, message_dialog); if (!result) { timeout = 0; } return result; }); message_dialog.AddButton (Catalog.GetString ("Close _without Saving"), ResponseType.Close, false); message_dialog.AddButton (Stock.Cancel, ResponseType.Cancel, false); message_dialog.AddButton (Stock.Save, ResponseType.Ok, true); try { switch ((ResponseType)message_dialog.Run ()) { case ResponseType.Ok: track_editor.Save (); break; case ResponseType.Close: break; case ResponseType.Cancel: case ResponseType.DeleteEvent: return; } } finally { if (timeout > 0) { GLib.Source.Remove (timeout); } message_dialog.Destroy (); } } track_editor.Destroy (); }; //track_editor.Run (); track_editor.Show (); } private static bool UpdateCancelMessage (TrackEditorDialog trackEditor, HigMessageDialog messageDialog) { if (messageDialog == null) { return false; } messageDialog.MessageLabel.Text = String.Format (Catalog.GetString ( "If you don't save, changes from the last {0} will be permanently lost."), Banshee.Sources.DurationStatusFormatters.ApproximateVerboseFormatter ( DateTime.Now - trackEditor.dialog_launch_datetime ) ); return messageDialog.IsMapped; } #endregion } }
#if NET20 // Taken and adapted from: https://github.com/mono/mono/blob/mono-3.12.1/mcs/class/System/System.Collections.Generic/RBTree.cs // // Authors: // Raja R Harinath <[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.CodeDom.Compiler; // ReSharper disable All namespace System.Collections.Generic { [GeneratedCode("Mono BCL", "3.12.1")] // ignore in code analysis [Serializable] internal class RBTree : IEnumerable, IEnumerable<RBTree.Node> { public interface INodeHelper<T> { int Compare(T key, Node node); Node CreateNode(T key); } public abstract class Node { public Node left, right; uint size_black; const uint black_mask = 1; const int black_shift = 1; public bool IsBlack { get { return (size_black & black_mask) == black_mask; } set { size_black = value ? (size_black | black_mask) : (size_black & ~black_mask); } } public uint Size { get { return size_black >> black_shift; } set { size_black = (value << black_shift) | (size_black & black_mask); } } public uint FixSize() { Size = 1; if (left != null) Size += left.Size; if (right != null) Size += right.Size; return Size; } public Node() { size_black = 2; // Size == 1, IsBlack = false } public abstract void SwapValue(Node other); } Node root; object hlp; uint version; [ThreadStatic] static List<Node> cached_path; static List<Node> alloc_path() { if (cached_path == null) return new List<Node>(); List<Node> path = cached_path; cached_path = null; return path; } static void release_path(List<Node> path) { if (cached_path == null || cached_path.Capacity < path.Capacity) { path.Clear(); cached_path = path; } } public RBTree(object hlp) { // hlp is INodeHelper<T> for some T this.hlp = hlp; } public void Clear() { root = null; ++version; } // if key is already in the tree, return the node associated with it // if not, insert new_node into the tree, and return it public Node Intern<T>(T key, Node new_node) { if (root == null) { if (new_node == null) new_node = ((INodeHelper<T>)hlp).CreateNode(key); root = new_node; root.IsBlack = true; ++version; return root; } List<Node> path = alloc_path(); int in_tree_cmp = find_key(key, path); Node retval = path[path.Count - 1]; if (retval == null) { if (new_node == null) new_node = ((INodeHelper<T>)hlp).CreateNode(key); retval = do_insert(in_tree_cmp, new_node, path); } // no need for a try .. finally, this is only used to mitigate allocations release_path(path); return retval; } // returns the just-removed node (or null if the value wasn't in the tree) public Node Remove<T>(T key) { if (root == null) return null; List<Node> path = alloc_path(); int in_tree_cmp = find_key(key, path); Node retval = null; if (in_tree_cmp == 0) retval = do_remove(path); // no need for a try .. finally, this is only used to mitigate allocations release_path(path); return retval; } public Node Lookup<T>(T key) { INodeHelper<T> hlp = (INodeHelper<T>)this.hlp; Node current = root; while (current != null) { int c = hlp.Compare(key, current); if (c == 0) break; current = c < 0 ? current.left : current.right; } return current; } public void Bound<T>(T key, ref Node lower, ref Node upper) { INodeHelper<T> hlp = (INodeHelper<T>)this.hlp; Node current = root; while (current != null) { int c = hlp.Compare(key, current); if (c <= 0) upper = current; if (c >= 0) lower = current; if (c == 0) break; current = c < 0 ? current.left : current.right; } } public int Count { get { return root == null ? 0 : (int)root.Size; } } public Node this[int index] { get { if (index < 0 || index >= Count) throw new IndexOutOfRangeException("index"); Node current = root; while (current != null) { int left_size = current.left == null ? 0 : (int)current.left.Size; if (index == left_size) return current; if (index < left_size) { current = current.left; } else { index -= left_size + 1; current = current.right; } } throw new SystemException("Internal Error: index calculation"); } } public NodeEnumerator GetEnumerator() { return new NodeEnumerator(this); } // Get an enumerator that starts at 'key' or the next higher element in the tree public NodeEnumerator GetSuffixEnumerator<T>(T key) { var pennants = new Stack<Node>(); INodeHelper<T> hlp = (INodeHelper<T>)this.hlp; Node current = root; while (current != null) { int c = hlp.Compare(key, current); if (c <= 0) pennants.Push(current); if (c == 0) break; current = c < 0 ? current.left : current.right; } return new NodeEnumerator(this, pennants); } IEnumerator<Node> IEnumerable<Node>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // Pre-condition: root != null int find_key<T>(T key, List<Node> path) { INodeHelper<T> hlp = (INodeHelper<T>)this.hlp; int c = 0; Node sibling = null; Node current = root; if (path != null) path.Add(root); while (current != null) { c = hlp.Compare(key, current); if (c == 0) return c; if (c < 0) { sibling = current.right; current = current.left; } else { sibling = current.left; current = current.right; } if (path != null) { path.Add(sibling); path.Add(current); } } return c; } Node do_insert(int in_tree_cmp, Node current, List<Node> path) { path[path.Count - 1] = current; Node parent = path[path.Count - 3]; if (in_tree_cmp < 0) parent.left = current; else parent.right = current; for (int i = 0; i < path.Count - 2; i += 2) ++path[i].Size; if (!parent.IsBlack) rebalance_insert(path); if (!root.IsBlack) throw new SystemException("Internal error: root is not black"); ++version; return current; } Node do_remove(List<Node> path) { int curpos = path.Count - 1; Node current = path[curpos]; if (current.left != null) { Node pred = right_most(current.left, current.right, path); current.SwapValue(pred); if (pred.left != null) { Node ppred = pred.left; path.Add(null); path.Add(ppred); pred.SwapValue(ppred); } } else if (current.right != null) { Node succ = current.right; path.Add(null); path.Add(succ); current.SwapValue(succ); } curpos = path.Count - 1; current = path[curpos]; if (current.Size != 1) throw new SystemException("Internal Error: red-black violation somewhere"); // remove it from our data structures path[curpos] = null; node_reparent(curpos == 0 ? null : path[curpos - 2], current, 0, null); for (int i = 0; i < path.Count - 2; i += 2) --path[i].Size; if (current.IsBlack) { current.IsBlack = false; if (curpos != 0) rebalance_delete(path); } if (root != null && !root.IsBlack) throw new SystemException("Internal Error: root is not black"); ++version; return current; } // Pre-condition: current is red void rebalance_insert(List<Node> path) { int curpos = path.Count - 1; do { // parent == curpos-2, uncle == curpos-3, grandpa == curpos-4 if (path[curpos - 3] == null || path[curpos - 3].IsBlack) { rebalance_insert__rotate_final(curpos, path); return; } path[curpos - 2].IsBlack = path[curpos - 3].IsBlack = true; curpos -= 4; // move to the grandpa if (curpos == 0) // => current == root return; path[curpos].IsBlack = false; } while (!path[curpos - 2].IsBlack); } // Pre-condition: current is black void rebalance_delete(List<Node> path) { int curpos = path.Count - 1; do { Node sibling = path[curpos - 1]; // current is black => sibling != null if (!sibling.IsBlack) { // current is black && sibling is red // => both sibling.left and sibling.right are black, and are not null curpos = ensure_sibling_black(curpos, path); // one of the nephews became the new sibling -- in either case, sibling != null sibling = path[curpos - 1]; } if ((sibling.left != null && !sibling.left.IsBlack) || (sibling.right != null && !sibling.right.IsBlack)) { rebalance_delete__rotate_final(curpos, path); return; } sibling.IsBlack = false; curpos -= 2; // move to the parent if (curpos == 0) return; } while (path[curpos].IsBlack); path[curpos].IsBlack = true; } void rebalance_insert__rotate_final(int curpos, List<Node> path) { Node current = path[curpos]; Node parent = path[curpos - 2]; Node grandpa = path[curpos - 4]; uint grandpa_size = grandpa.Size; Node new_root; bool l1 = parent == grandpa.left; bool l2 = current == parent.left; if (l1 && l2) { grandpa.left = parent.right; parent.right = grandpa; new_root = parent; } else if (l1 && !l2) { grandpa.left = current.right; current.right = grandpa; parent.right = current.left; current.left = parent; new_root = current; } else if (!l1 && l2) { grandpa.right = current.left; current.left = grandpa; parent.left = current.right; current.right = parent; new_root = current; } else { // (!l1 && !l2) grandpa.right = parent.left; parent.left = grandpa; new_root = parent; } grandpa.FixSize(); grandpa.IsBlack = false; if (new_root != parent) parent.FixSize(); /* parent is red already, so no need to set it */ new_root.IsBlack = true; node_reparent(curpos == 4 ? null : path[curpos - 6], grandpa, grandpa_size, new_root); } // Pre-condition: sibling is black, and one of sibling.left and sibling.right is red void rebalance_delete__rotate_final(int curpos, List<Node> path) { //Node current = path [curpos]; Node sibling = path[curpos - 1]; Node parent = path[curpos - 2]; uint parent_size = parent.Size; bool parent_was_black = parent.IsBlack; Node new_root; if (parent.right == sibling) { // if far nephew is black if (sibling.right == null || sibling.right.IsBlack) { // => near nephew is red, move it up Node nephew = sibling.left; parent.right = nephew.left; nephew.left = parent; sibling.left = nephew.right; nephew.right = sibling; new_root = nephew; } else { parent.right = sibling.left; sibling.left = parent; sibling.right.IsBlack = true; new_root = sibling; } } else { // if far nephew is black if (sibling.left == null || sibling.left.IsBlack) { // => near nephew is red, move it up Node nephew = sibling.right; parent.left = nephew.right; nephew.right = parent; sibling.right = nephew.left; nephew.left = sibling; new_root = nephew; } else { parent.left = sibling.right; sibling.right = parent; sibling.left.IsBlack = true; new_root = sibling; } } parent.FixSize(); parent.IsBlack = true; if (new_root != sibling) sibling.FixSize(); /* sibling is already black, so no need to set it */ new_root.IsBlack = parent_was_black; node_reparent(curpos == 2 ? null : path[curpos - 4], parent, parent_size, new_root); } // Pre-condition: sibling is red (=> parent, sibling.left and sibling.right are black) int ensure_sibling_black(int curpos, List<Node> path) { Node current = path[curpos]; Node sibling = path[curpos - 1]; Node parent = path[curpos - 2]; bool current_on_left; uint parent_size = parent.Size; if (parent.right == sibling) { parent.right = sibling.left; sibling.left = parent; current_on_left = true; } else { parent.left = sibling.right; sibling.right = parent; current_on_left = false; } parent.FixSize(); parent.IsBlack = false; sibling.IsBlack = true; node_reparent(curpos == 2 ? null : path[curpos - 4], parent, parent_size, sibling); // accomodate the rotation if (curpos + 1 == path.Count) { path.Add(null); path.Add(null); } path[curpos - 2] = sibling; path[curpos - 1] = current_on_left ? sibling.right : sibling.left; path[curpos] = parent; path[curpos + 1] = current_on_left ? parent.right : parent.left; path[curpos + 2] = current; return curpos + 2; } void node_reparent(Node orig_parent, Node orig, uint orig_size, Node updated) { if (updated != null && updated.FixSize() != orig_size) throw new SystemException("Internal error: rotation"); if (orig == root) root = updated; else if (orig == orig_parent.left) orig_parent.left = updated; else if (orig == orig_parent.right) orig_parent.right = updated; else throw new SystemException("Internal error: path error"); } // Pre-condition: current != null static Node right_most(Node current, Node sibling, List<Node> path) { for (;;) { path.Add(sibling); path.Add(current); if (current.right == null) return current; sibling = current.left; current = current.right; } } [Serializable] public struct NodeEnumerator : IEnumerator, IEnumerator<Node> { RBTree tree; uint version; Stack<Node> pennants, init_pennants; internal NodeEnumerator(RBTree tree) : this() { this.tree = tree; version = tree.version; } internal NodeEnumerator(RBTree tree, Stack<Node> init_pennants) : this(tree) { this.init_pennants = init_pennants; } public void Reset() { check_version(); pennants = null; } public Node Current { get { return pennants.Peek(); } } object IEnumerator.Current { get { check_current(); return Current; } } public bool MoveNext() { check_version(); Node next; if (pennants == null) { if (tree.root == null) return false; if (init_pennants != null) { pennants = init_pennants; init_pennants = null; return pennants.Count != 0; } pennants = new Stack<Node>(); next = tree.root; } else { if (pennants.Count == 0) return false; Node current = pennants.Pop(); next = current.right; } for (; next != null; next = next.left) pennants.Push(next); return pennants.Count != 0; } public void Dispose() { tree = null; pennants = null; } void check_version() { if (tree == null) throw new ObjectDisposedException("enumerator"); if (version != tree.version) throw new InvalidOperationException("tree modified"); } internal void check_current() { check_version(); if (pennants == null || pennants.Count == 0) throw new InvalidOperationException("Enumerator is before the first element or after the last element"); } } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using Microsoft.Build.BuildEngine.Shared; using System.Collections.Generic; namespace Microsoft.Build.BuildEngine { internal static class ExpressionShredder { /// <summary> /// Splits an expression into fragments at semi-colons, except where the /// semi-colons are in a macro or separator expression. /// Fragments are trimmed and empty fragments discarded. /// </summary> /// <remarks> /// These complex cases prevent us from doing a simple split on ';': /// (1) Macro expression: @(foo->'xxx;xxx') /// (2) Separator expression: @(foo, 'xxx;xxx') /// (3) Combination: @(foo->'xxx;xxx', 'xxx;xxx') /// We must not split on semicolons in macro or separator expressions like these. /// </remarks> /// <param name="expression">List expression to split</param> /// <owner>danmose</owner> /// <returns>Array of non-empty strings from split list.</returns> internal static List<string> SplitSemiColonSeparatedList(string expression) { List<string> splitList = new List<string>(); int segmentStart = 0; bool insideItemList = false; bool insideQuotedPart = false; string segment; // Walk along the string, keeping track of whether we are in an item list expression. // If we hit a semi-colon or the end of the string and we aren't in an item list, // add the segment to the list. for (int current = 0; current < expression.Length; current++) { switch (expression[current]) { case ';': if (!insideItemList) { // End of segment, so add it to the list segment = expression.Substring(segmentStart, current - segmentStart).Trim(); if (segment.Length > 0) { splitList.Add(segment); } // Move past this semicolon segmentStart = current + 1; } break; case '@': // An '@' immediately followed by a '(' is the start of an item list if (expression.Length > current + 1 && expression[current + 1] == '(') { // Start of item expression insideItemList = true; } break; case ')': if (insideItemList && !insideQuotedPart) { // End of item expression insideItemList = false; } break; case '\'': if (insideItemList) { // Start or end of quoted expression in item expression insideQuotedPart = !insideQuotedPart; } break; } } // Reached the end of the string: what's left is another segment segment = expression.Substring(segmentStart, expression.Length - segmentStart).Trim(); if (segment.Length > 0) { splitList.Add(segment); } return splitList; } /// <summary> /// Given a list of expressions that may contain item list expressions, /// returns a pair of tables of all item names found, as K=Name, V=String.Empty; /// and all metadata not in transforms, as K=Metadata key, V=MetadataReference, /// where metadata key is like "itemname.metadataname" or "metadataname". /// PERF: Tables are null if there are no entries, because this is quite a common case. /// </summary> internal static ItemsAndMetadataPair GetReferencedItemNamesAndMetadata(List<string> expressions) { ItemsAndMetadataPair pair = new ItemsAndMetadataPair(null, null); foreach (string expression in expressions) { GetReferencedItemNamesAndMetadata(expression, 0, expression.Length, ref pair, ShredderOptions.All); } return pair; } /// <summary> /// Returns true if there is a metadata expression (outside of a transform) in the expression. /// </summary> internal static bool ContainsMetadataExpressionOutsideTransform(string expression) { ItemsAndMetadataPair pair = new ItemsAndMetadataPair(null, null); GetReferencedItemNamesAndMetadata(expression, 0, expression.Length, ref pair, ShredderOptions.MetadataOutsideTransforms); bool result = (pair.Metadata?.Count > 0); return result; } /// <summary> /// Given a subexpression, finds referenced item names and inserts them into the table /// as K=Name, V=String.Empty. /// </summary> /// <remarks> /// We can ignore any semicolons in the expression, since we're not itemizing it. /// </remarks> private static void GetReferencedItemNamesAndMetadata(string expression, int start, int end, ref ItemsAndMetadataPair pair, ShredderOptions whatToShredFor) { for (int i = start; i < end; i++) { int restartPoint; if (Sink(expression, ref i, end, '@', '(')) { // Start of a possible item list expression // Store the index to backtrack to if this doesn't turn out to be a well // formed metadata expression. (Subtract one for the increment when we loop around.) restartPoint = i - 1; SinkWhitespace(expression, ref i); int startOfName = i; if (!SinkValidName(expression, ref i, end)) { i = restartPoint; continue; } // '-' is a legitimate char in an item name, but we should match '->' as an arrow // in '@(foo->'x')' rather than as the last char of the item name. // The old regex accomplished this by being "greedy" if (end > i && expression[i - 1] == '-' && expression[i] == '>') { i--; } // Grab the name, but continue to verify it's a well-formed expression // before we store it. string name = expression.Substring(startOfName, i - startOfName); SinkWhitespace(expression, ref i); // If there's an '->' eat it and the subsequent quoted expression if (Sink(expression, ref i, end, '-', '>')) { SinkWhitespace(expression, ref i); if (!SinkSingleQuotedExpression(expression, ref i, end)) { i = restartPoint; continue; } } SinkWhitespace(expression, ref i); // If there's a ',', eat it and the subsequent quoted expression if (Sink(expression, ref i, ',')) { SinkWhitespace(expression, ref i); if (!Sink(expression, ref i, '\'')) { i = restartPoint; continue; } int closingQuote = expression.IndexOf('\'', i); if (closingQuote == -1) { i = restartPoint; continue; } // Look for metadata in the separator expression // e.g., @(foo, '%(bar)') contains batchable metadata 'bar' GetReferencedItemNamesAndMetadata(expression, i, closingQuote, ref pair, ShredderOptions.MetadataOutsideTransforms); i = closingQuote + 1; } SinkWhitespace(expression, ref i); if (!Sink(expression, ref i, ')')) { i = restartPoint; continue; } // If we've got this far, we know the item expression was // well formed, so make sure the name's in the table if ((whatToShredFor & ShredderOptions.ItemTypes) != 0) { pair.Items = Utilities.CreateTableIfNecessary(pair.Items); pair.Items[name] = String.Empty; } i--; continue; } if (Sink(expression, ref i, end, '%', '(')) { // Start of a possible metadata expression // Store the index to backtrack to if this doesn't turn out to be a well // formed metadata expression. (Subtract one for the increment when we loop around.) restartPoint = i - 1; SinkWhitespace(expression, ref i); int startOfText = i; if (!SinkValidName(expression, ref i, end)) { i = restartPoint; continue; } // Grab this, but we don't know if it's an item or metadata name yet string firstPart = expression.Substring(startOfText, i - startOfText); string itemName = null; string metadataName; string qualifiedMetadataName; SinkWhitespace(expression, ref i); bool qualified = Sink(expression, ref i, '.'); if (qualified) { SinkWhitespace(expression, ref i); startOfText = i; if (!SinkValidName(expression, ref i, end)) { i = restartPoint; continue; } itemName = firstPart; metadataName = expression.Substring(startOfText, i - startOfText); qualifiedMetadataName = itemName + "." + metadataName; } else { metadataName = firstPart; qualifiedMetadataName = metadataName; } SinkWhitespace(expression, ref i); if (!Sink(expression, ref i, ')')) { i = restartPoint; continue; } if ((whatToShredFor & ShredderOptions.MetadataOutsideTransforms) != 0) { pair.Metadata = Utilities.CreateTableIfNecessary(pair.Metadata); pair.Metadata[qualifiedMetadataName] = new MetadataReference(itemName, metadataName); } i--; } } } /// <summary> /// Returns true if a single quoted subexpression begins at the specified index /// and ends before the specified end index. /// Leaves index one past the end of the second quote. /// </summary> private static bool SinkSingleQuotedExpression(string expression, ref int i, int end) { if (!Sink(expression, ref i, '\'')) { return false; } while (i < end && expression[i] != '\'') { i++; } i++; if (end <= i) { return false; } return true; } /// <summary> /// Returns true if a valid name begins at the specified index. /// Leaves index one past the end of the name. /// </summary> private static bool SinkValidName(string expression, ref int i, int end) { if (end <= i || !XmlUtilities.IsValidInitialElementNameCharacter(expression[i])) { return false; } i++; while (end > i && XmlUtilities.IsValidSubsequentElementNameCharacter(expression[i])) { i++; } return true; } /// <summary> /// Returns true if the character at the specified index /// is the specified char. /// Leaves index one past the character. /// </summary> private static bool Sink(string expression, ref int i, char c) { if (i < expression.Length && expression[i] == c) { i++; return true; } return false; } /// <summary> /// Returns true if the next two characters at the specified index /// are the specified sequence. /// Leaves index one past the second character. /// </summary> private static bool Sink(string expression, ref int i, int end, char c1, char c2) { if (i < end - 1 && expression[i] == c1 && expression[i + 1] == c2) { i += 2; return true; } return false; } /// <summary> /// Moves past all whitespace starting at the specified index. /// Returns the next index, possibly the string length. /// </summary> /// <remarks> /// Char.IsWhitespace() is not identical in behavior to regex's \s character class, /// but it's extremely close, and it's what we use in conditional expressions. /// </remarks> private static void SinkWhitespace(string expression, ref int i) { while (i < expression.Length && Char.IsWhiteSpace(expression[i])) { i++; } } } # region Related Types /// <summary> /// What the shredder should be looking for. /// </summary> [Flags] internal enum ShredderOptions { Invalid = 0x0, ItemTypes = 0x1, MetadataOutsideTransforms = 0x2, All = ItemTypes | MetadataOutsideTransforms } /// <summary> /// Wrapper of two tables for a convenient method return value. /// </summary> internal struct ItemsAndMetadataPair { private Hashtable items; private Dictionary<string, MetadataReference> metadata; internal ItemsAndMetadataPair(Hashtable items, Dictionary<string, MetadataReference> metadata) { this.items = items; this.metadata = metadata; } internal Hashtable Items { get { return items; } set { items = value; } } internal Dictionary<string, MetadataReference> Metadata { get { return metadata; } set { metadata = value; } } } // This struct represents a reference to a piece of item metadata. For example, // %(EmbeddedResource.Culture) or %(Culture) in the project file. In this case, // "EmbeddedResource" is the item name, and "Culture" is the metadata name. // The item name is optional. internal struct MetadataReference { /// <summary> /// Constructor /// </summary> /// <param name="itemName">can be null</param> /// <param name="metadataName"></param> internal MetadataReference ( string itemName, string metadataName ) { this.itemName = itemName; this.metadataName = metadataName; } internal string itemName; // Could be null if the %(...) is not qualified with an item name. internal string metadataName; } #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 Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Security.Claims; namespace System.Security.Principal { [Serializable] public enum WindowsBuiltInRole { Administrator = 0x220, User = 0x221, Guest = 0x222, PowerUser = 0x223, AccountOperator = 0x224, SystemOperator = 0x225, PrintOperator = 0x226, BackupOperator = 0x227, Replicator = 0x228 } [Serializable] public class WindowsPrincipal : ClaimsPrincipal { private WindowsIdentity _identity = null; // // Constructors. // private WindowsPrincipal() { } public WindowsPrincipal(WindowsIdentity ntIdentity) : base(ntIdentity) { if (ntIdentity == null) throw new ArgumentNullException(nameof(ntIdentity)); Contract.EndContractBlock(); _identity = ntIdentity; } [OnDeserialized] private void OnDeserializedMethod(StreamingContext context) { ClaimsIdentity firstNonNullIdentity = null; foreach (ClaimsIdentity identity in base.Identities) { if (identity != null) { firstNonNullIdentity = identity; break; } } if (firstNonNullIdentity == null) { base.AddIdentity(_identity); } } // // Properties. // public override IIdentity Identity { get { return _identity; } } // // Public methods. // public override bool IsInRole(string role) { if (role == null || role.Length == 0) return false; NTAccount ntAccount = new NTAccount(role); IdentityReferenceCollection source = new IdentityReferenceCollection(1); source.Add(ntAccount); IdentityReferenceCollection target = NTAccount.Translate(source, typeof(SecurityIdentifier), false); SecurityIdentifier sid = target[0] as SecurityIdentifier; if (sid != null) { if (IsInRole(sid)) { return true; } } // possible that identity has other role claims that match return base.IsInRole(role); } // <summary // Returns all of the claims from all of the identities that are windows user claims // found in the NT token. // </summary> public virtual IEnumerable<Claim> UserClaims { get { foreach (ClaimsIdentity identity in Identities) { WindowsIdentity wi = identity as WindowsIdentity; if (wi != null) { foreach (Claim claim in wi.UserClaims) { yield return claim; } } } } } // <summary // Returns all of the claims from all of the identities that are windows device claims // found in the NT token. // </summary> public virtual IEnumerable<Claim> DeviceClaims { get { foreach (ClaimsIdentity identity in Identities) { WindowsIdentity wi = identity as WindowsIdentity; if (wi != null) { foreach (Claim claim in wi.DeviceClaims) { yield return claim; } } } } } public virtual bool IsInRole(WindowsBuiltInRole role) { if (role < WindowsBuiltInRole.Administrator || role > WindowsBuiltInRole.Replicator) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)role), nameof(role)); Contract.EndContractBlock(); return IsInRole((int)role); } public virtual bool IsInRole(int rid) { SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, rid }); return IsInRole(sid); } // This method (with a SID parameter) is more general than the 2 overloads that accept a WindowsBuiltInRole or // a rid (as an int). It is also better from a performance standpoint than the overload that accepts a string. // The aformentioned overloads remain in this class since we do not want to introduce a // breaking change. However, this method should be used in all new applications. public virtual bool IsInRole(SecurityIdentifier sid) { if (sid == null) throw new ArgumentNullException(nameof(sid)); Contract.EndContractBlock(); // special case the anonymous identity. if (_identity.AccessToken.IsInvalid) return false; // CheckTokenMembership expects an impersonation token SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle; if (_identity.ImpersonationLevel == TokenImpersonationLevel.None) { if (!Interop.Advapi32.DuplicateTokenEx(_identity.AccessToken, (uint)TokenAccessLevels.Query, IntPtr.Zero, (uint)TokenImpersonationLevel.Identification, (uint)TokenType.TokenImpersonation, ref token)) throw new SecurityException(new Win32Exception().Message); } bool isMember = false; // CheckTokenMembership will check if the SID is both present and enabled in the access token. if (!Interop.Advapi32.CheckTokenMembership((_identity.ImpersonationLevel != TokenImpersonationLevel.None ? _identity.AccessToken : token), sid.BinaryForm, ref isMember)) throw new SecurityException(new Win32Exception().Message); token.Dispose(); return isMember; } } }
// // pending.cs: Pending method implementation // // Authors: // Miguel de Icaza ([email protected]) // Marek Safar ([email protected]) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com) // Copyright 2003-2008 Novell, Inc. // using System.Collections.Generic; using System.Linq; #if STATIC using IKVM.Reflection; using IKVM.Reflection.Emit; #else using System.Reflection; using System.Reflection.Emit; #endif namespace Mono.CSharp { struct TypeAndMethods { public TypeSpec type; public IList<MethodSpec> methods; // // Whether it is optional, this is used to allow the explicit/implicit // implementation when a base class already implements an interface. // // For example: // // class X : IA { } class Y : X, IA { IA.Explicit (); } // public bool optional; // // This flag on the method says `We found a match, but // because it was private, we could not use the match // public MethodData [] found; // If a method is defined here, then we always need to // create a proxy for it. This is used when implementing // an interface's indexer with a different IndexerName. public MethodSpec [] need_proxy; } public class PendingImplementation { /// <summary> /// The container for this PendingImplementation /// </summary> TypeContainer container; /// <summary> /// This is the array of TypeAndMethods that describes the pending implementations /// (both interfaces and abstract methods in base class) /// </summary> TypeAndMethods [] pending_implementations; PendingImplementation (TypeContainer container, MissingInterfacesInfo[] missing_ifaces, MethodSpec[] abstract_methods, int total) { var type_builder = container.Definition; this.container = container; pending_implementations = new TypeAndMethods [total]; int i = 0; if (abstract_methods != null) { int count = abstract_methods.Length; pending_implementations [i].methods = new MethodSpec [count]; pending_implementations [i].need_proxy = new MethodSpec [count]; pending_implementations [i].methods = abstract_methods; pending_implementations [i].found = new MethodData [count]; pending_implementations [i].type = type_builder; ++i; } foreach (MissingInterfacesInfo missing in missing_ifaces) { var iface = missing.Type; var mi = MemberCache.GetInterfaceMethods (iface); int count = mi.Count; pending_implementations [i].type = iface; pending_implementations [i].optional = missing.Optional; pending_implementations [i].methods = mi; pending_implementations [i].found = new MethodData [count]; pending_implementations [i].need_proxy = new MethodSpec [count]; i++; } } struct MissingInterfacesInfo { public TypeSpec Type; public bool Optional; public MissingInterfacesInfo (TypeSpec t) { Type = t; Optional = false; } } static MissingInterfacesInfo [] EmptyMissingInterfacesInfo = new MissingInterfacesInfo [0]; static MissingInterfacesInfo [] GetMissingInterfaces (TypeContainer container) { // // Notice that Interfaces will only return the interfaces that the Type // is supposed to implement, not all the interfaces that the type implements. // var impl = container.Definition.Interfaces; if (impl == null || impl.Count == 0) return EmptyMissingInterfacesInfo; MissingInterfacesInfo[] ret = new MissingInterfacesInfo[impl.Count]; for (int i = 0; i < impl.Count; i++) ret [i] = new MissingInterfacesInfo (impl [i]); // we really should not get here because Object doesnt implement any // interfaces. But it could implement something internal, so we have // to handle that case. if (container.BaseType == null) return ret; var base_impls = container.BaseType.Interfaces; if (base_impls != null) { foreach (TypeSpec t in base_impls) { for (int i = 0; i < ret.Length; i++) { if (t == ret[i].Type) { ret[i].Optional = true; break; } } } } return ret; } // // Factory method: if there are pending implementation methods, we return a PendingImplementation // object, otherwise we return null. // // Register method implementations are either abstract methods // flagged as such on the base class or interface methods // static public PendingImplementation GetPendingImplementations (TypeContainer container) { TypeSpec b = container.BaseType; var missing_interfaces = GetMissingInterfaces (container); // // If we are implementing an abstract class, and we are not // ourselves abstract, and there are abstract methods (C# allows // abstract classes that have no abstract methods), then allocate // one slot. // // We also pre-compute the methods. // bool implementing_abstract = ((b != null) && b.IsAbstract && (container.ModFlags & Modifiers.ABSTRACT) == 0); MethodSpec[] abstract_methods = null; if (implementing_abstract){ var am = MemberCache.GetNotImplementedAbstractMethods (b); if (am == null) { implementing_abstract = false; } else { abstract_methods = new MethodSpec[am.Count]; am.CopyTo (abstract_methods, 0); } } int total = missing_interfaces.Length + (implementing_abstract ? 1 : 0); if (total == 0) return null; return new PendingImplementation (container, missing_interfaces, abstract_methods, total); } public enum Operation { // // If you change this, review the whole InterfaceMethod routine as there // are a couple of assumptions on these three states // Lookup, ClearOne, ClearAll } /// <summary> /// Whether the specified method is an interface method implementation /// </summary> public MethodSpec IsInterfaceMethod (MemberName name, TypeSpec ifaceType, MethodData method) { return InterfaceMethod (name, ifaceType, method, Operation.Lookup); } public void ImplementMethod (MemberName name, TypeSpec ifaceType, MethodData method, bool clear_one) { InterfaceMethod (name, ifaceType, method, clear_one ? Operation.ClearOne : Operation.ClearAll); } /// <remarks> /// If a method in Type `t' (or null to look in all interfaces /// and the base abstract class) with name `Name', return type `ret_type' and /// arguments `args' implements an interface, this method will /// return the MethodInfo that this method implements. /// /// If `name' is null, we operate solely on the method's signature. This is for /// instance used when implementing indexers. /// /// The `Operation op' controls whether to lookup, clear the pending bit, or clear /// all the methods with the given signature. /// /// The `MethodInfo need_proxy' is used when we're implementing an interface's /// indexer in a class. If the new indexer's IndexerName does not match the one /// that was used in the interface, then we always need to create a proxy for it. /// /// </remarks> public MethodSpec InterfaceMethod (MemberName name, TypeSpec iType, MethodData method, Operation op) { if (pending_implementations == null) return null; TypeSpec ret_type = method.method.ReturnType; ParametersCompiled args = method.method.ParameterInfo; bool is_indexer = method.method is Indexer.SetIndexerMethod || method.method is Indexer.GetIndexerMethod; foreach (TypeAndMethods tm in pending_implementations){ if (!(iType == null || tm.type == iType)) continue; int method_count = tm.methods.Count; MethodSpec m; for (int i = 0; i < method_count; i++){ m = tm.methods [i]; if (m == null) continue; if (is_indexer) { if (!m.IsAccessor || m.Parameters.IsEmpty) continue; } else { if (name.Name != m.Name) continue; if (m.Arity != name.Arity) continue; } if (!TypeSpecComparer.Override.IsEqual (m.Parameters, args)) continue; if (!TypeSpecComparer.Override.IsEqual (m.ReturnType, ret_type)) { tm.found[i] = method; continue; } // // `need_proxy' is not null when we're implementing an // interface indexer and this is Clear(One/All) operation. // // If `name' is null, then we do a match solely based on the // signature and not on the name (this is done in the Lookup // for an interface indexer). // if (op != Operation.Lookup) { // If `t != null', then this is an explicitly interface // implementation and we can always clear the method. // `need_proxy' is not null if we're implementing an // interface indexer. In this case, we need to create // a proxy if the implementation's IndexerName doesn't // match the IndexerName in the interface. if (m.DeclaringType.IsInterface && iType == null && name.Name != m.Name) { // TODO: This is very expensive comparison tm.need_proxy[i] = method.method.Spec; } else { tm.methods[i] = null; } } else { tm.found [i] = method; } // // Lookups and ClearOne return // if (op != Operation.ClearAll) return m; } // If a specific type was requested, we can stop now. if (tm.type == iType) return null; } return null; } /// <summary> /// C# allows this kind of scenarios: /// interface I { void M (); } /// class X { public void M (); } /// class Y : X, I { } /// /// For that case, we create an explicit implementation function /// I.M in Y. /// </summary> void DefineProxy (TypeSpec iface, MethodSpec base_method, MethodSpec iface_method) { // TODO: Handle nested iface names string proxy_name; var ns = iface.MemberDefinition.Namespace; if (string.IsNullOrEmpty (ns)) proxy_name = iface.MemberDefinition.Name + "." + iface_method.Name; else proxy_name = ns + "." + iface.MemberDefinition.Name + "." + iface_method.Name; var param = iface_method.Parameters; MethodBuilder proxy = container.TypeBuilder.DefineMethod ( proxy_name, MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.CheckAccessOnOverride | MethodAttributes.Virtual, CallingConventions.Standard | CallingConventions.HasThis, base_method.ReturnType.GetMetaInfo (), param.GetMetaInfo ()); if (iface_method.IsGeneric) { var gnames = iface_method.GenericDefinition.TypeParameters.Select (l => l.Name).ToArray (); proxy.DefineGenericParameters (gnames); } for (int i = 0; i < param.Count; i++) { string name = param.FixedParameters [i].Name; ParameterAttributes attr = ParametersCompiled.GetParameterAttribute (param.FixedParameters [i].ModFlags); proxy.DefineParameter (i + 1, attr, name); } int top = param.Count; var ec = new EmitContext (null, proxy.GetILGenerator (), null); // TODO: GetAllParametersArguments for (int i = 0; i <= top; i++) ParameterReference.EmitLdArg (ec, i); ec.Emit (OpCodes.Call, base_method); ec.Emit (OpCodes.Ret); container.TypeBuilder.DefineMethodOverride (proxy, (MethodInfo) iface_method.GetMetaInfo ()); } /// <summary> /// This function tells whether one of our base classes implements /// the given method (which turns out, it is valid to have an interface /// implementation in a base /// </summary> bool BaseImplements (TypeSpec iface_type, MethodSpec mi, out MethodSpec base_method) { var base_type = container.BaseType; // // Setup filter with no return type to give better error message // about mismatch at return type when the check bellow rejects them // var filter = new MemberFilter (mi.Name, mi.Arity, MemberKind.Method, mi.Parameters, null); base_method = (MethodSpec) MemberCache.FindMember (base_type, filter, BindingRestriction.None); if (base_method == null || (base_method.Modifiers & Modifiers.PUBLIC) == 0) return false; if (base_method.DeclaringType.IsInterface) return false; if (!TypeSpecComparer.Override.IsEqual (mi.ReturnType, base_method.ReturnType)) return false; if (!base_method.IsAbstract && !base_method.IsVirtual) // FIXME: We can avoid creating a proxy if base_method can be marked 'final virtual' instead. // However, it's too late now, the MethodBuilder has already been created (see bug 377519) DefineProxy (iface_type, base_method, mi); return true; } /// <summary> /// Verifies that any pending abstract methods or interface methods /// were implemented. /// </summary> public bool VerifyPendingMethods (Report Report) { int top = pending_implementations.Length; bool errors = false; int i; for (i = 0; i < top; i++){ TypeSpec type = pending_implementations [i].type; bool base_implements_type = type.IsInterface && container.BaseType != null && container.BaseType.ImplementsInterface (type, false); for (int j = 0; j < pending_implementations [i].methods.Count; ++j) { var mi = pending_implementations[i].methods[j]; if (mi == null) continue; if (type.IsInterface){ var need_proxy = pending_implementations [i].need_proxy [j]; if (need_proxy != null) { DefineProxy (type, need_proxy, mi); continue; } if (pending_implementations [i].optional) continue; MethodSpec candidate = null; if (base_implements_type || BaseImplements (type, mi, out candidate)) continue; if (candidate == null) { MethodData md = pending_implementations [i].found [j]; if (md != null) candidate = md.method.Spec; } Report.SymbolRelatedToPreviousError (mi); if (candidate != null) { Report.SymbolRelatedToPreviousError (candidate); if (candidate.IsStatic) { Report.Error (736, container.Location, "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' is static", container.GetSignatureForError (), mi.GetSignatureForError (), TypeManager.CSharpSignature (candidate)); } else if ((candidate.Modifiers & Modifiers.PUBLIC) == 0) { Report.Error (737, container.Location, "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' in not public", container.GetSignatureForError (), mi.GetSignatureForError (), candidate.GetSignatureForError ()); } else { Report.Error (738, container.Location, "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' return type `{3}' does not match interface member return type `{4}'", container.GetSignatureForError (), mi.GetSignatureForError (), TypeManager.CSharpSignature (candidate), TypeManager.CSharpName (candidate.ReturnType), TypeManager.CSharpName (mi.ReturnType)); } } else { Report.Error (535, container.Location, "`{0}' does not implement interface member `{1}'", container.GetSignatureForError (), mi.GetSignatureForError ()); } } else { Report.SymbolRelatedToPreviousError (mi); Report.Error (534, container.Location, "`{0}' does not implement inherited abstract member `{1}'", container.GetSignatureForError (), mi.GetSignatureForError ()); } errors = true; } } return errors; } } }
namespace SPALM.SPSF.Library { using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.IO; using System.Windows.Forms; using Microsoft.Practices.ComponentModel; using Microsoft.Practices.RecipeFramework.Services; using Microsoft.Practices.WizardFramework; using SPALM.SPSF.Library.Properties; /// <summary> /// Controls changes the background image in the header of a wizard. /// </summary> [ServiceDependency(typeof(IServiceProvider)), ServiceDependency(typeof(IContainer))] public class BrandingPanel : ArgumentPanelTypeEditor { Microsoft.VisualStudio.VSHelp.Help helpService; protected string GetBasePath() { IConfigurationService s = this.GetService(typeof(IConfigurationService)) as IConfigurationService; return s.BasePath; } private bool logosChanged = false; public BrandingPanel() : base() { } private string helpPage = ""; public void UpdateHelpPage(string basepath, string recipeName, Microsoft.VisualStudio.VSHelp.Help helpService) { this.helpService = helpService; try { helpPage = GetHelpPage(basepath, recipeName); if (helpPage != "") { this.WizardPage.Wizard.HelpButton = true; this.WizardPage.Wizard.HelpButtonClicked += new CancelEventHandler(Wizard_HelpButtonClicked); } } catch (Exception) { } } protected override void UpdateValue(object newValue) { base.UpdateValue("test"); UpdateImage(GetBasePath()); } public void UpdateImage(string basePath) { Bitmap image = Resources.SPSFBannerLogo; WizardForm wizard = this.WizardPage.Wizard; Control header = wizard.Controls["_headerBannerPanel"]; double width = (double)header.Height / (double)image.Height * (double)image.Width; image = new Bitmap(image, new Size((int)width, header.Height)); helpPage = GetHelpPage(basePath, ""); if (helpPage != "") { this.WizardPage.Wizard.HelpButton = true; this.WizardPage.Wizard.HelpButtonClicked += new CancelEventHandler(Wizard_HelpButtonClicked); } if (!logosChanged) { logosChanged = true; try { for (int i = 0; i < this.WizardPage.Wizard.PageCount; i++) { this.WizardPage.Wizard.GetPage(i).Logo = image; } } catch (Exception ex) { MessageBox.Show("Ex" + ex.ToString()); } } } void Wizard_HelpButtonClicked(object sender, CancelEventArgs e) { if (helpPage != "") { if (helpService == null) { helpService = (Microsoft.VisualStudio.VSHelp.Help)base.GetService(typeof(Microsoft.VisualStudio.VSHelp.Help)); } if (helpService != null) { try { helpService.DisplayTopicFromURL(helpPage); } catch (Exception) { } } e.Cancel = true; } } private string GetHelpPage(string basePath, string recipeName) { if (recipeName == "") { try { IDictionaryService dictionaryService = GetService(typeof(IDictionaryService)) as IDictionaryService; recipeName = dictionaryService.GetValue("RecipeName").ToString(); } catch (Exception) { } } string localPath = string.Empty; if (recipeName != "") { string uriString = basePath += "\\Help\\OutputHTML\\SPSF_RECIPE_" + recipeName.ToUpper() + ".html"; if (File.Exists(uriString)) { Uri result = null; if (!Uri.TryCreate(uriString, UriKind.RelativeOrAbsolute, out result)) { } if (result != null) { if (result.IsAbsoluteUri) { if (result.IsFile) { localPath = result.LocalPath; } else { localPath = result.AbsoluteUri; } } else { //localPath = Path.Combine(this.basePath, uriString); } } } } return localPath; } protected override void InitLayout() { base.InitLayout(); try { WizardForm wizard = this.WizardPage.Wizard; for (int i = 0; i < wizard.PageCount; i++ ) { Microsoft.WizardFramework.WizardPage page = wizard.GetPage(i); page.InfoRTBoxIcon = null; } } catch { } try { WizardForm wizard = this.WizardPage.Wizard; Control header = wizard.Controls["_headerBannerPanel"]; header.BackColor = Color.White; //header.BackgroundImage = SPALM.SPSF.Library.Properties.Resources.SPSFBannerTitle; Image title = Resources.SPSFBannerTitle; double width = (double)header.Height / (double)title.Height * (double)title.Width; header.BackgroundImage = (Image)new Bitmap(title, new Size((int)width, header.Height)); header.BackgroundImageLayout = ImageLayout.None; header.Visible = true; PictureBox pictureBox = header.Controls["_pageLogo"] as PictureBox; pictureBox.Dock = DockStyle.Right; pictureBox.SizeMode = PictureBoxSizeMode.AutoSize; // resize not working, for whatever reason, taking two images for now to support VisualStyles (Win8) //Image logo = header.Height < 74?SPALM.SPSF.Library.Properties.Resources.SPSFBannerLogoSmall:SPALM.SPSF.Library.Properties.Resources.SPSFBannerLogo; Image logo = Resources.SPSFBannerLogo; width = (double)header.Height / (double)logo.Height * (double)logo.Width; logo = (Image)new Bitmap(logo, new Size((int)width, header.Height)); pictureBox.Image = logo; pictureBox.InitialImage = logo; pictureBox.Visible = true; //pictureBox.Visible = false; Label headlineLabel = header.Controls["_headlineLabel"] as Label; headlineLabel.Visible = false; //headlineLabel.ForeColor = Color.Red; //headlineLabel.TextAlign = ContentAlignment.MiddleRight; //headlineLabel.Font = new Font(this.Font.FontFamily, 11); //headlineLabel.BringToFront(); pictureBox.SendToBack(); } catch (Exception ex) { MessageBox.Show("Ex" + ex.ToString()); } //hide the argumentpanelcontrol this.Visible = 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; using System.Globalization; /// <summary> /// String.System.IConvertible.ToSByte(IFormatProvider provider) /// This method supports the .NET Framework infrastructure and is /// not intended to be used directly from your code. /// Converts the value of the current String object to an 8-bit signed integer. /// </summary> class IConvertibleToSByte { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; public static int Main() { IConvertibleToSByte iege = new IConvertibleToSByte(); TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToSByte(IFormatProvider)"); if (iege.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive test scenarioes public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Random positive numeric string"; const string c_TEST_ID = "P001"; string strSrc; IFormatProvider provider; sbyte b; bool expectedValue = true; bool actualValue = false; b = (sbyte)(TestLibrary.Generator.GetByte(-55) % (sbyte.MaxValue + 1)); strSrc = b.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (b == ((IConvertible)strSrc).ToSByte(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Positive sign"; const string c_TEST_ID = "P002"; string strSrc; IFormatProvider provider; NumberFormatInfo ni = new NumberFormatInfo(); sbyte b; bool expectedValue = true; bool actualValue = false; b = (sbyte)(TestLibrary.Generator.GetByte(-55) % (sbyte.MaxValue + 1)); ni.PositiveSign = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); //ni.PositiveSign = "**"; strSrc = ni.PositiveSign + b.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (b == ((IConvertible)strSrc).ToSByte(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: string is SByte.MaxValue"; const string c_TEST_ID = "P003"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = sbyte.MaxValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (sbyte.MaxValue == ((IConvertible)strSrc).ToSByte(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: string is sByte.MinValue"; const string c_TEST_ID = "P004"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = sbyte.MinValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (sbyte.MinValue == ((IConvertible)strSrc).ToSByte(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_DESC = "PosTest5: Negative sign"; const string c_TEST_ID = "P005"; string strSrc; IFormatProvider provider; NumberFormatInfo ni = new NumberFormatInfo(); sbyte b; bool expectedValue = true; bool actualValue = false; b = (sbyte)(TestLibrary.Generator.GetByte(-55) % (sbyte.MaxValue + 1)); ni.NegativeSign = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); strSrc = ni.NegativeSign + b.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = ((-1 * b) == ((IConvertible)strSrc).ToSByte(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion // end for positive test scenarioes #region Negative test scenarios //FormatException public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed"; const string c_TEST_ID = "N001"; string strSrc; IFormatProvider provider; strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToSByte(provider); TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue"; const string c_TEST_ID = "N002"; string strSrc; IFormatProvider provider; int i; i = sbyte.MaxValue + 1 + TestLibrary.Generator.GetByte(-55); strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToSByte(provider); TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue"; const string c_TEST_ID = "N003"; string strSrc; IFormatProvider provider; int i; i = -1*(TestLibrary.Generator.GetByte(-55) % (sbyte.MaxValue)) +sbyte.MinValue - 1; strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToSByte(provider); TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion private string GetDataString(string strSrc, IFormatProvider provider) { string str1, str2, str; int len1; if (null == strSrc) { str1 = "null"; len1 = 0; } else { str1 = strSrc; len1 = strSrc.Length; } str2 = (null == provider) ? "null" : provider.ToString(); str = string.Format("\n[Source string value]\n \"{0}\"", str1); str += string.Format("\n[Length of source string]\n {0}", len1); str += string.Format("\n[Format provider string]\n {0}", str2); return str; } }
// 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 Xunit; namespace System.Numerics.Tests { public class StackCalc { public string[] input; public Stack<BigInteger> myCalc; public Stack<BigInteger> snCalc; public Queue<string> operators; private BigInteger _snOut = 0; private BigInteger _myOut = 0; public StackCalc(string _input) { myCalc = new Stack<System.Numerics.BigInteger>(); snCalc = new Stack<System.Numerics.BigInteger>(); string delimStr = " "; char[] delimiter = delimStr.ToCharArray(); input = _input.Split(delimiter); operators = new Queue<string>(input); } public bool DoNextOperation() { string op = ""; bool ret = false; bool checkValues = false; BigInteger snnum1 = 0; BigInteger snnum2 = 0; BigInteger snnum3 = 0; BigInteger mynum1 = 0; BigInteger mynum2 = 0; BigInteger mynum3 = 0; if (operators.Count == 0) { return false; } op = operators.Dequeue(); if (op.StartsWith("u")) { checkValues = true; snnum1 = snCalc.Pop(); snCalc.Push(DoUnaryOperatorSN(snnum1, op)); mynum1 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoUnaryOperatorMine(mynum1, op)); ret = true; } else if (op.StartsWith("b")) { checkValues = true; snnum1 = snCalc.Pop(); snnum2 = snCalc.Pop(); snCalc.Push(DoBinaryOperatorSN(snnum1, snnum2, op)); mynum1 = myCalc.Pop(); mynum2 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoBinaryOperatorMine(mynum1, mynum2, op)); ret = true; } else if (op.StartsWith("t")) { checkValues = true; snnum1 = snCalc.Pop(); snnum2 = snCalc.Pop(); snnum3 = snCalc.Pop(); snCalc.Push(DoTertanaryOperatorSN(snnum1, snnum2, snnum3, op)); mynum1 = myCalc.Pop(); mynum2 = myCalc.Pop(); mynum3 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoTertanaryOperatorMine(mynum1, mynum2, mynum3, op)); ret = true; } else { if (op.Equals("make")) { snnum1 = DoConstruction(); snCalc.Push(snnum1); myCalc.Push(snnum1); } else if (op.Equals("Corruption")) { snCalc.Push(-33); myCalc.Push(-555); } else if (BigInteger.TryParse(op, out snnum1)) { snCalc.Push(snnum1); myCalc.Push(snnum1); } else { Console.WriteLine("Failed to parse string {0}", op); } ret = true; } if (checkValues) { if ((snnum1 != mynum1) || (snnum2 != mynum2) || (snnum3 != mynum3)) { operators.Enqueue("Corruption"); } } return ret; } private BigInteger DoConstruction() { List<byte> bytes = new List<byte>(); BigInteger ret = new BigInteger(0); string op = operators.Dequeue(); while (String.CompareOrdinal(op, "endmake") != 0) { bytes.Add(byte.Parse(op)); op = operators.Dequeue(); } return new BigInteger(bytes.ToArray()); } private BigInteger DoUnaryOperatorSN(BigInteger num1, string op) { switch (op) { case "uSign": return new BigInteger(num1.Sign); case "u~": return (~(num1)); case "uLog10": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log10(num1)); case "uLog": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1)); case "uAbs": return BigInteger.Abs(num1); case "uNegate": return BigInteger.Negate(num1); case "u--": return (--(num1)); case "u++": return (++(num1)); case "u-": return (-(num1)); case "u+": return (+(num1)); case "uMultiply": return BigInteger.Multiply(num1, num1); case "u*": return num1 * num1; default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } private BigInteger DoBinaryOperatorSN(BigInteger num1, BigInteger num2, string op) { switch (op) { case "bMin": return BigInteger.Min(num1, num2); case "bMax": return BigInteger.Max(num1, num2); case "b>>": return num1 >> (int)num2; case "b<<": return num1 << (int)num2; case "b^": return num1 ^ num2; case "b|": return num1 | num2; case "b&": return num1 & num2; case "b%": return num1 % num2; case "b/": return num1 / num2; case "b*": return num1 * num2; case "b-": return num1 - num2; case "b+": return num1 + num2; case "bLog": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1, (double)num2)); case "bGCD": return BigInteger.GreatestCommonDivisor(num1, num2); case "bPow": int arg2 = (int)num2; return BigInteger.Pow(num1, arg2); case "bDivRem": BigInteger num3; BigInteger ret = BigInteger.DivRem(num1, num2, out num3); SetSNOutCheck(num3); return ret; case "bRemainder": return BigInteger.Remainder(num1, num2); case "bDivide": return BigInteger.Divide(num1, num2); case "bMultiply": return BigInteger.Multiply(num1, num2); case "bSubtract": return BigInteger.Subtract(num1, num2); case "bAdd": return BigInteger.Add(num1, num2); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } private BigInteger DoTertanaryOperatorSN(BigInteger num1, BigInteger num2, BigInteger num3, string op) { switch (op) { case "tModPow": return BigInteger.ModPow(num1, num2, num3); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } private void SetSNOutCheck(BigInteger value) { _snOut = value; } public void VerifyOutParameter() { Assert.Equal(_snOut, MyBigIntImp.outParam); _snOut = 0; MyBigIntImp.outParam = 0; } private static String Print(byte[] bytes) { return MyBigIntImp.PrintFormatX(bytes); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using Orchard.Caching; using Orchard.Environment.Configuration; using Orchard.Environment.Extensions; using Orchard.Environment.ShellBuilders; using Orchard.Environment.State; using Orchard.Environment.Descriptor; using Orchard.Environment.Descriptor.Models; using Orchard.Localization; using Orchard.Logging; using Orchard.Mvc; using Orchard.Mvc.Extensions; using Orchard.Utility.Extensions; using Orchard.Utility; using System.Threading; namespace Orchard.Environment { // All the event handlers that DefaultOrchardHost implements have to be declared in OrchardStarter. public class DefaultOrchardHost : IOrchardHost, IShellSettingsManagerEventHandler, IShellDescriptorManagerEventHandler { private readonly IHostLocalRestart _hostLocalRestart; private readonly IShellSettingsManager _shellSettingsManager; private readonly IShellContextFactory _shellContextFactory; private readonly IRunningShellTable _runningShellTable; private readonly IProcessingEngine _processingEngine; private readonly IExtensionLoaderCoordinator _extensionLoaderCoordinator; private readonly IExtensionMonitoringCoordinator _extensionMonitoringCoordinator; private readonly ICacheManager _cacheManager; private readonly IHttpContextAccessor _httpContextAccessor; private readonly static object _syncLock = new object(); private readonly static object _shellContextsWriteLock = new object(); private readonly NamedReaderWriterLock _shellActivationLock = new NamedReaderWriterLock(); private IEnumerable<ShellContext> _shellContexts; private readonly ContextState<IList<ShellSettings>> _tenantsToRestart; public int Retries { get; set; } public bool DelayRetries { get; set; } public DefaultOrchardHost( IShellSettingsManager shellSettingsManager, IShellContextFactory shellContextFactory, IRunningShellTable runningShellTable, IProcessingEngine processingEngine, IExtensionLoaderCoordinator extensionLoaderCoordinator, IExtensionMonitoringCoordinator extensionMonitoringCoordinator, ICacheManager cacheManager, IHostLocalRestart hostLocalRestart, IHttpContextAccessor httpContextAccessor) { _shellSettingsManager = shellSettingsManager; _shellContextFactory = shellContextFactory; _runningShellTable = runningShellTable; _processingEngine = processingEngine; _extensionLoaderCoordinator = extensionLoaderCoordinator; _extensionMonitoringCoordinator = extensionMonitoringCoordinator; _cacheManager = cacheManager; _hostLocalRestart = hostLocalRestart; _httpContextAccessor = httpContextAccessor; _tenantsToRestart = new ContextState<IList<ShellSettings>>("DefaultOrchardHost.TenantsToRestart", () => new List<ShellSettings>()); T = NullLocalizer.Instance; Logger = NullLogger.Instance; } public Localizer T { get; set; } public ILogger Logger { get; set; } public IList<ShellContext> Current { get { return BuildCurrent().ToReadOnlyCollection(); } } public ShellContext GetShellContext(ShellSettings shellSettings) { return BuildCurrent().SingleOrDefault(shellContext => shellContext.Settings.Name.Equals(shellSettings.Name)); } void IOrchardHost.Initialize() { Logger.Information("Initializing"); BuildCurrent(); Logger.Information("Initialized"); } void IOrchardHost.ReloadExtensions() { DisposeShellContext(); } void IOrchardHost.BeginRequest() { Logger.Debug("BeginRequest"); BeginRequest(); } void IOrchardHost.EndRequest() { Logger.Debug("EndRequest"); EndRequest(); } IWorkContextScope IOrchardHost.CreateStandaloneEnvironment(ShellSettings shellSettings) { Logger.Debug("Creating standalone environment for tenant {0}", shellSettings.Name); MonitorExtensions(); BuildCurrent(); var shellContext = CreateShellContext(shellSettings); var workContext = shellContext.LifetimeScope.CreateWorkContextScope(); return new StandaloneEnvironmentWorkContextScopeWrapper(workContext, shellContext); } /// <summary> /// Ensures shells are activated, or re-activated if extensions have changed /// </summary> IEnumerable<ShellContext> BuildCurrent() { if (_shellContexts == null) { lock (_syncLock) { if (_shellContexts == null) { SetupExtensions(); MonitorExtensions(); CreateAndActivateShells(); } } } return _shellContexts; } void StartUpdatedShells() { while (_tenantsToRestart.GetState().Any()) { lock (_syncLock) { var state = _tenantsToRestart.GetState(); foreach (var settings in state) { Logger.Debug("Updating shell: " + settings.Name); ActivateShell(settings); } state.Clear(); } } } void CreateAndActivateShells() { Logger.Information("Start creation of shells"); // Is there any tenant right now? var allSettings = _shellSettingsManager.LoadSettings() .Where(settings => settings.State == TenantState.Running || settings.State == TenantState.Uninitialized || settings.State == TenantState.Initializing) .ToArray(); // Load all tenants, and activate their shell. if (allSettings.Any()) { Parallel.ForEach(allSettings, settings => { _processingEngine.Initialize(); ShellContext context = null; for (var i = 0; i <= Retries; i++) { // Not the first attempt, wait for a while ... if (DelayRetries && i > 0) { // Wait for i^2 which means 1, 2, 4, 8 ... seconds Thread.Sleep(TimeSpan.FromSeconds(Math.Pow(i, 2))); } try { context = CreateShellContext(settings); ActivateShell(context); // If everything went well, break the retry loop break; } catch (Exception ex) { if (i == Retries) { Logger.Fatal("A tenant could not be started: {0} after {1} retries.", settings.Name, Retries); return; } else { Logger.Error(ex, "A tenant could not be started: " + settings.Name + " Attempt number: " + i); } } } if (_processingEngine.AreTasksPending()) { context.Shell.Sweep.Terminate(); while (_processingEngine.AreTasksPending()) { Logger.Debug("Processing pending task after activate Shell"); _processingEngine.ExecuteNextTask(); } context.Shell.Sweep.Activate(); } }); } // No settings, run the Setup. else { var setupContext = CreateSetupContext(); ActivateShell(setupContext); } Logger.Information("Done creating shells"); } /// <summary> /// Starts a Shell and registers its settings in RunningShellTable /// </summary> private void ActivateShell(ShellContext context) { Logger.Debug("Activating context for tenant {0}", context.Settings.Name); context.Shell.Activate(); lock (_shellContextsWriteLock) { _shellContexts = (_shellContexts ?? Enumerable.Empty<ShellContext>()) .Where(c => c.Settings.Name != context.Settings.Name) .Concat(new[] { context }) .ToArray(); } _runningShellTable.Add(context.Settings); } /// <summary> /// Creates a transient shell for the default tenant's setup. /// </summary> private ShellContext CreateSetupContext() { Logger.Debug("Creating shell context for root setup."); return _shellContextFactory.CreateSetupContext(new ShellSettings { Name = ShellSettings.DefaultName }); } /// <summary> /// Creates a shell context based on shell settings. /// </summary> private ShellContext CreateShellContext(ShellSettings settings) { if (settings.State == TenantState.Uninitialized || settings.State == TenantState.Invalid) { Logger.Debug("Creating shell context for tenant {0} setup.", settings.Name); return _shellContextFactory.CreateSetupContext(settings); } Logger.Debug("Creating shell context for tenant {0}.", settings.Name); return _shellContextFactory.CreateShellContext(settings); } private void SetupExtensions() { _extensionLoaderCoordinator.SetupExtensions(); } private void MonitorExtensions() { // This is a "fake" cache entry to allow the extension loader coordinator // notify us (by resetting _current to "null") when an extension has changed // on disk, and we need to reload new/updated extensions. _cacheManager.Get("OrchardHost_Extensions", true, ctx => { _extensionMonitoringCoordinator.MonitorExtensions(ctx.Monitor); _hostLocalRestart.Monitor(ctx.Monitor); DisposeShellContext(); return ""; }); } /// <summary> /// Terminates all active shell contexts, and dispose their scope, forcing /// them to be reloaded if necessary. /// </summary> private void DisposeShellContext() { Logger.Information("Disposing active shell contexts"); if (_shellContexts != null) { lock (_syncLock) { if (_shellContexts != null) { foreach (var shellContext in _shellContexts) { shellContext.Shell.Terminate(); shellContext.Dispose(); } } } _shellContexts = null; } } protected virtual void BeginRequest() { BlockRequestsDuringSetup(); Action ensureInitialized = () => { // Ensure all shell contexts are loaded, or need to be reloaded if // extensions have changed MonitorExtensions(); BuildCurrent(); }; ShellSettings currentShellSettings = null; var httpContext = _httpContextAccessor.Current(); if (httpContext != null) { currentShellSettings = _runningShellTable.Match(httpContext); } if (currentShellSettings == null) { ensureInitialized(); } else { _shellActivationLock.RunWithReadLock(currentShellSettings.Name, () => { ensureInitialized(); }); } // StartUpdatedShells can cause a writer shell activation lock so it should run outside the reader lock. StartUpdatedShells(); } protected virtual void EndRequest() { // Synchronously process all pending tasks. It's safe to do this at this point // of the pipeline, as the request transaction has been closed, so creating a new // environment and transaction for these tasks will behave as expected.) while (_processingEngine.AreTasksPending()) { Logger.Debug("Processing pending task"); _processingEngine.ExecuteNextTask(); } StartUpdatedShells(); } void IShellSettingsManagerEventHandler.Saved(ShellSettings settings) { Logger.Debug("Shell saved: " + settings.Name); // if a tenant has been created if (settings.State != TenantState.Invalid) { if (!_tenantsToRestart.GetState().Any(t => t.Name.Equals(settings.Name))) { Logger.Debug("Adding tenant to restart: " + settings.Name + " " + settings.State); _tenantsToRestart.GetState().Add(settings); } } } public void ActivateShell(ShellSettings settings) { Logger.Debug("Activating shell: " + settings.Name); // look for the associated shell context var shellContext = _shellContexts.FirstOrDefault(c => c.Settings.Name == settings.Name); if (shellContext == null && settings.State == TenantState.Disabled) { return; } // is this is a new tenant ? or is it a tenant waiting for setup ? if (shellContext == null || settings.State == TenantState.Uninitialized) { // create the Shell var context = CreateShellContext(settings); // activate the Shell ActivateShell(context); } // terminate the shell if the tenant was disabled else if (settings.State == TenantState.Disabled) { shellContext.Shell.Terminate(); _runningShellTable.Remove(settings); // Forcing enumeration with ToArray() so a lazy execution isn't causing issues by accessing the disposed context. _shellContexts = _shellContexts.Where(shell => shell.Settings.Name != settings.Name).ToArray(); shellContext.Dispose(); } // reload the shell as its settings have changed else { _shellActivationLock.RunWithWriteLock(settings.Name, () => { // dispose previous context shellContext.Shell.Terminate(); var context = _shellContextFactory.CreateShellContext(settings); // Activate and register modified context. // Forcing enumeration with ToArray() so a lazy execution isn't causing issues by accessing the disposed shell context. _shellContexts = _shellContexts.Where(shell => shell.Settings.Name != settings.Name).Union(new[] { context }).ToArray(); shellContext.Dispose(); context.Shell.Activate(); _runningShellTable.Update(settings); }); } } /// <summary> /// A feature is enabled/disabled, the tenant needs to be restarted /// </summary> void IShellDescriptorManagerEventHandler.Changed(ShellDescriptor descriptor, string tenant) { if (_shellContexts == null) { return; } Logger.Debug("Shell changed: " + tenant); var context = _shellContexts.FirstOrDefault(x => x.Settings.Name == tenant); if (context == null) { return; } // don't restart when tenant is in setup if (context.Settings.State != TenantState.Running) { return; } // don't flag the tenant if already listed if (_tenantsToRestart.GetState().Any(x => x.Name == tenant)) { return; } Logger.Debug("Adding tenant to restart: " + tenant); _tenantsToRestart.GetState().Add(context.Settings); } private void BlockRequestsDuringSetup() { var httpContext = _httpContextAccessor.Current(); if (httpContext.IsBackgroundContext()) return; // Get the requested shell. var runningShell = _runningShellTable.Match(httpContext); if (runningShell == null) return; // If the requested shell is currently initializing, return a Service Unavailable HTTP status code. if (runningShell.State == TenantState.Initializing) { var response = httpContext.Response; response.StatusCode = 503; response.StatusDescription = "This tenant is currently initializing. Please try again later."; response.Write("This tenant is currently initializing. Please try again later."); } } // To be used from CreateStandaloneEnvironment(), also disposes the ShellContext LifetimeScope. private class StandaloneEnvironmentWorkContextScopeWrapper : IWorkContextScope { private readonly ShellContext _shellContext; private readonly IWorkContextScope _workContextScope; public WorkContext WorkContext { get { return _workContextScope.WorkContext; } } public StandaloneEnvironmentWorkContextScopeWrapper(IWorkContextScope workContextScope, ShellContext shellContext) { _workContextScope = workContextScope; _shellContext = shellContext; } public TService Resolve<TService>() { return _workContextScope.Resolve<TService>(); } public bool TryResolve<TService>(out TService service) { return _workContextScope.TryResolve<TService>(out service); } public void Dispose() { _workContextScope.Dispose(); _shellContext.Dispose(); } } } }
// 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>FeedItemSet</c> resource.</summary> public sealed partial class FeedItemSetName : gax::IResourceName, sys::IEquatable<FeedItemSetName> { /// <summary>The possible contents of <see cref="FeedItemSetName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/feedItemSets/{feed_id}~{feed_item_set_id}</c>. /// </summary> CustomerFeedFeedItemSet = 1, } private static gax::PathTemplate s_customerFeedFeedItemSet = new gax::PathTemplate("customers/{customer_id}/feedItemSets/{feed_id_feed_item_set_id}"); /// <summary>Creates a <see cref="FeedItemSetName"/> 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="FeedItemSetName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static FeedItemSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new FeedItemSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="FeedItemSetName"/> with the pattern /// <c>customers/{customer_id}/feedItemSets/{feed_id}~{feed_item_set_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemSetId">The <c>FeedItemSet</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="FeedItemSetName"/> constructed from the provided ids.</returns> public static FeedItemSetName FromCustomerFeedFeedItemSet(string customerId, string feedId, string feedItemSetId) => new FeedItemSetName(ResourceNameType.CustomerFeedFeedItemSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemSetId, nameof(feedItemSetId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedItemSetName"/> with pattern /// <c>customers/{customer_id}/feedItemSets/{feed_id}~{feed_item_set_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemSetId">The <c>FeedItemSet</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedItemSetName"/> with pattern /// <c>customers/{customer_id}/feedItemSets/{feed_id}~{feed_item_set_id}</c>. /// </returns> public static string Format(string customerId, string feedId, string feedItemSetId) => FormatCustomerFeedFeedItemSet(customerId, feedId, feedItemSetId); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedItemSetName"/> with pattern /// <c>customers/{customer_id}/feedItemSets/{feed_id}~{feed_item_set_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemSetId">The <c>FeedItemSet</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedItemSetName"/> with pattern /// <c>customers/{customer_id}/feedItemSets/{feed_id}~{feed_item_set_id}</c>. /// </returns> public static string FormatCustomerFeedFeedItemSet(string customerId, string feedId, string feedItemSetId) => s_customerFeedFeedItemSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemSetId, nameof(feedItemSetId)))}"); /// <summary>Parses the given resource name string into a new <see cref="FeedItemSetName"/> 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}/feedItemSets/{feed_id}~{feed_item_set_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="feedItemSetName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="FeedItemSetName"/> if successful.</returns> public static FeedItemSetName Parse(string feedItemSetName) => Parse(feedItemSetName, false); /// <summary> /// Parses the given resource name string into a new <see cref="FeedItemSetName"/> 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}/feedItemSets/{feed_id}~{feed_item_set_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedItemSetName">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="FeedItemSetName"/> if successful.</returns> public static FeedItemSetName Parse(string feedItemSetName, bool allowUnparsed) => TryParse(feedItemSetName, allowUnparsed, out FeedItemSetName 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="FeedItemSetName"/> 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}/feedItemSets/{feed_id}~{feed_item_set_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="feedItemSetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedItemSetName"/>, 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 feedItemSetName, out FeedItemSetName result) => TryParse(feedItemSetName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedItemSetName"/> 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}/feedItemSets/{feed_id}~{feed_item_set_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedItemSetName">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="FeedItemSetName"/>, 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 feedItemSetName, bool allowUnparsed, out FeedItemSetName result) { gax::GaxPreconditions.CheckNotNull(feedItemSetName, nameof(feedItemSetName)); gax::TemplatedResourceName resourceName; if (s_customerFeedFeedItemSet.TryParseName(feedItemSetName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerFeedFeedItemSet(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(feedItemSetName, 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 FeedItemSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null, string feedItemSetId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FeedId = feedId; FeedItemSetId = feedItemSetId; } /// <summary> /// Constructs a new instance of a <see cref="FeedItemSetName"/> class from the component parts of pattern /// <c>customers/{customer_id}/feedItemSets/{feed_id}~{feed_item_set_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemSetId">The <c>FeedItemSet</c> ID. Must not be <c>null</c> or empty.</param> public FeedItemSetName(string customerId, string feedId, string feedItemSetId) : this(ResourceNameType.CustomerFeedFeedItemSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemSetId, nameof(feedItemSetId))) { } /// <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>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedId { get; } /// <summary> /// The <c>FeedItemSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedItemSetId { 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.CustomerFeedFeedItemSet: return s_customerFeedFeedItemSet.Expand(CustomerId, $"{FeedId}~{FeedItemSetId}"); 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 FeedItemSetName); /// <inheritdoc/> public bool Equals(FeedItemSetName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(FeedItemSetName a, FeedItemSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(FeedItemSetName a, FeedItemSetName b) => !(a == b); } public partial class FeedItemSet { /// <summary> /// <see cref="FeedItemSetName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal FeedItemSetName ResourceNameAsFeedItemSetName { get => string.IsNullOrEmpty(ResourceName) ? null : FeedItemSetName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary> internal FeedName FeedAsFeedName { get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true); set => Feed = value?.ToString() ?? ""; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class SessionEventEncoder { public const ushort BLOCK_LENGTH = 36; public const ushort TEMPLATE_ID = 2; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private SessionEventEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public SessionEventEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public SessionEventEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public SessionEventEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ClusterSessionIdEncodingOffset() { return 0; } public static int ClusterSessionIdEncodingLength() { return 8; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public SessionEventEncoder ClusterSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public SessionEventEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int LeadershipTermIdEncodingOffset() { return 16; } public static int LeadershipTermIdEncodingLength() { return 8; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public SessionEventEncoder LeadershipTermId(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int LeaderMemberIdEncodingOffset() { return 24; } public static int LeaderMemberIdEncodingLength() { return 4; } public static int LeaderMemberIdNullValue() { return -2147483648; } public static int LeaderMemberIdMinValue() { return -2147483647; } public static int LeaderMemberIdMaxValue() { return 2147483647; } public SessionEventEncoder LeaderMemberId(int value) { _buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian); return this; } public static int CodeEncodingOffset() { return 28; } public static int CodeEncodingLength() { return 4; } public SessionEventEncoder Code(EventCode value) { _buffer.PutInt(_offset + 28, (int)value, ByteOrder.LittleEndian); return this; } public static int VersionEncodingOffset() { return 32; } public static int VersionEncodingLength() { return 4; } public static int VersionNullValue() { return 0; } public static int VersionMinValue() { return 1; } public static int VersionMaxValue() { return 16777215; } public SessionEventEncoder Version(int value) { _buffer.PutInt(_offset + 32, value, ByteOrder.LittleEndian); return this; } public static int DetailId() { return 7; } public static string DetailCharacterEncoding() { return "US-ASCII"; } public static string DetailMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int DetailHeaderLength() { return 4; } public SessionEventEncoder PutDetail(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public SessionEventEncoder PutDetail(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public SessionEventEncoder Detail(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { SessionEventDecoder writer = new SessionEventDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
namespace Nancy.Tests.Unit { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using FakeItEasy; using Nancy.Bootstrapper; using Nancy.Helpers; using Nancy.Owin; using Xunit; using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>; using MidFunc = System.Func<System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>, System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>>; public class NancyMiddlewareFixture { private readonly Dictionary<string, object> environment; private readonly INancyBootstrapper fakeBootstrapper; private readonly INancyEngine fakeEngine; private readonly AppFunc host; public NancyMiddlewareFixture() { this.fakeEngine = A.Fake<INancyEngine>(); this.fakeBootstrapper = A.Fake<INancyBootstrapper>(); A.CallTo(() => this.fakeBootstrapper.GetEngine()).Returns(this.fakeEngine); this.host = NancyMiddleware.UseNancy(new NancyOptions {Bootstrapper = this.fakeBootstrapper})(null); this.environment = new Dictionary<string, object> { {"owin.RequestMethod", "GET"}, {"owin.RequestPath", "/test"}, {"owin.RequestPathBase", "/root"}, {"owin.RequestQueryString", "var=value"}, {"owin.RequestBody", Stream.Null}, {"owin.RequestHeaders", new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)}, {"owin.RequestScheme", "http"}, {"owin.ResponseHeaders", new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)}, {"owin.ResponseBody", new MemoryStream()}, {"owin.ResponseReasonPhrase", string.Empty}, {"owin.Version", "1.0"}, {"owin.CallCancelled", CancellationToken.None} }; } [Fact] public void Should_immediately_invoke_nancy_if_no_request_body_delegate() { // Given var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { } }; var fakeContext = new NancyContext { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host(this.environment); // Then A.CallTo(() => this.fakeEngine.HandleRequest( A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored, (CancellationToken)this.environment["owin.CallCancelled"])) .MustHaveHappenedOnceExactly(); } [Fact] public void Should_set_return_code_in_response_callback() { // Given var fakeResponse = new Response {StatusCode = HttpStatusCode.OK, Contents = s => { }}; var fakeContext = new NancyContext {Response = fakeResponse}; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(this.environment); // Then ((int)this.environment["owin.ResponseStatusCode"]).ShouldEqual(200); } [Fact] public void Should_set_headers_in_response_callback() { // Given var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Headers = new Dictionary<string, string> {{"TestHeader", "TestValue"}}, Contents = s => { } }; var fakeContext = new NancyContext {Response = fakeResponse}; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(this.environment); var headers = (IDictionary<string, string[]>)this.environment["owin.ResponseHeaders"]; // Then // 2 headers because the default content-type is text/html headers.Count.ShouldEqual(2); headers["Content-Type"][0].ShouldEqual("text/html"); headers["TestHeader"][0].ShouldEqual("TestValue"); } [Fact] public void Should_send_entire_body() { // Given var data1 = Encoding.ASCII.GetBytes("Some content"); var data2 = Encoding.ASCII.GetBytes("Some more content"); var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { s.Write(data1, 0, data1.Length); s.Write(data2, 0, data2.Length); } }; var fakeContext = new NancyContext {Response = fakeResponse}; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(this.environment); var data = ((MemoryStream)this.environment["owin.ResponseBody"]).ToArray(); // Then data.ShouldEqualSequence(data1.Concat(data2)); } [Fact] public void Should_dispose_context_on_completion_of_body_delegate() { // Given var data1 = Encoding.ASCII.GetBytes("Some content"); var fakeResponse = new Response {StatusCode = HttpStatusCode.OK, Contents = s => s.Write(data1, 0, data1.Length)}; var fakeContext = new NancyContext {Response = fakeResponse}; var mockDisposable = A.Fake<IDisposable>(); fakeContext.Items.Add("Test", mockDisposable); this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(environment); // Then A.CallTo(() => mockDisposable.Dispose()).MustHaveHappenedOnceExactly(); } [Fact] public void Should_set_cookie_with_valid_header() { // Given var fakeResponse = new Response {StatusCode = HttpStatusCode.OK}; fakeResponse.WithCookie("test", "testvalue"); fakeResponse.WithCookie("test1", "testvalue1"); var fakeContext = new NancyContext {Response = fakeResponse}; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(this.environment).Wait(); var respHeaders = Get<IDictionary<string, string[]>>(this.environment, "owin.ResponseHeaders"); // Then respHeaders.ContainsKey("Set-Cookie").ShouldBeTrue(); (respHeaders["Set-Cookie"][0] == "test=testvalue; path=/").ShouldBeTrue(); (respHeaders["Set-Cookie"][1] == "test1=testvalue1; path=/").ShouldBeTrue(); } [Fact] public void Should_append_setcookie_headers() { //Given var respHeaders = Get<IDictionary<string, string[]>>(this.environment, "owin.ResponseHeaders"); const string middlewareSetCookie = "other=othervalue; path=/"; respHeaders.Add("Set-Cookie", new[] { middlewareSetCookie }); var fakeResponse = new Response { StatusCode = HttpStatusCode.OK }; fakeResponse.WithCookie("test", "testvalue"); var fakeContext = new NancyContext { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); //When this.host.Invoke(this.environment).Wait(); //Then respHeaders["Set-Cookie"].Length.ShouldEqual(2); (respHeaders["Set-Cookie"][0] == middlewareSetCookie).ShouldBeTrue(); (respHeaders["Set-Cookie"][1] == "test=testvalue; path=/").ShouldBeTrue(); } [Fact] public async Task Should_flow_katana_user() { // Given IPrincipal user = new ClaimsPrincipal(new GenericIdentity("testuser")); this.environment.Add("server.User", user); var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { } }; var fakeContext = new NancyContext { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); // When await this.host.Invoke(this.environment); // Then fakeContext.CurrentUser.ShouldEqual(user); } [Fact] public async Task Should_flow_owin_user() { // Given var user = new ClaimsPrincipal(new GenericIdentity("testuser")); this.environment.Add("owin.RequestUser", user); var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { } }; var fakeContext = new NancyContext { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); // When await this.host.Invoke(this.environment); // Then fakeContext.CurrentUser.ShouldEqual(user); } /// <summary> /// Sets the fake nancy engine to execute the complete callback with the given context /// </summary> /// <param name="context">Context to return</param> private void SetupFakeNancyCompleteCallback(NancyContext context) { A.CallTo(() => this.fakeEngine.HandleRequest( A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored)) .Invokes((Request _, Func<NancyContext, NancyContext> preRequest, CancellationToken __) => preRequest(context)) .Returns(Task.FromResult(context)); } private static T Get<T>(IDictionary<string, object> env, string key) { object value; return env.TryGetValue(key, out value) && value is T ? (T)value : default(T); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // QueuedMap.cs // // // A key-value pair queue, where pushing an existing key into the collection overwrites // the existing value. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.Threading.Tasks.Dataflow.Internal { /// <summary> /// Provides a data structure that supports pushing and popping key/value pairs. /// Pushing a key/value pair for which the key already exists results in overwriting /// the existing key entry's value. /// </summary> /// <typeparam name="TKey">Specifies the type of keys in the map.</typeparam> /// <typeparam name="TValue">Specifies the type of values in the map.</typeparam> /// <remarks>This type is not thread-safe.</remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(EnumerableDebugView<,>))] internal sealed class QueuedMap<TKey, TValue> { /// <summary> /// A queue structure that uses an array-based list to store its items /// and that supports overwriting elements at specific indices. /// </summary> /// <typeparam name="T">The type of the items storedin the queue</typeparam> /// <remarks>This type is not thread-safe.</remarks> private sealed class ArrayBasedLinkedQueue<T> { /// <summary>Terminator index.</summary> private const int TERMINATOR_INDEX = -1; /// <summary> /// The queue where the items will be stored. /// The key of each entry is the index of the next entry in the queue. /// </summary> private readonly List<KeyValuePair<int, T>> _storage; /// <summary>Index of the first queue item.</summary> private int _headIndex = TERMINATOR_INDEX; /// <summary>Index of the last queue item.</summary> private int _tailIndex = TERMINATOR_INDEX; /// <summary>Index of the first free slot.</summary> private int _freeIndex = TERMINATOR_INDEX; /// <summary>Initializes the Queue instance.</summary> internal ArrayBasedLinkedQueue() { _storage = new List<KeyValuePair<int, T>>(); } /// <summary>Initializes the Queue instance.</summary> /// <param name="capacity">The capacity of the internal storage.</param> internal ArrayBasedLinkedQueue(int capacity) { _storage = new List<KeyValuePair<int, T>>(capacity); } /// <summary>Enqueues an item.</summary> /// <param name="item">The item to be enqueued.</param> /// <returns>The index of the slot where item was stored.</returns> internal int Enqueue(T item) { int newIndex; // If there is a free slot, reuse it if (_freeIndex != TERMINATOR_INDEX) { Debug.Assert(0 <= _freeIndex && _freeIndex < _storage.Count, "Index is out of range."); newIndex = _freeIndex; _freeIndex = _storage[_freeIndex].Key; _storage[newIndex] = new KeyValuePair<int, T>(TERMINATOR_INDEX, item); } // If there is no free slot, add one else { newIndex = _storage.Count; _storage.Add(new KeyValuePair<int, T>(TERMINATOR_INDEX, item)); } if (_headIndex == TERMINATOR_INDEX) { // Point _headIndex to newIndex if the queue was empty Debug.Assert(_tailIndex == TERMINATOR_INDEX, "If head indicates empty, so too should tail."); _headIndex = newIndex; } else { // Point the tail slot to newIndex if the queue was not empty Debug.Assert(_tailIndex != TERMINATOR_INDEX, "If head does not indicate empty, neither should tail."); _storage[_tailIndex] = new KeyValuePair<int, T>(newIndex, _storage[_tailIndex].Value); } // Point the tail slot newIndex _tailIndex = newIndex; return newIndex; } /// <summary>Tries to dequeue an item.</summary> /// <param name="item">The item that is dequeued.</param> internal bool TryDequeue(out T item) { // If the queue is empty, just initialize the output item and return false if (_headIndex == TERMINATOR_INDEX) { Debug.Assert(_tailIndex == TERMINATOR_INDEX, "If head indicates empty, so too should tail."); item = default(T); return false; } // If there are items in the queue, start with populating the output item Debug.Assert(0 <= _headIndex && _headIndex < _storage.Count, "Head is out of range."); item = _storage[_headIndex].Value; // Move the popped slot to the head of the free list int newHeadIndex = _storage[_headIndex].Key; _storage[_headIndex] = new KeyValuePair<int, T>(_freeIndex, default(T)); _freeIndex = _headIndex; _headIndex = newHeadIndex; if (_headIndex == TERMINATOR_INDEX) _tailIndex = TERMINATOR_INDEX; return true; } /// <summary>Replaces the item of a given slot.</summary> /// <param name="index">The index of the slot where the value should be replaced.</param> /// <param name="item">The item to be places.</param> internal void Replace(int index, T item) { Debug.Assert(0 <= index && index < _storage.Count, "Index is out of range."); #if DEBUG // Also assert that index does not belong to the list of free slots for (int idx = _freeIndex; idx != TERMINATOR_INDEX; idx = _storage[idx].Key) Debug.Assert(idx != index, "Index should not belong to the list of free slots."); #endif _storage[index] = new KeyValuePair<int, T>(_storage[index].Key, item); } internal bool IsEmpty { get { return _headIndex == TERMINATOR_INDEX; } } } /// <summary>The queue of elements.</summary> private readonly ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>> _queue; /// <summary>A map from key to index into the list.</summary> /// <remarks>The correctness of this map relies on the list only having elements removed from its end.</remarks> private readonly Dictionary<TKey, int> _mapKeyToIndex; /// <summary>Initializes the QueuedMap.</summary> internal QueuedMap() { _queue = new ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>>(); _mapKeyToIndex = new Dictionary<TKey, int>(); } /// <summary>Initializes the QueuedMap.</summary> /// <param name="capacity">The initial capacity of the data structure.</param> internal QueuedMap(int capacity) { _queue = new ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>>(capacity); _mapKeyToIndex = new Dictionary<TKey, int>(capacity); } /// <summary>Pushes a key/value pair into the data structure.</summary> /// <param name="key">The key for the pair.</param> /// <param name="value">The value for the pair.</param> internal void Push(TKey key, TValue value) { // Try to get the index of the key in the queue. If it's there, replace the value. int indexOfKeyInQueue; if (!_queue.IsEmpty && _mapKeyToIndex.TryGetValue(key, out indexOfKeyInQueue)) { _queue.Replace(indexOfKeyInQueue, new KeyValuePair<TKey, TValue>(key, value)); } // If it's not there, add it to the queue and then add the mapping. else { indexOfKeyInQueue = _queue.Enqueue(new KeyValuePair<TKey, TValue>(key, value)); _mapKeyToIndex.Add(key, indexOfKeyInQueue); } } /// <summary>Try to pop the next element from the data structure.</summary> /// <param name="item">The popped pair.</param> /// <returns>true if an item could be popped; otherwise, false.</returns> internal bool TryPop(out KeyValuePair<TKey, TValue> item) { bool popped = _queue.TryDequeue(out item); if (popped) _mapKeyToIndex.Remove(item.Key); return popped; } /// <summary>Tries to pop one or more elements from the data structure.</summary> /// <param name="items">The items array into which the popped elements should be stored.</param> /// <param name="arrayOffset">The offset into the array at which to start storing popped items.</param> /// <param name="count">The number of items to be popped.</param> /// <returns>The number of items popped, which may be less than the requested number if fewer existed in the data structure.</returns> internal int PopRange(KeyValuePair<TKey, TValue>[] items, int arrayOffset, int count) { // As this data structure is internal, only assert incorrect usage. // If this were to ever be made public, these would need to be real argument checks. Debug.Assert(items != null, "Requires non-null array to store into."); Debug.Assert(count >= 0 && arrayOffset >= 0, "Count and offset must be non-negative"); Debug.Assert(arrayOffset + count >= 0, "Offset plus count overflowed"); Debug.Assert(arrayOffset + count <= items.Length, "Range must be within array size"); int actualCount = 0; for (int i = arrayOffset; actualCount < count; i++, actualCount++) { KeyValuePair<TKey, TValue> item; if (TryPop(out item)) items[i] = item; else break; } return actualCount; } /// <summary>Gets the number of items in the data structure.</summary> internal int Count { get { return _mapKeyToIndex.Count; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.ComponentModel.DataAnnotations.Tests { public class ValidationAttributeTests { private static readonly ValidationContext s_testValidationContext = new ValidationContext(new object()); [Fact] public static void Default_value_of_RequiresValidationContext_is_false() { var attribute = new ValidationAttributeNoOverrides(); Assert.False(attribute.RequiresValidationContext); } [Fact] public static void Can_get_and_set_ErrorMessage() { var attribute = new ValidationAttributeNoOverrides(); Assert.Null(attribute.ErrorMessage); attribute.ErrorMessage = "SomeErrorMessage"; Assert.Equal("SomeErrorMessage", attribute.ErrorMessage); } [Fact] public static void Can_get_and_set_ErrorMessageResourceName() { var attribute = new ValidationAttributeNoOverrides(); Assert.Null(attribute.ErrorMessageResourceName); attribute.ErrorMessageResourceName = "SomeErrorMessageResourceName"; Assert.Equal("SomeErrorMessageResourceName", attribute.ErrorMessageResourceName); } [Fact] public static void Can_get_and_set_ErrorMessageResourceType() { var attribute = new ValidationAttributeNoOverrides(); Assert.Null(attribute.ErrorMessageResourceType); attribute.ErrorMessageResourceType = typeof(string); Assert.Equal(typeof(string), attribute.ErrorMessageResourceType); } // Public_IsValid_throws_NotImplementedException_if_derived_ValidationAttribute_does_not_override_either_IsValid_method [Fact] public static void TestThrowIfNoOverrideIsValid() { var attribute = new ValidationAttributeNoOverrides(); Assert.Throws<NotImplementedException>( () => attribute.IsValid("Does not matter - no override of IsValid")); } // Validate_object_string_throws_NotImplementedException_if_derived_ValidationAttribute_does_not_override_either_IsValid_method [Fact] public static void TestThrowIfNoOverrideIsValid01() { var attribute = new ValidationAttributeNoOverrides(); Assert.Throws<NotImplementedException>( () => attribute.Validate( "Object to validate does not matter - no override of IsValid", "Name to put in error message does not matter either")); } // Validate_object_ValidationContext_throws_NotImplementedException_if_derived_ValidationAttribute_does_not_override_either_IsValid_method [Fact] public static void TestThrowIfNoOverrideIsValid02() { var attribute = new ValidationAttributeNoOverrides(); Assert.Throws<NotImplementedException>( () => attribute.Validate("Object to validate does not matter - no override of IsValid", s_testValidationContext)); } // Validate_object_string_successful_if_derived_ValidationAttribute_overrides_One_Arg_IsValid_method [Fact] public static void TestNoThrowIfOverrideIsValid() { var attribute = new ValidationAttributeOverrideOneArgIsValid(); attribute.Validate("Valid Value", "Name to put in error message does not matter - no error"); } // Validate_object_string_successful_if_derived_ValidationAttribute_overrides_Two_Args_IsValid_method [Fact] public static void TestNoThrowIfOverrideIsValid01() { var attribute = new ValidationAttributeOverrideTwoArgsIsValid(); attribute.Validate("Valid Value", "Name to put in error message does not matter - no error"); } // Validate_object_ValidationContext_successful_if_derived_ValidationAttribute_overrides_One_Arg_IsValid_method [Fact] public static void TestNoThrowIfOverrideIsValid02() { var attribute = new ValidationAttributeOverrideOneArgIsValid(); attribute.Validate("Valid Value", s_testValidationContext); } // Validate_object_ValidationContext_successful_if_derived_ValidationAttribute_overrides_Two_Args_IsValid_method() [Fact] public static void TestNoThrowIfOverrideIsValid03() { var attribute = new ValidationAttributeOverrideTwoArgsIsValid(); attribute.Validate("Valid Value", s_testValidationContext); } // Validate_object_string_preferentially_uses_One_Arg_IsValid_method_to_validate [Fact] public static void TestNoThrowIfOverrideIsValid04() { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.Validate("Valid 1-Arg Value", "Name to put in error message does not matter - no error"); Assert.Throws<ValidationException>( () => attribute.Validate("Valid 2-Args Value", "Name to put in error message does not matter - no error")); } // Validate_object_ValidationContext_preferentially_uses_Two_Args_IsValid_method_to_validate [Fact] public static void TestNoThrowIfOverrideIsValid05() { var attribute = new ValidationAttributeOverrideBothIsValids(); Assert.Throws<ValidationException>(() => attribute.Validate("Valid 1-Arg Value", s_testValidationContext)); attribute.Validate("Valid 2-Args Value", s_testValidationContext); } [Theory] [InlineData("SomeErrorMessage", "SomeErrorMessage")] [InlineData("SomeErrorMessage with name <{0}>", "SomeErrorMessage with name <name>")] public void FormatErrorMessage_HasErrorMessage_ReturnsExpected(string errorMessage, string expected) { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.ErrorMessage = errorMessage; attribute.ErrorMessageResourceName = null; attribute.ErrorMessageResourceType = null; Assert.Equal(expected, attribute.FormatErrorMessage("name")); } [Theory] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.PublicErrorMessageTestProperty), typeof(ValidationAttributeOverrideBothIsValids), "Error Message from PublicErrorMessageTestProperty")] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.PublicErrorMessageTestPropertyWithName), typeof(ValidationAttributeOverrideBothIsValids), "Error Message from PublicErrorMessageTestProperty With Name <name>")] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.StaticInternalProperty), typeof(ValidationAttributeOverrideBothIsValids), "ErrorMessage")] public void FormatErrorMessage_HasResourceProperty_ReturnsExpected(string resourceName, Type resourceType, string expected) { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.ErrorMessage = string.Empty; attribute.ErrorMessageResourceName = resourceName; attribute.ErrorMessageResourceType = resourceType; Assert.Equal(expected, attribute.FormatErrorMessage("name")); } [Theory] [InlineData(null)] [InlineData("")] public void FormatErrorMessage_NullOrEmptyErrorMessageAndName_ThrowsInvalidOperationException(string value) { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.ErrorMessage = value; attribute.ErrorMessageResourceName = value; Assert.Throws<InvalidOperationException>(() => attribute.FormatErrorMessage("name")); } [Fact] public void FormatErrorMessage_BothErrorMessageAndResourceName_ThrowsInvalidOperationException() { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.ErrorMessage = "SomeErrorMessage"; attribute.ErrorMessageResourceName = "SomeErrorMessageResourceName"; Assert.Throws<InvalidOperationException>(() => attribute.FormatErrorMessage("Name to put in error message does not matter")); } [Fact] public void FormatErrorMessage_BothErrorMessageAndResourceType_ThrowsInvalidOperationException() { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.ErrorMessage = "SomeErrorMessage"; attribute.ErrorMessageResourceType = typeof(int); Assert.Throws<InvalidOperationException>(() => attribute.FormatErrorMessage("Name to put in error message does not matter")); } [Theory] [InlineData("ResourceName", null)] [InlineData(null, typeof(int))] [InlineData("", typeof(int))] [InlineData("NoSuchProperty", typeof(int))] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.GetSetProperty), typeof(ValidationAttributeOverrideBothIsValids))] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.GetOnlyProperty), typeof(ValidationAttributeOverrideBothIsValids))] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.SetOnlyProperty), typeof(ValidationAttributeOverrideBothIsValids))] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.StaticSetOnlyProperty), typeof(ValidationAttributeOverrideBothIsValids))] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.StaticIntProperty), typeof(ValidationAttributeOverrideBothIsValids))] [InlineData("StaticPrivateProperty", typeof(ValidationAttributeOverrideBothIsValids))] [InlineData("StaticProtectedProperty", typeof(ValidationAttributeOverrideBothIsValids))] [InlineData(nameof(ValidationAttributeOverrideBothIsValids.StaticProtectedInternalProperty), typeof(ValidationAttributeOverrideBothIsValids))] public void FormatErrorMessage_InvalidResourceNameAndResourceType_ThrowsInvalidOperationException(string resourceName, Type resourceType) { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.ErrorMessageResourceName = resourceName; attribute.ErrorMessageResourceType = resourceType; Assert.Throws<InvalidOperationException>(() => attribute.FormatErrorMessage("Name to put in error message does not matter")); } // Validate_object_string_throws_exception_with_ValidationResult_ErrorMessage_matching_ErrorMessage_passed_in [Fact] public static void TestThrowWithValidationResultErrorMessage() { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.ErrorMessage = "SomeErrorMessage with name <{0}> here"; attribute.ErrorMessageResourceName = null; attribute.ErrorMessageResourceType = null; var exception = Assert.Throws<ValidationException>(() => attribute.Validate("Invalid Value", "Error Message Name")); Assert.Equal("Invalid Value", exception.Value); Assert.Equal( string.Format( "SomeErrorMessage with name <{0}> here", "Error Message Name"), exception.ValidationResult.ErrorMessage); } // Validate_object_string_throws_exception_with_ValidationResult_ErrorMessage_from_ErrorMessageResourceName_and_ErrorMessageResourceType [Fact] public static void TestThrowWithValidationResultErrorMessage01() { var attribute = new ValidationAttributeOverrideBothIsValids(); attribute.ErrorMessage = string.Empty; attribute.ErrorMessageResourceName = "PublicErrorMessageTestPropertyWithName"; attribute.ErrorMessageResourceType = typeof(ValidationAttributeOverrideBothIsValids); var exception = Assert.Throws<ValidationException>(() => attribute.Validate("Invalid Value", "Error Message Name")); Assert.Equal("Invalid Value", exception.Value); Assert.Equal( string.Format( ValidationAttributeOverrideBothIsValids.PublicErrorMessageTestPropertyWithName, "Error Message Name"), exception.ValidationResult.ErrorMessage); } // FormatErrorMessage_is_successful_when_ErrorMessage_from_ErrorMessageResourceName_and_ErrorMessageResourceType_point_to_internal_property [Fact] public static void TestFormatErrorMessage05() { var attribute = new ValidationAttributeOverrideBothIsValids() { ErrorMessageResourceName = "InternalErrorMessageTestProperty", ErrorMessageResourceType = typeof(ErrorMessageResources) }; Assert.Equal( ErrorMessageResources.InternalErrorMessageTestProperty, attribute.FormatErrorMessage("Ignored by this error message")); } // GetValidationResult_throws_ArgumentNullException_if_ValidationContext_is_null( [Fact] public static void TestThrowIfNullValidationContext() { var attribute = new ValidationAttributeOverrideBothIsValids(); Assert.Throws<ArgumentNullException>(() => attribute.GetValidationResult("Does not matter", validationContext: null)); } [Fact] public static void Validate_NullValidationContext_ThrowsArgumentNullException() { ValidationAttributeOverrideBothIsValids attribute = new ValidationAttributeOverrideBothIsValids(); AssertExtensions.Throws<ArgumentNullException>("validationContext", () => attribute.Validate("Any", validationContext: null)); } // GetValidationResult_successful_if_One_Arg_IsValid_validates_successfully [Fact] public static void TestOneArgsIsValidValidatesSuccessfully() { var attribute = new ValidationAttributeOverrideOneArgIsValid(); attribute.GetValidationResult("Valid Value", s_testValidationContext); } // GetValidationResult_successful_if_Two_Args_IsValid_validates_successfully [Fact] public static void TestTwoArgsIsValidValidatesSuccessfully() { var attribute = new ValidationAttributeOverrideTwoArgsIsValid(); attribute.GetValidationResult("Valid Value", s_testValidationContext); } // GetValidationResult_returns_ValidationResult_with_preset_error_message_if_One_Arg_IsValid_fails_to_validate [Fact] public static void TestReturnPresetErrorMessage() { var attribute = new ValidationAttributeOverrideOneArgIsValid(); var toBeTested = new ToBeTested(); var validationContext = new ValidationContext(toBeTested); validationContext.MemberName = "PropertyToBeTested"; var validationResult = attribute.GetValidationResult(toBeTested, validationContext); Assert.NotNull(validationResult); // validationResult == null would be success // cannot check error message - not defined on ret builds } // GetValidationResult_returns_ValidationResult_with_error_message_defined_in_IsValid_if_Two_Args_IsValid_fails_to_validate [Fact] public static void TestReturnErrorMessageInIsValid() { var attribute = new ValidationAttributeOverrideTwoArgsIsValid(); var toBeTested = new ToBeTested(); var validationContext = new ValidationContext(toBeTested); validationContext.MemberName = "PropertyToBeTested"; var validationResult = attribute.GetValidationResult(toBeTested, validationContext); Assert.NotNull(validationResult); // validationResult == null would be success // cannot check error message - not defined on ret builds } [Fact] public void GetValidationResult_NullErrorMessage_ProvidesErrorMessage() { ValidationAttributeAlwaysInvalidNullErrorMessage attribute = new ValidationAttributeAlwaysInvalidNullErrorMessage(); ValidationResult validationResult = attribute.GetValidationResult("abc", new ValidationContext(new object())); Assert.NotEmpty(validationResult.ErrorMessage); } [Fact] public void GetValidationResult_EmptyErrorMessage_ProvidesErrorMessage() { ValidationAttributeAlwaysInvalidEmptyErrorMessage attribute = new ValidationAttributeAlwaysInvalidEmptyErrorMessage(); ValidationResult validationResult = attribute.GetValidationResult("abc", new ValidationContext(new object())); Assert.NotEmpty(validationResult.ErrorMessage); } public class ValidationAttributeNoOverrides : ValidationAttribute { } public class ValidationAttributeOverrideOneArgIsValid : ValidationAttribute { public override bool IsValid(object value) { var valueAsString = value as string; if ("Valid Value".Equals(valueAsString)) { return true; } return false; } } public class ValidationAttributeOverrideTwoArgsIsValid : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext _) { var valueAsString = value as string; if ("Valid Value".Equals(valueAsString)) { return ValidationResult.Success; } return new ValidationResult("TestValidationAttributeOverrideTwoArgsIsValid IsValid failed"); } } public class ValidationAttributeOverrideBothIsValids : ValidationAttribute { public static string PublicErrorMessageTestProperty { get { return "Error Message from PublicErrorMessageTestProperty"; } } public static string PublicErrorMessageTestPropertyWithName { get { return "Error Message from PublicErrorMessageTestProperty With Name <{0}>"; } } public string GetSetProperty { get; set; } public string GetOnlyProperty { get; } public string SetOnlyProperty { set { } } public static string StaticSetOnlyProperty { set { } } public static int StaticIntProperty { get; set; } private static string StaticPrivateProperty { get; set; } = "ErrorMessage"; private static string StaticProtectedProperty { get; set; } = "ErrorMessage"; internal static string StaticInternalProperty { get; set; } = "ErrorMessage"; protected internal static string StaticProtectedInternalProperty { get; set; } = "ErrorMessage"; public override bool IsValid(object value) { var valueAsString = value as string; if ("Valid 1-Arg Value".Equals(valueAsString)) { return true; } return false; } protected override ValidationResult IsValid(object value, ValidationContext _) { var valueAsString = value as string; if ("Valid 2-Args Value".Equals(valueAsString)) { return ValidationResult.Success; } return new ValidationResult("TestValidationAttributeOverrideTwoArgsIsValid IsValid failed"); } } public class ValidationAttributeAlwaysInvalidNullErrorMessage : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) => new ValidationResult(null); } public class ValidationAttributeAlwaysInvalidEmptyErrorMessage : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) => new ValidationResult(string.Empty); } public class ToBeTested { public string PropertyToBeTested { get { return "PropertyToBeTested"; } } } } internal class ErrorMessageResources { internal static string InternalErrorMessageTestProperty { get { return "Error Message from ErrorMessageResources.InternalErrorMessageTestProperty"; } } internal string InstanceProperty => ""; private static string PrivateProperty => ""; internal string SetOnlyProperty { set { } } internal static bool BoolProperty => false; } }
using System; using UnityEngine; using System.Collections; /// <summary> /// /// Implements an RTS-style camera. /// /// For KEYBOARD control, also add "Components/Camera-Control/RtsCamera-Keyboard" (RtsCameraKeys.cs) /// For MOUSE control, also add "Components/Camera-Control/RtsCamera-Mouse" (RtsCameraMouse.cs) /// /// </summary> [AddComponentMenu("Camera-Control/RtsCamera")] [RequireComponent(typeof(RtsCameraMouse))] [RequireComponent(typeof(RtsCameraKeys))] public class RtsCamera : MonoBehaviour { #region NOTES /* * ---------------------------------------------- * Options for height calculation: * * 1) Set GetTerrainHeight function (from another script) to provide x/z height lookup: * * _rtsCamera.GetTerrainHeight = MyGetTerrainHeightFunction; * ... * private float MyGetTerrainHeightFunction(float x, float z) * { * return ...; * } * * 2) Set "TerrainHeightViaPhysics = true;" * * 3) For a "simple plain" style terrain (flat), set "LookAtHeightOffset" to base terrain height * * See demo code for examples. * * ---------------------------------------------- * To "Auto Follow" a target: * * _rtsCamera.Follow(myGameObjectOrTransform) * * See demo code for examples. * * ---------------------------------------------- * To be notified when Auto-Follow target changes (or is cleared): * * _rtsCamera.OnBeginFollow = MyBeginFollowCallback; * _rtsCamera.OnEndFollow = MyEndFollowCallback; * * void OnBeginFollow(Transform followTransform) { ... } * void OnEndFollow(Transform followTransform) { ... } * * See demo code for examples. * * ---------------------------------------------- * To force the camera to follow "behind" (with optional degree offset): * * _rtsCamera.FollowBehind = true; * _rtsCamera.FollowRotationOffset = 90; // optional * * See demo code for examples. * * ---------------------------------------------- * For target visibility checking via Physics: * * _rtsCamera.TargetVisbilityViaPhysics = true; * _rtsCamera.TargetVisibilityIgnoreLayerMask = {your layer masks that should block camera}; * * See demo code for examples. * */ #endregion public Vector3 LookAt; // Desired lookat position public float Distance; // Desired distance (units, ie Meters) public float Rotation; // Desired rotation (degrees) public float Tilt; // Desired tilt (degrees) public bool Smoothing; // Should the camera "slide" between positions and targets? public float MoveDampening; // How "smooth" should the camera moves be? Note: Smaller numbers are smoother public float ZoomDampening; // How "smooth" should the camera zooms be? Note: Smaller numbers are smoother public float RotationDampening; // How "smooth" should the camera rotations be? Note: Smaller numbers are smoother public float TiltDampening; // How "smooth" should the camera tilts be? Note: Smaller numbers are smoother public Vector3 MinBounds; // Minimum x,y,z world position for camera target public Vector3 MaxBounds; // Maximum x,y,z world position for camera target public float MinDistance; // Minimum distance of camera from target public float MaxDistance; // Maximum distance of camera from target public float MinTilt; // Minimum tilt (degrees) public float MaxTilt; // Maximum tilt (degrees) public Func<float, float, float> GetTerrainHeight; // Function taking x,z position and returning height (y). public bool TerrainHeightViaPhysics; // If set, camera will automatically raycast against terrain (using TerrainPhysicsLayerMask) to determine height public LayerMask TerrainPhysicsLayerMask; // Layer mask indicating which layers the camera should ray cast against for height detection public float LookAtHeightOffset; // Y coordinate of camera target. Only used if TerrainHeightViaPhysics and GetTerrainHeight are not set. public bool TargetVisbilityViaPhysics; // If set, camera will raycast from target out in order to avoid objects being between target and camera public LayerMask TargetVisibilityIgnoreLayerMask; // Layer mask to ignore when raycasting to determine camera visbility public bool FollowBehind; // If set, keyboard and mouse rotation will be disabled when Following a target public float FollowRotationOffset; // Offset (degrees from zero) when forcing follow behind target public Action<Transform> OnBeginFollow; // "Callback" for when automatic target following begins public Action<Transform> OnEndFollow; // "Callback" for when automatic target following ends public bool ShowDebugCameraTarget; // If set, "small green sphere" will be shown indicating camera target position (even when Following) // // PRIVATE VARIABLES // private Vector3 _initialLookAt; private float _initialDistance; private float _initialRotation; private float _initialTilt; private float _currDistance; // actual distance private float _currRotation; // actual rotation private float _currTilt; // actual tilt private Vector3 _moveVector; private GameObject _target; private MeshRenderer _targetRenderer; private Transform _followTarget; private bool _lastDebugCamera = false; // // Unity METHODS // #region UNITY_METHODS protected void Reset() { Smoothing = true; LookAtHeightOffset = 0f; TerrainHeightViaPhysics = false; TerrainPhysicsLayerMask = ~0; // "Everything" by default! GetTerrainHeight = null; TargetVisbilityViaPhysics = false; TargetVisibilityIgnoreLayerMask = 0; // "Nothing" by default! LookAt = new Vector3(0, 0, 0); MoveDampening = 5f; MinBounds = new Vector3(-100, -100, -100); MaxBounds = new Vector3(100, 100, 100); Distance = 16f; MinDistance = 8f; MaxDistance = 32f; ZoomDampening = 5f; Rotation = 0f; RotationDampening = 5f; Tilt = 45f; MinTilt = 30f; MaxTilt = 85f; TiltDampening = 5f; FollowBehind = false; FollowRotationOffset = 0; } protected void Start() { if (rigidbody) { // don't allow camera to rotate rigidbody.freezeRotation = true; } // // store initial values so that we can reset them using ResetToInitialValues method // _initialLookAt = LookAt; _initialDistance = Distance; _initialRotation = Rotation; _initialTilt = Tilt; // // set our current values to the desired values so that we don't "slide in" // _currDistance = Distance; _currRotation = Rotation; _currTilt = Tilt; // // create a target sphere, hidden by default // CreateTarget(); } protected void Update() { // // show or hide camera target (mainly for debugging purposes) // if (_lastDebugCamera != ShowDebugCameraTarget) { if (_targetRenderer != null) { _targetRenderer.enabled = ShowDebugCameraTarget; _lastDebugCamera = ShowDebugCameraTarget; } } } protected void LateUpdate() { // // update desired target position // if (IsFollowing) { LookAt = _followTarget.position; } else { _moveVector.y = 0; LookAt += Quaternion.Euler(0, Rotation, 0) * _moveVector; LookAt.y = GetHeightAt(LookAt.x, LookAt.z); } LookAt.y += LookAtHeightOffset; // // clamp values // Tilt = Mathf.Clamp(Tilt, MinTilt, MaxTilt); Distance = Mathf.Clamp(Distance, MinDistance, MaxDistance); LookAt = new Vector3(Mathf.Clamp(LookAt.x, MinBounds.x, MaxBounds.x), Mathf.Clamp(LookAt.y, MinBounds.y, MaxBounds.y), Mathf.Clamp(LookAt.z, MinBounds.z, MaxBounds.z)); // // move from "desired" to "target" values // if (Smoothing) { _currRotation = Mathf.LerpAngle(_currRotation, Rotation, Time.deltaTime * RotationDampening); _currDistance = Mathf.Lerp(_currDistance, Distance, Time.deltaTime * ZoomDampening); _currTilt = Mathf.LerpAngle(_currTilt, Tilt, Time.deltaTime * TiltDampening); _target.transform.position = Vector3.Lerp(_target.transform.position, LookAt, Time.deltaTime * MoveDampening); } else { _currRotation = Rotation; _currDistance = Distance; _currTilt = Tilt; _target.transform.position = LookAt; } _moveVector = Vector3.zero; // // if we're following AND forcing behind, override the rotation to point to target (with offset) // if (IsFollowing && FollowBehind) { ForceFollowBehind(); } // // optionally, we'll check to make sure the target is visible // Note: we only do this when following so that we don't "jar" when moving manually // if (IsFollowing && TargetVisbilityViaPhysics && DistanceToTargetIsLessThan(1f)) { EnsureTargetIsVisible(); } // // recalculate the actual position of the camera based on the above // UpdateCamera(); } #endregion // // PUBLIC METHODS // #region PUBLIC_METHODS /// <summary> /// Current transform of camera target (NOTE: should not be set directly) /// </summary> public Transform CameraTarget { get { return _target.transform; } } /// <summary> /// True if the current camera auto-follow target is set. Else, false. /// </summary> public bool IsFollowing { get { return FollowTarget != null; } } /// <summary> /// Current auto-follow target /// </summary> public Transform FollowTarget { get { return _followTarget; } } /// <summary> /// Reset camera to initial (startup) position, distance, rotation, tilt, etc. /// </summary> /// <param name="includePosition">If true, position will be reset as well. If false, only distance/rotation/tilt.</param> /// <param name="snap">If true, camera will snap instantly to the position. If false, camera will slide smoothly back to initial values.</param> public void ResetToInitialValues(bool includePosition, bool snap = false) { if (includePosition) LookAt = _initialLookAt; Distance = _initialDistance; Rotation = _initialRotation; Tilt = _initialTilt; if (snap) { _currDistance = Distance; _currRotation = Rotation; _currTilt = Tilt; _target.transform.position = LookAt; } } /// <summary> /// Manually set target position (snap or slide). /// </summary> /// <param name="toPosition">Vector3 position</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void JumpTo(Vector3 toPosition, bool snap = false) { EndFollow(); LookAt = toPosition; if (snap) { _target.transform.position = toPosition; } } /// <summary> /// Manually set target position (snap or slide). /// </summary> /// <param name="toTransform">Transform to which the camera target will be moved</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void JumpTo(Transform toTransform, bool snap = false) { JumpTo(toTransform.position, snap); } /// <summary> /// Manually set target position (snap or slide). /// </summary> /// <param name="toGameObject">GameObject to which the camera target will be moved</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void JumpTo(GameObject toGameObject, bool snap = false) { JumpTo(toGameObject.transform.position, snap); } /// <summary> /// Set current auto-follow target (snap or slide). /// </summary> /// <param name="followTarget">Transform which the camera should follow</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void Follow(Transform followTarget, bool snap = false) { if (_followTarget != null) { if (OnEndFollow != null) { OnEndFollow(_followTarget); } } _followTarget = followTarget; if (_followTarget != null) { if (snap) { LookAt = _followTarget.position; } if (OnBeginFollow != null) { OnBeginFollow(_followTarget); } } } /// <summary> /// Set current auto-follow target (snap or slide). /// </summary> /// <param name="followTarget">GameObject which the camera should follow</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void Follow(GameObject followTarget, bool snap = false) { Follow(followTarget.transform); } /// <summary> /// Break auto-follow. Camera will now be manually controlled by player input. /// </summary> public void EndFollow() { Follow((Transform)null, false); } /// <summary> /// Adds movement to the camera (world coordinates). /// </summary> /// <param name="dx">World coordinate X distance to move</param> /// <param name="dy">World coordinate Y distance to move</param> /// <param name="dz">World coordinate Z distance to move</param> public void AddToPosition(float dx, float dy, float dz) { _moveVector += new Vector3(dx, dy, dz); } #endregion // // PRIVATE METHODS // #region PRIVATE_METHODS /// <summary> /// If "GetTerrainHeight" function set, will call to obtain desired camera height (y position). /// Else, if TerrainHeightViaPhysics is true, will use Physics.RayCast to determine camera height. /// Else, will assume flat terrain and will return "0" (which will later be offset by LookAtHeightOffset) /// </summary> /// <param name="x"></param> /// <param name="z"></param> /// <returns></returns> private float GetHeightAt(float x, float z) { // // priority 1: use supplied function to get height at point // if (GetTerrainHeight != null) { return GetTerrainHeight(x, z); } // // priority 2: use physics ray casting to get height at point // if (TerrainHeightViaPhysics) { var y = MaxBounds.y; var maxDist = MaxBounds.y - MinBounds.y + 1f; RaycastHit hitInfo; if (Physics.Raycast(new Vector3(x, y, z), new Vector3(0, -1, 0), out hitInfo, maxDist, TerrainPhysicsLayerMask)) { return hitInfo.point.y; } return 0; // no hit! } // // assume flat terrain // return 0; } /// <summary> /// Update the camera position and rotation based on calculated values /// </summary> private void UpdateCamera() { var rotation = Quaternion.Euler(_currTilt, _currRotation, 0); var v = new Vector3(0.0f, 0.0f, -_currDistance); var position = rotation * v + _target.transform.position; if (camera.orthographic) { camera.orthographicSize = _currDistance; } // update position and rotation of camera transform.rotation = rotation; transform.position = position; } /// <summary> /// Creates the camera's target, initially not visible. /// </summary> private void CreateTarget() { _target = GameObject.CreatePrimitive(PrimitiveType.Sphere); _target.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); _target.renderer.material.color = Color.green; var targetCollider = _target.GetComponent<Collider>(); if (targetCollider != null) { targetCollider.enabled = false; } _targetRenderer = _target.GetComponent<MeshRenderer>(); _targetRenderer.enabled = false; _target.name = "CameraTarget"; _target.transform.position = LookAt; } private bool DistanceToTargetIsLessThan(float sqrDistance) { if (!IsFollowing) return true; // our distance is technically zero var p1 = _target.transform.position; var p2 = _followTarget.position; p1.y = p2.y = 0; // ignore height offset var v = p1 - p2; var vd = v.sqrMagnitude; // use sqr for performance return vd < sqrDistance; } private void EnsureTargetIsVisible() { var direction = (transform.position - _target.transform.position); direction.Normalize(); var distance = Distance; RaycastHit hitInfo; if (Physics.Raycast(_target.transform.position, direction, out hitInfo, distance, ~TargetVisibilityIgnoreLayerMask)) { if (hitInfo.transform != _target) // don't collide with outself! { _currDistance = hitInfo.distance - 0.1f; } } } private void ForceFollowBehind() { var v = _followTarget.transform.forward * -1; var angle = Vector3.Angle(Vector3.forward, v); var sign = (Vector3.Dot(v, Vector3.right) > 0.0f) ? 1.0f : -1.0f; _currRotation = Rotation = 180f + (sign * angle) + FollowRotationOffset; } #endregion }
//---------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Security { using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Runtime; using System.Security.Authentication.ExtendedProtection; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.ServiceModel.Security.Tokens; using System.Globalization; /* * See * http://xws/gxa/main/specs/security/security_profiles/SecurityProfiles.doc * for details on security protocols * Concrete implementations are required to me thread safe after * Open() is called; * instances of concrete protocol factories are scoped to a * channel/listener factory; * Each channel/listener factory must have a * SecurityProtocolFactory set on it before open/first use; the * factory instance cannot be changed once the factory is opened * or listening; * security protocol instances are scoped to a channel and will be * created by the Create calls on protocol factories; * security protocol instances are required to be thread-safe. * for typical subclasses, factory wide state and immutable * settings are expected to be on the ProtocolFactory itself while * channel-wide state is maintained internally in each security * protocol instance; * the security protocol instance set on a channel cannot be * changed; however, the protocol instance may change internal * state; this covers RM's SCT renego case; by keeping state * change internal to protocol instances, we get better * coordination with concurrent message security on channels; * the primary pivot in creating a security protocol instance is * initiator (client) vs. responder (server), NOT sender vs * receiver * Create calls for input and reply channels will contain the * listener-wide state (if any) created by the corresponding call * on the factory; */ // Whether we need to add support for targetting different SOAP roles is tracked by 19144 abstract class SecurityProtocolFactory : ISecurityCommunicationObject { internal const bool defaultAddTimestamp = true; internal const bool defaultDeriveKeys = true; internal const bool defaultDetectReplays = true; internal const string defaultMaxClockSkewString = "00:05:00"; internal const string defaultReplayWindowString = "00:05:00"; internal static readonly TimeSpan defaultMaxClockSkew = TimeSpan.Parse(defaultMaxClockSkewString, CultureInfo.InvariantCulture); internal static readonly TimeSpan defaultReplayWindow = TimeSpan.Parse(defaultReplayWindowString, CultureInfo.InvariantCulture); internal const int defaultMaxCachedNonces = 900000; internal const string defaultTimestampValidityDurationString = "00:05:00"; internal static readonly TimeSpan defaultTimestampValidityDuration = TimeSpan.Parse(defaultTimestampValidityDurationString, CultureInfo.InvariantCulture); internal const SecurityHeaderLayout defaultSecurityHeaderLayout = SecurityHeaderLayout.Strict; static ReadOnlyCollection<SupportingTokenAuthenticatorSpecification> emptyTokenAuthenticators; bool actAsInitiator; bool isDuplexReply; bool addTimestamp = defaultAddTimestamp; bool detectReplays = defaultDetectReplays; bool expectIncomingMessages; bool expectOutgoingMessages; SecurityAlgorithmSuite incomingAlgorithmSuite = SecurityAlgorithmSuite.Default; // per receiver protocol factory lists ICollection<SupportingTokenAuthenticatorSpecification> channelSupportingTokenAuthenticatorSpecification; Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>> scopedSupportingTokenAuthenticatorSpecification; Dictionary<string, MergedSupportingTokenAuthenticatorSpecification> mergedSupportingTokenAuthenticatorsMap; int maxCachedNonces = defaultMaxCachedNonces; TimeSpan maxClockSkew = defaultMaxClockSkew; NonceCache nonceCache = null; SecurityAlgorithmSuite outgoingAlgorithmSuite = SecurityAlgorithmSuite.Default; TimeSpan replayWindow = defaultReplayWindow; SecurityStandardsManager standardsManager = SecurityStandardsManager.DefaultInstance; SecurityTokenManager securityTokenManager; SecurityBindingElement securityBindingElement; string requestReplyErrorPropertyName; NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken> derivedKeyTokenAuthenticator; TimeSpan timestampValidityDuration = defaultTimestampValidityDuration; AuditLogLocation auditLogLocation; bool suppressAuditFailure; SecurityHeaderLayout securityHeaderLayout; AuditLevel serviceAuthorizationAuditLevel; AuditLevel messageAuthenticationAuditLevel; bool expectKeyDerivation; bool expectChannelBasicTokens; bool expectChannelSignedTokens; bool expectChannelEndorsingTokens; bool expectSupportingTokens; Uri listenUri; MessageSecurityVersion messageSecurityVersion; WrapperSecurityCommunicationObject communicationObject; Uri privacyNoticeUri; int privacyNoticeVersion; IMessageFilterTable<EndpointAddress> endpointFilterTable; ExtendedProtectionPolicy extendedProtectionPolicy; BufferManager streamBufferManager = null; protected SecurityProtocolFactory() { this.channelSupportingTokenAuthenticatorSpecification = new Collection<SupportingTokenAuthenticatorSpecification>(); this.scopedSupportingTokenAuthenticatorSpecification = new Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>>(); this.communicationObject = new WrapperSecurityCommunicationObject(this); } internal SecurityProtocolFactory(SecurityProtocolFactory factory) : this() { if (factory == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("factory"); } this.actAsInitiator = factory.actAsInitiator; this.addTimestamp = factory.addTimestamp; this.detectReplays = factory.detectReplays; this.incomingAlgorithmSuite = factory.incomingAlgorithmSuite; this.maxCachedNonces = factory.maxCachedNonces; this.maxClockSkew = factory.maxClockSkew; this.outgoingAlgorithmSuite = factory.outgoingAlgorithmSuite; this.replayWindow = factory.replayWindow; this.channelSupportingTokenAuthenticatorSpecification = new Collection<SupportingTokenAuthenticatorSpecification>(new List<SupportingTokenAuthenticatorSpecification>(factory.channelSupportingTokenAuthenticatorSpecification)); this.scopedSupportingTokenAuthenticatorSpecification = new Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>>(factory.scopedSupportingTokenAuthenticatorSpecification); this.standardsManager = factory.standardsManager; this.timestampValidityDuration = factory.timestampValidityDuration; this.auditLogLocation = factory.auditLogLocation; this.suppressAuditFailure = factory.suppressAuditFailure; this.serviceAuthorizationAuditLevel = factory.serviceAuthorizationAuditLevel; this.messageAuthenticationAuditLevel = factory.messageAuthenticationAuditLevel; if (factory.securityBindingElement != null) { this.securityBindingElement = (SecurityBindingElement) factory.securityBindingElement.Clone(); } this.securityTokenManager = factory.securityTokenManager; this.privacyNoticeUri = factory.privacyNoticeUri; this.privacyNoticeVersion = factory.privacyNoticeVersion; this.endpointFilterTable = factory.endpointFilterTable; this.extendedProtectionPolicy = factory.extendedProtectionPolicy; this.nonceCache = factory.nonceCache; } protected WrapperSecurityCommunicationObject CommunicationObject { get { return this.communicationObject; } } // The ActAsInitiator value is set automatically on Open and // remains unchanged thereafter. ActAsInitiator is true for // the initiator of the message exchange, such as the sender // of a datagram, sender of a request and sender of either leg // of a duplex exchange. public bool ActAsInitiator { get { return this.actAsInitiator; } } public BufferManager StreamBufferManager { get { if (this.streamBufferManager == null) { this.streamBufferManager = BufferManager.CreateBufferManager(0, int.MaxValue); } return this.streamBufferManager; } set { this.streamBufferManager = value; } } public ExtendedProtectionPolicy ExtendedProtectionPolicy { get { return this.extendedProtectionPolicy; } set { this.extendedProtectionPolicy = value; } } internal bool IsDuplexReply { get { return this.isDuplexReply; } set { this.isDuplexReply = value; } } public bool AddTimestamp { get { return this.addTimestamp; } set { ThrowIfImmutable(); this.addTimestamp = value; } } public AuditLogLocation AuditLogLocation { get { return this.auditLogLocation; } set { ThrowIfImmutable(); AuditLogLocationHelper.Validate(value); this.auditLogLocation = value; } } public bool SuppressAuditFailure { get { return this.suppressAuditFailure; } set { ThrowIfImmutable(); this.suppressAuditFailure = value; } } public AuditLevel ServiceAuthorizationAuditLevel { get { return this.serviceAuthorizationAuditLevel; } set { ThrowIfImmutable(); AuditLevelHelper.Validate(value); this.serviceAuthorizationAuditLevel = value; } } public AuditLevel MessageAuthenticationAuditLevel { get { return this.messageAuthenticationAuditLevel; } set { ThrowIfImmutable(); AuditLevelHelper.Validate(value); this.messageAuthenticationAuditLevel = value; } } public bool DetectReplays { get { return this.detectReplays; } set { ThrowIfImmutable(); this.detectReplays = value; } } public Uri PrivacyNoticeUri { get { return this.privacyNoticeUri; } set { ThrowIfImmutable(); this.privacyNoticeUri = value; } } public int PrivacyNoticeVersion { get { return this.privacyNoticeVersion; } set { ThrowIfImmutable(); this.privacyNoticeVersion = value; } } public IMessageFilterTable<EndpointAddress> EndpointFilterTable { get { return this.endpointFilterTable; } set { ThrowIfImmutable(); this.endpointFilterTable = value; } } static ReadOnlyCollection<SupportingTokenAuthenticatorSpecification> EmptyTokenAuthenticators { get { if (emptyTokenAuthenticators == null) { emptyTokenAuthenticators = Array.AsReadOnly(new SupportingTokenAuthenticatorSpecification[0]); } return emptyTokenAuthenticators; } } internal NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken> DerivedKeyTokenAuthenticator { get { return this.derivedKeyTokenAuthenticator; } } internal bool ExpectIncomingMessages { get { return this.expectIncomingMessages; } } internal bool ExpectOutgoingMessages { get { return this.expectOutgoingMessages; } } internal bool ExpectKeyDerivation { get { return this.expectKeyDerivation; } set { this.expectKeyDerivation = value; } } internal bool ExpectSupportingTokens { get { return this.expectSupportingTokens; } set { this.expectSupportingTokens = value; } } public SecurityAlgorithmSuite IncomingAlgorithmSuite { get { return this.incomingAlgorithmSuite; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } this.incomingAlgorithmSuite = value; } } protected bool IsReadOnly { get { return this.CommunicationObject.State != CommunicationState.Created; } } public int MaxCachedNonces { get { return this.maxCachedNonces; } set { ThrowIfImmutable(); if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } this.maxCachedNonces = value; } } public TimeSpan MaxClockSkew { get { return this.maxClockSkew; } set { ThrowIfImmutable(); if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } this.maxClockSkew = value; } } public NonceCache NonceCache { get { return this.nonceCache; } set { ThrowIfImmutable(); this.nonceCache = value; } } public SecurityAlgorithmSuite OutgoingAlgorithmSuite { get { return this.outgoingAlgorithmSuite; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } this.outgoingAlgorithmSuite = value; } } public TimeSpan ReplayWindow { get { return this.replayWindow; } set { ThrowIfImmutable(); if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero))); } this.replayWindow = value; } } public ICollection<SupportingTokenAuthenticatorSpecification> ChannelSupportingTokenAuthenticatorSpecification { get { return this.channelSupportingTokenAuthenticatorSpecification; } } public Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>> ScopedSupportingTokenAuthenticatorSpecification { get { return this.scopedSupportingTokenAuthenticatorSpecification; } } public SecurityBindingElement SecurityBindingElement { get { return this.securityBindingElement; } set { ThrowIfImmutable(); if (value != null) { value = (SecurityBindingElement) value.Clone(); } this.securityBindingElement = value; } } public SecurityTokenManager SecurityTokenManager { get { return this.securityTokenManager; } set { ThrowIfImmutable(); this.securityTokenManager = value; } } public virtual bool SupportsDuplex { get { return false; } } public SecurityHeaderLayout SecurityHeaderLayout { get { return this.securityHeaderLayout; } set { ThrowIfImmutable(); this.securityHeaderLayout = value; } } public virtual bool SupportsReplayDetection { get { return true; } } public virtual bool SupportsRequestReply { get { return true; } } public SecurityStandardsManager StandardsManager { get { return this.standardsManager; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } this.standardsManager = value; } } public TimeSpan TimestampValidityDuration { get { return this.timestampValidityDuration; } set { ThrowIfImmutable(); if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero))); } this.timestampValidityDuration = value; } } public Uri ListenUri { get { return this.listenUri; } set { ThrowIfImmutable(); this.listenUri = value; } } internal MessageSecurityVersion MessageSecurityVersion { get { return this.messageSecurityVersion; } } // ISecurityCommunicationObject members public TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnClose), timeout, callback, state); } public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnOpen), timeout, callback, state); } public void OnClosed() { } public void OnClosing() { } public void OnEndClose(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnEndOpen(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnFaulted() { } public void OnOpened() { } public void OnOpening() { } public virtual void OnAbort() { if (!this.actAsInitiator) { foreach (SupportingTokenAuthenticatorSpecification spec in this.channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.AbortTokenAuthenticatorIfRequired(spec.TokenAuthenticator); } foreach (string action in this.scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = this.scopedSupportingTokenAuthenticatorSpecification[action]; foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators) { SecurityUtils.AbortTokenAuthenticatorIfRequired(spec.TokenAuthenticator); } } } } public virtual void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (!this.actAsInitiator) { foreach (SupportingTokenAuthenticatorSpecification spec in this.channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.CloseTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); } foreach (string action in this.scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = this.scopedSupportingTokenAuthenticatorSpecification[action]; foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators) { SecurityUtils.CloseTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); } } } } public virtual object CreateListenerSecurityState() { return null; } public SecurityProtocol CreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, bool isReturnLegSecurityRequired, TimeSpan timeout) { ThrowIfNotOpen(); SecurityProtocol securityProtocol = OnCreateSecurityProtocol(target, via, listenerSecurityState, timeout); if (securityProtocol == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.ProtocolFactoryCouldNotCreateProtocol))); } return securityProtocol; } public virtual EndpointIdentity GetIdentityOfSelf() { return null; } public virtual T GetProperty<T>() { if (typeof(T) == typeof(Collection<ISecurityContextSecurityTokenCache>)) { ThrowIfNotOpen(); Collection<ISecurityContextSecurityTokenCache> result = new Collection<ISecurityContextSecurityTokenCache>(); if (channelSupportingTokenAuthenticatorSpecification != null) { foreach (SupportingTokenAuthenticatorSpecification spec in this.channelSupportingTokenAuthenticatorSpecification) { if (spec.TokenAuthenticator is ISecurityContextSecurityTokenCacheProvider) { result.Add(((ISecurityContextSecurityTokenCacheProvider)spec.TokenAuthenticator).TokenCache); } } } return (T)(object)(result); } else { return default(T); } } protected abstract SecurityProtocol OnCreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, TimeSpan timeout); void VerifyTypeUniqueness(ICollection<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators) { // its ok to go brute force here since we are dealing with a small number of authenticators foreach (SupportingTokenAuthenticatorSpecification spec in supportingTokenAuthenticators) { Type authenticatorType = spec.TokenAuthenticator.GetType(); int numSkipped = 0; foreach (SupportingTokenAuthenticatorSpecification spec2 in supportingTokenAuthenticators) { Type spec2AuthenticatorType = spec2.TokenAuthenticator.GetType(); if (object.ReferenceEquals(spec, spec2)) { if (numSkipped > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MultipleSupportingAuthenticatorsOfSameType, spec.TokenParameters.GetType()))); } ++numSkipped; continue; } else if (authenticatorType.IsAssignableFrom(spec2AuthenticatorType) || spec2AuthenticatorType.IsAssignableFrom(authenticatorType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MultipleSupportingAuthenticatorsOfSameType, spec.TokenParameters.GetType()))); } } } } internal IList<SupportingTokenAuthenticatorSpecification> GetSupportingTokenAuthenticators(string action, out bool expectSignedTokens, out bool expectBasicTokens, out bool expectEndorsingTokens) { if (this.mergedSupportingTokenAuthenticatorsMap != null && this.mergedSupportingTokenAuthenticatorsMap.Count > 0) { if (action != null && this.mergedSupportingTokenAuthenticatorsMap.ContainsKey(action)) { MergedSupportingTokenAuthenticatorSpecification mergedSpec = this.mergedSupportingTokenAuthenticatorsMap[action]; expectSignedTokens = mergedSpec.ExpectSignedTokens; expectBasicTokens = mergedSpec.ExpectBasicTokens; expectEndorsingTokens = mergedSpec.ExpectEndorsingTokens; return mergedSpec.SupportingTokenAuthenticators; } else if (this.mergedSupportingTokenAuthenticatorsMap.ContainsKey(MessageHeaders.WildcardAction)) { MergedSupportingTokenAuthenticatorSpecification mergedSpec = this.mergedSupportingTokenAuthenticatorsMap[MessageHeaders.WildcardAction]; expectSignedTokens = mergedSpec.ExpectSignedTokens; expectBasicTokens = mergedSpec.ExpectBasicTokens; expectEndorsingTokens = mergedSpec.ExpectEndorsingTokens; return mergedSpec.SupportingTokenAuthenticators; } } expectSignedTokens = this.expectChannelSignedTokens; expectBasicTokens = this.expectChannelBasicTokens; expectEndorsingTokens = this.expectChannelEndorsingTokens; // in case the channelSupportingTokenAuthenticators is empty return null so that its Count does not get accessed. return (Object.ReferenceEquals(this.channelSupportingTokenAuthenticatorSpecification, EmptyTokenAuthenticators)) ? null : (IList<SupportingTokenAuthenticatorSpecification>) this.channelSupportingTokenAuthenticatorSpecification; } void MergeSupportingTokenAuthenticators(TimeSpan timeout) { if (this.scopedSupportingTokenAuthenticatorSpecification.Count == 0) { this.mergedSupportingTokenAuthenticatorsMap = null; } else { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.expectSupportingTokens = true; this.mergedSupportingTokenAuthenticatorsMap = new Dictionary<string, MergedSupportingTokenAuthenticatorSpecification>(); foreach (string action in this.scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> scopedAuthenticators = this.scopedSupportingTokenAuthenticatorSpecification[action]; if (scopedAuthenticators == null || scopedAuthenticators.Count == 0) { continue; } Collection<SupportingTokenAuthenticatorSpecification> mergedAuthenticators = new Collection<SupportingTokenAuthenticatorSpecification>(); bool expectSignedTokens = this.expectChannelSignedTokens; bool expectBasicTokens = this.expectChannelBasicTokens; bool expectEndorsingTokens = this.expectChannelEndorsingTokens; foreach (SupportingTokenAuthenticatorSpecification spec in this.channelSupportingTokenAuthenticatorSpecification) { mergedAuthenticators.Add(spec); } foreach (SupportingTokenAuthenticatorSpecification spec in scopedAuthenticators) { SecurityUtils.OpenTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); mergedAuthenticators.Add(spec); if (spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing) { if (spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey) { this.expectKeyDerivation = true; } } SecurityTokenAttachmentMode mode = spec.SecurityTokenAttachmentMode; if (mode == SecurityTokenAttachmentMode.SignedEncrypted || mode == SecurityTokenAttachmentMode.Signed || mode == SecurityTokenAttachmentMode.SignedEndorsing) { expectSignedTokens = true; if (mode == SecurityTokenAttachmentMode.SignedEncrypted) { expectBasicTokens = true; } } if (mode == SecurityTokenAttachmentMode.Endorsing || mode == SecurityTokenAttachmentMode.SignedEndorsing) { expectEndorsingTokens = true; } } VerifyTypeUniqueness(mergedAuthenticators); MergedSupportingTokenAuthenticatorSpecification mergedSpec = new MergedSupportingTokenAuthenticatorSpecification(); mergedSpec.SupportingTokenAuthenticators = mergedAuthenticators; mergedSpec.ExpectBasicTokens = expectBasicTokens; mergedSpec.ExpectEndorsingTokens = expectEndorsingTokens; mergedSpec.ExpectSignedTokens = expectSignedTokens; mergedSupportingTokenAuthenticatorsMap.Add(action, mergedSpec); } } } protected RecipientServiceModelSecurityTokenRequirement CreateRecipientSecurityTokenRequirement() { RecipientServiceModelSecurityTokenRequirement requirement = new RecipientServiceModelSecurityTokenRequirement(); requirement.SecurityBindingElement = this.securityBindingElement; requirement.SecurityAlgorithmSuite = this.IncomingAlgorithmSuite; requirement.ListenUri = this.listenUri; requirement.MessageSecurityVersion = this.MessageSecurityVersion.SecurityTokenVersion; requirement.AuditLogLocation = this.auditLogLocation; requirement.SuppressAuditFailure = this.suppressAuditFailure; requirement.MessageAuthenticationAuditLevel = this.messageAuthenticationAuditLevel; requirement.Properties[ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy] = this.extendedProtectionPolicy; if (this.endpointFilterTable != null) { requirement.Properties.Add(ServiceModelSecurityTokenRequirement.EndpointFilterTableProperty, this.endpointFilterTable); } return requirement; } RecipientServiceModelSecurityTokenRequirement CreateRecipientSecurityTokenRequirement(SecurityTokenParameters parameters, SecurityTokenAttachmentMode attachmentMode) { RecipientServiceModelSecurityTokenRequirement requirement = CreateRecipientSecurityTokenRequirement(); parameters.InitializeSecurityTokenRequirement(requirement); requirement.KeyUsage = SecurityKeyUsage.Signature; requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Input; requirement.Properties[ServiceModelSecurityTokenRequirement.SupportingTokenAttachmentModeProperty] = attachmentMode; requirement.Properties[ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy] = this.extendedProtectionPolicy; return requirement; } void AddSupportingTokenAuthenticators(SupportingTokenParameters supportingTokenParameters, bool isOptional, IList<SupportingTokenAuthenticatorSpecification> authenticatorSpecList) { for (int i = 0; i < supportingTokenParameters.Endorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Endorsing[i], SecurityTokenAttachmentMode.Endorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Endorsing, supportingTokenParameters.Endorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEndorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEndorsing[i], SecurityTokenAttachmentMode.SignedEndorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEndorsing, supportingTokenParameters.SignedEndorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEncrypted.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEncrypted[i], SecurityTokenAttachmentMode.SignedEncrypted); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEncrypted, supportingTokenParameters.SignedEncrypted[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.Signed.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Signed[i], SecurityTokenAttachmentMode.Signed); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Signed, supportingTokenParameters.Signed[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } } public virtual void OnOpen(TimeSpan timeout) { if (this.SecurityBindingElement == null) { this.OnPropertySettingsError("SecurityBindingElement", true); } if (this.SecurityTokenManager == null) { this.OnPropertySettingsError("SecurityTokenManager", true); } this.messageSecurityVersion = this.standardsManager.MessageSecurityVersion; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.expectOutgoingMessages = this.ActAsInitiator || this.SupportsRequestReply; this.expectIncomingMessages = !this.ActAsInitiator || this.SupportsRequestReply; if (!this.actAsInitiator) { AddSupportingTokenAuthenticators(this.securityBindingElement.EndpointSupportingTokenParameters, false, (IList<SupportingTokenAuthenticatorSpecification>)this.channelSupportingTokenAuthenticatorSpecification); AddSupportingTokenAuthenticators(this.securityBindingElement.OptionalEndpointSupportingTokenParameters, true, (IList<SupportingTokenAuthenticatorSpecification>)this.channelSupportingTokenAuthenticatorSpecification); foreach (string action in this.securityBindingElement.OperationSupportingTokenParameters.Keys) { Collection<SupportingTokenAuthenticatorSpecification> authenticatorSpecList = new Collection<SupportingTokenAuthenticatorSpecification>(); AddSupportingTokenAuthenticators(this.securityBindingElement.OperationSupportingTokenParameters[action], false, authenticatorSpecList); this.scopedSupportingTokenAuthenticatorSpecification.Add(action, authenticatorSpecList); } foreach (string action in this.securityBindingElement.OptionalOperationSupportingTokenParameters.Keys) { Collection<SupportingTokenAuthenticatorSpecification> authenticatorSpecList; ICollection<SupportingTokenAuthenticatorSpecification> existingList; if (this.scopedSupportingTokenAuthenticatorSpecification.TryGetValue(action, out existingList)) { authenticatorSpecList = ((Collection<SupportingTokenAuthenticatorSpecification>)existingList); } else { authenticatorSpecList = new Collection<SupportingTokenAuthenticatorSpecification>(); this.scopedSupportingTokenAuthenticatorSpecification.Add(action, authenticatorSpecList); } this.AddSupportingTokenAuthenticators(this.securityBindingElement.OptionalOperationSupportingTokenParameters[action], true, authenticatorSpecList); } // validate the token authenticator types and create a merged map if needed. if (!this.channelSupportingTokenAuthenticatorSpecification.IsReadOnly) { if (this.channelSupportingTokenAuthenticatorSpecification.Count == 0) { this.channelSupportingTokenAuthenticatorSpecification = EmptyTokenAuthenticators; } else { this.expectSupportingTokens = true; foreach (SupportingTokenAuthenticatorSpecification tokenAuthenticatorSpec in this.channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.OpenTokenAuthenticatorIfRequired(tokenAuthenticatorSpec.TokenAuthenticator, timeoutHelper.RemainingTime()); if (tokenAuthenticatorSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || tokenAuthenticatorSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing) { if (tokenAuthenticatorSpec.TokenParameters.RequireDerivedKeys && !tokenAuthenticatorSpec.TokenParameters.HasAsymmetricKey) { expectKeyDerivation = true; } } SecurityTokenAttachmentMode mode = tokenAuthenticatorSpec.SecurityTokenAttachmentMode; if (mode == SecurityTokenAttachmentMode.SignedEncrypted || mode == SecurityTokenAttachmentMode.Signed || mode == SecurityTokenAttachmentMode.SignedEndorsing) { this.expectChannelSignedTokens = true; if (mode == SecurityTokenAttachmentMode.SignedEncrypted) { this.expectChannelBasicTokens = true; } } if (mode == SecurityTokenAttachmentMode.Endorsing || mode == SecurityTokenAttachmentMode.SignedEndorsing) { this.expectChannelEndorsingTokens = true; } } this.channelSupportingTokenAuthenticatorSpecification = new ReadOnlyCollection<SupportingTokenAuthenticatorSpecification>((Collection<SupportingTokenAuthenticatorSpecification>)this.channelSupportingTokenAuthenticatorSpecification); } } VerifyTypeUniqueness(this.channelSupportingTokenAuthenticatorSpecification); MergeSupportingTokenAuthenticators(timeoutHelper.RemainingTime()); } if (this.DetectReplays) { if (!this.SupportsReplayDetection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("DetectReplays", SR.GetString(SR.SecurityProtocolCannotDoReplayDetection, this)); } if (this.MaxClockSkew == TimeSpan.MaxValue || this.ReplayWindow == TimeSpan.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoncesCachedInfinitely))); } // If DetectReplays is true and nonceCache is null then use the default InMemoryNonceCache. if (this.nonceCache == null) { // The nonce needs to be cached for replayWindow + 2*clockSkew to eliminate replays this.nonceCache = new InMemoryNonceCache(this.ReplayWindow + this.MaxClockSkew + this.MaxClockSkew, this.MaxCachedNonces); } } this.derivedKeyTokenAuthenticator = new NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken>(); } public void Open(bool actAsInitiator, TimeSpan timeout) { this.actAsInitiator = actAsInitiator; this.communicationObject.Open(timeout); } public IAsyncResult BeginOpen(bool actAsInitiator, TimeSpan timeout, AsyncCallback callback, object state) { this.actAsInitiator = actAsInitiator; return this.CommunicationObject.BeginOpen(timeout, callback, state); } public void EndOpen(IAsyncResult result) { this.CommunicationObject.EndOpen(result); } public void Close(bool aborted, TimeSpan timeout) { if (aborted) { this.CommunicationObject.Abort(); } else { this.CommunicationObject.Close(timeout); } } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return this.CommunicationObject.BeginClose(timeout, callback, state); } public void EndClose(IAsyncResult result) { this.CommunicationObject.EndClose(result); } internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenAuthenticator authenticator, TimeSpan timeout) { if (authenticator != null) { SecurityUtils.OpenTokenAuthenticatorIfRequired(authenticator, timeout); } else { OnPropertySettingsError(propertyName, requiredForForwardDirection); } } internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenProvider provider, TimeSpan timeout) { if (provider != null) { SecurityUtils.OpenTokenProviderIfRequired(provider, timeout); } else { OnPropertySettingsError(propertyName, requiredForForwardDirection); } } internal void OnPropertySettingsError(string propertyName, bool requiredForForwardDirection) { if (requiredForForwardDirection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.GetString(SR.PropertySettingErrorOnProtocolFactory, propertyName, this), propertyName)); } else if (this.requestReplyErrorPropertyName == null) { this.requestReplyErrorPropertyName = propertyName; } } void ThrowIfReturnDirectionSecurityNotSupported() { if (this.requestReplyErrorPropertyName != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.GetString(SR.PropertySettingErrorOnProtocolFactory, this.requestReplyErrorPropertyName, this), this.requestReplyErrorPropertyName)); } } internal void ThrowIfImmutable() { this.communicationObject.ThrowIfDisposedOrImmutable(); } void ThrowIfNotOpen() { this.communicationObject.ThrowIfNotOpened(); } } struct MergedSupportingTokenAuthenticatorSpecification { public Collection<SupportingTokenAuthenticatorSpecification> SupportingTokenAuthenticators; public bool ExpectSignedTokens; public bool ExpectEndorsingTokens; public bool ExpectBasicTokens; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; namespace SmallSharpTools.EmbeddedScripts.Controls { /// <summary> /// Includes several of the most popular Javascript libraries. /// </summary> [ToolboxData("<{0}:EmbeddedScriptsManager runat=server></{0}:EmbeddedScriptsManager>"), Designer(typeof(EmbeddedScriptsDesigner))] public class EmbeddedScriptsManager : CompositeControl { #region " Constants " private readonly string scriptTemplate = "<script type=\"text/javascript\" src=\"{0}\"></script>\n"; private readonly string Prefix = "SmallSharpTools.EmbeddedScripts.Resources."; private readonly string PrototypeScript = "prototype-1.5.0.js"; private readonly string RicoScript = "rico-1.1.2.js"; private readonly string ScriptaculousBuilderScript = "scriptaculous-js-1.7.0-builder.js"; private readonly string ScriptaculousControlsScript = "scriptaculous-js-1.7.0-controls.js"; private readonly string ScriptaculousDragDropScript = "scriptaculous-js-1.7.0-dragdrop.js"; private readonly string ScriptaculousEffectsScript = "scriptaculous-js-1.7.0-effects.js"; private readonly string ScriptaculousScript = "scriptaculous-js-1.7.0-scriptaculous.js"; private readonly string ScriptaculousSliderScript = "scriptaculous-js-1.7.0-slider.js"; private readonly string ScriptaculousUnitTestScript = "scriptaculous-js-1.7.0-unittest.js"; private readonly string DojoScript = "dojo-0.2.2-ajax.js"; private readonly string OverLibScript = "overlib-2.42.js"; private readonly string MochiKitScript = "MochiKit-1.3.1.js"; private readonly string LibertyScript = "liberty-01.js"; private readonly string JsonScript = "json-01102007.js"; private readonly string BehaviourScript = "behaviour-1.1.js"; private readonly string JQueryScript = "jquery-1.1.4.pack.js"; private readonly string JQueryJsonScript = "jquery.json.js"; private readonly string JQueryInterfaceScript = "interface-1.2.js"; private readonly string JQueryDimensionsScript = "jquery.dimensions.pack.js"; private readonly string JQueryTooltipScript = "jtip.js"; private readonly string JQueryContextMenuScript = "jquery.contextmenu.r2.packed.js"; #endregion #region " Variables " private Label label; private List<String> registeredScripts = new List<String>(); #endregion #region " Constructors " /// <summary> /// </summary> public EmbeddedScriptsManager() { Load += new EventHandler(EmbeddedScriptsManager_Load); } #endregion #region " Events " private void EmbeddedScriptsManager_Load(object sender, EventArgs e) { label.Visible = DesignMode; if (UsePrototypeScript) { RegisterScriptInclude(PrototypeScript); } if (UseJQueryScript) { RegisterScriptInclude(JQueryScript); } if (UseJQueryJsonScript) { RegisterScriptInclude(JQueryJsonScript); } if (UseJQueryInterfaceScript) { RegisterScriptInclude(JQueryInterfaceScript); } if (UseJQueryDimensionsScript) { RegisterScriptInclude(JQueryDimensionsScript); } if (UseJQueryTooltipScript) { RegisterScriptInclude(JQueryTooltipScript); } if (UseJQueryContextMenuScript) { RegisterScriptInclude(JQueryContextMenuScript); } if (UseRicoScript) { RegisterScriptInclude(RicoScript); } if (UseDojoScript) { RegisterScriptInclude(DojoScript); } if (UseOverLibScript) { RegisterScriptInclude(OverLibScript); } if (UseMochiKitScript) { RegisterScriptInclude(MochiKitScript); } if (UseLibertyScript) { RegisterScriptInclude(LibertyScript); } if (UseJsonScript) { RegisterScriptInclude(JsonScript); } if (UseBehaviourScript) { RegisterScriptInclude(BehaviourScript); } if (UseScriptaculousScript) { RegisterScriptInclude(ScriptaculousScript); } if (UseScriptaculousBuilderScript) { RegisterScriptInclude(ScriptaculousBuilderScript); } if (UseScriptaculousEffectsScript) { RegisterScriptInclude(ScriptaculousEffectsScript); } if (UseScriptaculousDragDropScript) { RegisterScriptInclude(ScriptaculousDragDropScript); } if (UseScriptaculousSliderScript) { RegisterScriptInclude(ScriptaculousSliderScript); } if (UseScriptaculousControlsScript) { RegisterScriptInclude(ScriptaculousControlsScript); } if (UseScriptaculousUnitTestScript) { RegisterScriptInclude(ScriptaculousUnitTestScript); } } #endregion #region " Rendering " /// <summary> /// </summary> protected override void CreateChildControls() { // Clear child controls Controls.Clear(); // Build the control tree CreateControlHierarchy(); // Clear the viewstate of child controls ClearChildViewState(); } /// <summary> /// Creates control hierarchy /// </summary> protected void CreateControlHierarchy() { if (label == null) { label = new Label(); label.Text = ClientID; } } #endregion #region " Properties " private bool _isVerbose = true; /// <summary> /// Shows comments with script include references /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(true), Description("Shows comments with script include references")] public bool IsVerbose { get { EnsureChildControls(); return _isVerbose; } set { EnsureChildControls(); _isVerbose = value; } } private bool _usePrototypeScript = false; /// <summary> /// Prototype Library (http://www.prototypejs.org/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Prototype Library (http://www.prototypejs.org/)")] public bool UsePrototypeScript { get { EnsureChildControls(); return _usePrototypeScript; } set { EnsureChildControls(); _usePrototypeScript = value; } } private bool _useJQueryScript = false; /// <summary> /// jQuery Library (http://jquery.com/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("jQuery Library (http://jquery.com/)")] public bool UseJQueryScript { get { EnsureChildControls(); return _useJQueryScript; } set { EnsureChildControls(); _useJQueryScript = value; } } private bool _useJQueryJsonScript = false; /// <summary> /// jQuery JSON Plugin (http://mg.to/2006/01/25/json-for-jquery) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("jQuery JSON Plugin (http://mg.to/2006/01/25/json-for-jquery)")] public bool UseJQueryJsonScript { get { EnsureChildControls(); return _useJQueryJsonScript; } set { EnsureChildControls(); if (value) { UseJQueryScript = true; } _useJQueryJsonScript = value; } } private bool _useJQueryInterfaceScript = false; /// <summary> /// jQuery Interface Plugin (http://interface.eyecon.ro/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("jQuery Interface Plugin (http://interface.eyecon.ro/)")] public bool UseJQueryInterfaceScript { get { EnsureChildControls(); return _useJQueryInterfaceScript; } set { EnsureChildControls(); if (value) { UseJQueryScript = true; } _useJQueryInterfaceScript = value; } } private bool _useJQueryDimensionsScript = false; /// <summary> /// jQuery Dimensions Plugin (http://jquery.com/plugins/project/dimensions) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("jQuery Dimensions Plugin (http://jquery.com/plugins/project/dimensions)")] public bool UseJQueryDimensionsScript { get { EnsureChildControls(); return _useJQueryDimensionsScript; } set { EnsureChildControls(); if (value) { UseJQueryScript = true; } _useJQueryDimensionsScript = value; } } private bool _useJQueryTooltipScript = false; /// <summary> /// jQuery Tooltip Plugin (http://www.codylindley.com/blogstuff/js/jtip/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("jQuery Tooltip Plugin (http://www.codylindley.com/blogstuff/js/jtip/)")] public bool UseJQueryTooltipScript { get { EnsureChildControls(); return _useJQueryTooltipScript; } set { EnsureChildControls(); if (value) { UseJQueryScript = true; } _useJQueryTooltipScript = value; } } private bool _useJQueryContextMenuScript = false; /// <summary> /// jQuery Context Menu Plugin (http://www.trendskitchens.co.nz/jquery/contextmenu/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("jQuery Context Menu (http://www.trendskitchens.co.nz/jquery/contextmenu/)")] public bool UseJQueryContextMenuScript { get { EnsureChildControls(); return _useJQueryContextMenuScript; } set { EnsureChildControls(); if (value) { UseJQueryScript = true; } _useJQueryContextMenuScript = value; } } private bool _useRicoScript = false; /// <summary> /// Rico (http://openrico.org/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Rico (http://openrico.org/)")] public bool UseRicoScript { get { EnsureChildControls(); return _useRicoScript; } set { EnsureChildControls(); _useRicoScript = value; if (value) { UsePrototypeScript = true; } } } private bool _useOverLibScript = false; /// <summary> /// OverLib (http://www.bosrup.com/web/overlib/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("OverLib (http://www.bosrup.com/web/overlib/)")] public bool UseOverLibScript { get { EnsureChildControls(); return _useOverLibScript; } set { EnsureChildControls(); _useOverLibScript = value; } } private bool _useMochiKitScript = false; /// <summary> /// MochiKit (http://mochikit.com/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("MochiKit (http://mochikit.com/)")] public bool UseMochiKitScript { get { EnsureChildControls(); return _useMochiKitScript; } set { EnsureChildControls(); _useMochiKitScript = value; } } private bool _useLibertyScript = false; /// <summary> /// Liberty (http://aka-fotos.de/web?javascript/liberty) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Liberty (http://aka-fotos.de/web?javascript/liberty)")] public bool UseLibertyScript { get { EnsureChildControls(); return _useLibertyScript; } set { EnsureChildControls(); _useLibertyScript = value; } } private bool _useJsonScript = false; /// <summary> /// JSON (http://www.json.org/js.html) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("JSON (http://www.json.org/js.html)")] public bool UseJsonScript { get { EnsureChildControls(); return _useJsonScript; } set { EnsureChildControls(); _useJsonScript = value; } } private bool _useBehaviourScript = false; /// <summary> /// Behaviour Library (http://www.bennolan.com/behaviour/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Behaviour Library (http://www.bennolan.com/behaviour/)")] public bool UseBehaviourScript { get { EnsureChildControls(); return _useBehaviourScript; } set { EnsureChildControls(); _useBehaviourScript = value; } } private bool _useScriptaculousScript = false; /// <summary> /// Scriptaculous Library (http://script.aculo.us/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Scriptaculous Library (http://script.aculo.us/)")] public bool UseScriptaculousScript { get { EnsureChildControls(); return _useScriptaculousScript; } set { EnsureChildControls(); _useScriptaculousScript = value; if (value) { UsePrototypeScript = true; } } } private bool _useScriptaculousBuilderScript = false; /// <summary> /// Scriptaculous Library (Builder) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Scriptaculous Library (Builder)")] public bool UseScriptaculousBuilderScript { get { EnsureChildControls(); return _useScriptaculousBuilderScript; } set { EnsureChildControls(); _useScriptaculousBuilderScript = value; if (value) { UseScriptaculousScript = true; } } } private bool _useScriptaculousControlsScript = false; /// <summary> /// Scriptaculous Library (Controls) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Scriptaculous Library (Controls)")] public bool UseScriptaculousControlsScript { get { EnsureChildControls(); return _useScriptaculousControlsScript; } set { EnsureChildControls(); _useScriptaculousControlsScript = value; if (value) { UseScriptaculousScript = true; } } } private bool _useScriptaculousDragDropScript = false; /// <summary> /// Scriptaculous Library (DragDrop) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Scriptaculous Library (DragDrop)")] public bool UseScriptaculousDragDropScript { get { EnsureChildControls(); return _useScriptaculousDragDropScript; } set { EnsureChildControls(); _useScriptaculousDragDropScript = value; if (value) { UseScriptaculousScript = true; UseScriptaculousEffectsScript = true; } } } private bool _useScriptaculousEffectsScript = false; /// <summary> /// Scriptaculous Library (Effects) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Scriptaculous Library (Effects)")] public bool UseScriptaculousEffectsScript { get { EnsureChildControls(); return _useScriptaculousEffectsScript; } set { EnsureChildControls(); _useScriptaculousEffectsScript = value; if (value) { UseScriptaculousScript = true; } } } private bool _useScriptaculousSliderScript = false; /// <summary> /// Scriptaculous Library (Slider) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Scriptaculous Library (Slider)")] public bool UseScriptaculousSliderScript { get { EnsureChildControls(); return _useScriptaculousSliderScript; } set { EnsureChildControls(); _useScriptaculousSliderScript = value; if (value) { UseScriptaculousScript = true; } } } private bool _useScriptaculousUnitTestScript = false; /// <summary> /// Scriptaculous Library (UnitTests) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Scriptaculous Library (UnitTests)")] public bool UseScriptaculousUnitTestScript { get { EnsureChildControls(); return _useScriptaculousUnitTestScript; } set { EnsureChildControls(); _useScriptaculousUnitTestScript = value; if (value) { UseScriptaculousScript = true; } } } private bool _useDojoScript = false; /// <summary> /// Dojo Toolkit (http://dojotoolkit.org/) /// </summary> [Browsable(true), Category("Scripts"), DefaultValue(false), Description("Dojo Toolkit (http://dojotoolkit.org/)")] public bool UseDojoScript { get { EnsureChildControls(); return _useDojoScript; } set { EnsureChildControls(); _useDojoScript = value; } } #endregion #region " Methods " private void RegisterScriptInclude(string key) { if (!registeredScripts.Contains(key)) { registeredScripts.Add(key); string url = Page.ClientScript.GetWebResourceUrl(GetType(), Prefix + key); if (IsVerbose) { LiteralControl comment = new LiteralControl(String.Format("<!-- {0} -->\n", key)); Page.Header.Controls.Add(comment); } Page.Header.Controls.Add(new LiteralControl(String.Format(scriptTemplate, url))); } } #endregion } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: ErrorTweetModule.cs 923 2011-12-23 22:02:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Web; using System.Collections.Generic; using IDictionary = System.Collections.IDictionary; #endregion /// <summary> /// HTTP module implementation that posts tweets (short messages /// usually limited to 140 characters) about unhandled exceptions in /// an ASP.NET Web application to a Twitter account. /// </summary> /// <remarks> /// This module requires that the hosting application has permissions /// send HTTP POST requests to another Internet domain. /// </remarks> public class ErrorTweetModule : HttpModuleBase, IExceptionFiltering { public event ExceptionFilterEventHandler Filtering; private ICredentials _credentials; private string _statusFormat; private Uri _url; private int _maxStatusLength; private string _ellipsis; private string _formFormat; private List<WebRequest> _requests; /// <summary> /// Initializes the module and prepares it to handle requests. /// </summary> protected override void OnInit(HttpApplication application) { if (application == null) throw new ArgumentNullException("application"); // // Get the configuration section of this module. // If it's not there then there is nothing to initialize or do. // In this case, the module is as good as mute. // var config = (IDictionary) GetConfig(); if (config == null) return; var userName = GetSetting(config, "userName", string.Empty); var password = GetSetting(config, "password", string.Empty); var statusFormat = GetSetting(config, "statusFormat", "{Message}"); var maxStatusLength = int.Parse(GetSetting(config, "maxStatusLength", "140"), NumberStyles.None, CultureInfo.InvariantCulture); var ellipsis = GetSetting(config, "ellipsis", /* ... */ "\x2026"); var formFormat = GetSetting(config, "formFormat", "status={0}"); var url = new Uri(GetSetting(config, "url", "http://twitter.com/statuses/update.xml"), UriKind.Absolute); _credentials = new NetworkCredential(userName, password); _statusFormat = statusFormat; _url = url; _maxStatusLength = maxStatusLength; _ellipsis = ellipsis; _formFormat = formFormat; _requests = new List<WebRequest>(); // TODO Synchronization application.Error += OnError; ErrorSignal.Get(application).Raised += OnErrorSignaled; } /// <summary> /// Gets the <see cref="ErrorLog"/> instance to which the module /// will log exceptions. /// </summary> protected virtual ErrorLog GetErrorLog(HttpContextBase context) { return ErrorLog.GetDefault(context); } /// <summary> /// The handler called when an unhandled exception bubbles up to /// the module. /// </summary> protected virtual void OnError(object sender, EventArgs args) { var application = (HttpApplication) sender; LogException(application.Server.GetLastError(), new HttpContextWrapper(application.Context)); } /// <summary> /// The handler called when an exception is explicitly signaled. /// </summary> protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args) { using (args.Exception.TryScopeCallerInfo(args.CallerInfo)) LogException(args.Exception, args.Context); } /// <summary> /// Logs an exception and its context to the error log. /// </summary> protected virtual void LogException(Exception e, HttpContextBase context) { if (e == null) throw new ArgumentNullException("e"); // // Fire an event to check if listeners want to filter out // logging of the uncaught exception. // var args = new ExceptionFilterEventArgs(e, context); OnFiltering(args); if (args.Dismissed) return; // // Tweet away... // HttpWebRequest request = null; try { var status = StringFormatter.Format(_statusFormat, new Error(e, context)); // // Apply ellipsis if status is too long. If the trimmed // status plus ellipsis yields nothing then just use // the trimmed status without ellipsis. This can happen if // someone gives an ellipsis that is ridiculously long. // var maxLength = _maxStatusLength; if (status.Length > maxLength) { var ellipsis = _ellipsis; var trimmedStatusLength = maxLength - ellipsis.Length; status = trimmedStatusLength >= 0 ? status.Substring(0, trimmedStatusLength) + ellipsis : status.Substring(0, maxLength); } // // Submit the status by posting form data as typically down // by browsers for forms found in HTML. // request = (HttpWebRequest) WebRequest.Create(_url); request.Method = "POST"; // WebRequestMethods.Http.Post; request.ContentType = "application/x-www-form-urlencoded"; if (_credentials != null) // Need Basic authentication? { request.Credentials = _credentials; request.PreAuthenticate = true; } // See http://blogs.msdn.com/shitals/archive/2008/12/27/9254245.aspx request.ServicePoint.Expect100Continue = false; // // URL-encode status into the form and get the bytes to // determine and set the content length. // var encodedForm = string.Format(_formFormat, Uri.EscapeDataString(status)); var data = Encoding.ASCII.GetBytes(encodedForm); Debug.Assert(data.Length > 0); request.ContentLength = data.Length; // // Get the request stream into which the form data is to // be written. This is done asynchronously to free up this // thread. // // NOTE: We maintain a (possibly paranoid) list of // outstanding requests and add the request to it so that // it does not get treated as garbage by GC. In effect, // we are creating an explicit root. It is also possible // for this module to get disposed before a request // completes. During the callback, no other member should // be touched except the requests list! // _requests.Add(request); var ar = request.BeginGetRequestStream(OnGetRequestStreamCompleted, AsyncArgs(request, data)); } catch (Exception localException) { // // IMPORTANT! We swallow any exception raised during the // logging and send them out to the trace . The idea // here is that logging of exceptions by itself should not // be critical to the overall operation of the application. // The bad thing is that we catch ANY kind of exception, // even system ones and potentially let them slip by. // OnWebPostError(request, localException); } } private void OnWebPostError(WebRequest request, Exception e) { Debug.Assert(e != null); Trace.WriteLine(e); if (request != null) _requests.Remove(request); } private static object[] AsyncArgs(params object[] args) { return args; } private void OnGetRequestStreamCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); var args = (object[]) ar.AsyncState; OnGetRequestStreamCompleted(ar, (WebRequest) args[0], (byte[]) args[1]); } private void OnGetRequestStreamCompleted(IAsyncResult ar, WebRequest request, byte[] data) { Debug.Assert(ar != null); Debug.Assert(request != null); Debug.Assert(data != null); Debug.Assert(data.Length > 0); try { using (var output = request.EndGetRequestStream(ar)) output.Write(data, 0, data.Length); request.BeginGetResponse(OnGetResponseCompleted, request); } catch (Exception e) { OnWebPostError(request, e); } } private void OnGetResponseCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); OnGetResponseCompleted(ar, (WebRequest) ar.AsyncState); } private void OnGetResponseCompleted(IAsyncResult ar, WebRequest request) { Debug.Assert(ar != null); Debug.Assert(request != null); try { Debug.Assert(request != null); request.EndGetResponse(ar).Close(); // Not interested; assume OK _requests.Remove(request); } catch (Exception e) { OnWebPostError(request, e); } } /// <summary> /// Raises the <see cref="Filtering"/> event. /// </summary> protected virtual void OnFiltering(ExceptionFilterEventArgs args) { var handler = Filtering; if (handler != null) handler(this, args); } /// <summary> /// Determines whether the module will be registered for discovery /// in partial trust environments or not. /// </summary> protected override bool SupportDiscoverability { get { return true; } } /// <summary> /// Gets the configuration object used by <see cref="OnInit"/> to read /// the settings for module. /// </summary> protected virtual object GetConfig() { return Configuration.GetSubsection("errorTweet"); } private static string GetSetting(IDictionary config, string name, string defaultValue) { Debug.Assert(config != null); Debug.AssertStringNotEmpty(name); var value = ((string)config[name]) ?? string.Empty; if (value.Length == 0) { if (defaultValue == null) { throw new ApplicationException(string.Format( "The required configuration setting '{0}' is missing for the error tweeting module.", name)); } value = defaultValue; } return value; } } }
using System; using System.Text; using System.Threading; using LanguageExt.Effects.Traits; using LanguageExt.Sys.Traits; using static LanguageExt.Prelude; namespace LanguageExt.Sys.Test { /// <summary> /// Test IO runtime /// </summary> public readonly struct Runtime : HasCancel<Runtime>, HasConsole<Runtime>, HasFile<Runtime>, HasEncoding<Runtime>, HasTextRead<Runtime>, HasTime<Runtime>, HasEnvironment<Runtime>, HasDirectory<Runtime> { public readonly RuntimeEnv env; /// <summary> /// Constructor /// </summary> Runtime(RuntimeEnv env) => this.env = env; /// <summary> /// Configuration environment accessor /// </summary> public RuntimeEnv Env => env ?? throw new InvalidOperationException("Runtime Env not set. Perhaps because of using default(Runtime) or new Runtime() rather than Runtime.New()"); /// <summary> /// Constructor function /// </summary> /// <param name="timeSpec">Defines how time works in the runtime</param> public static Runtime New(TestTimeSpec? timeSpec = default) => new Runtime(new RuntimeEnv(new CancellationTokenSource(), System.Text.Encoding.Default, new MemoryConsole(), new MemoryFS(), timeSpec, MemorySystemEnvironment.InitFromSystem())); /// <summary> /// Constructor function /// </summary> /// <param name="source">Cancellation token source</param> /// <param name="timeSpec">Defines how time works in the runtime</param> public static Runtime New(CancellationTokenSource source, TestTimeSpec? timeSpec = default) => new Runtime(new RuntimeEnv(source, System.Text.Encoding.Default, new MemoryConsole(), new MemoryFS(), timeSpec, MemorySystemEnvironment.InitFromSystem())); /// <summary> /// Constructor function /// </summary> /// <param name="encoding">Text encoding</param> /// <param name="timeSpec">Defines how time works in the runtime</param> public static Runtime New(Encoding encoding, TestTimeSpec? timeSpec = default) => new Runtime(new RuntimeEnv(new CancellationTokenSource(), encoding, new MemoryConsole(), new MemoryFS(), timeSpec, MemorySystemEnvironment.InitFromSystem())); /// <summary> /// Constructor function /// </summary> /// <param name="encoding">Text encoding</param> /// <param name="source">Cancellation token source</param> /// <param name="timeSpec">Defines how time works in the runtime</param> public static Runtime New(Encoding encoding, CancellationTokenSource source, TestTimeSpec? timeSpec = default) => new Runtime(new RuntimeEnv(source, encoding, new MemoryConsole(), new MemoryFS(), timeSpec, MemorySystemEnvironment.InitFromSystem())); /// <summary> /// Create a new Runtime with a fresh cancellation token /// </summary> /// <remarks>Used by localCancel to create new cancellation context for its sub-environment</remarks> /// <returns>New runtime</returns> public Runtime LocalCancel => new Runtime(Env.LocalCancel); /// <summary> /// Direct access to cancellation token /// </summary> public CancellationToken CancellationToken => Env.Token; /// <summary> /// Directly access the cancellation token source /// </summary> /// <returns>CancellationTokenSource</returns> public CancellationTokenSource CancellationTokenSource => Env.Source; /// <summary> /// Get encoding /// </summary> /// <returns></returns> public Encoding Encoding => Env.Encoding; /// <summary> /// Access the console environment /// </summary> /// <returns>Console environment</returns> public Eff<Runtime, Traits.ConsoleIO> ConsoleEff => Eff<Runtime, Traits.ConsoleIO>(rt => new Test.ConsoleIO(rt.Env.Console)); /// <summary> /// Access the file environment /// </summary> /// <returns>File environment</returns> public Eff<Runtime, Traits.FileIO> FileEff => from n in Time<Runtime>.now from r in Eff<Runtime, Traits.FileIO>(rt => new Test.FileIO(rt.Env.FileSystem, n)) select r; /// <summary> /// Access the directory environment /// </summary> /// <returns>Directory environment</returns> public Eff<Runtime, Traits.DirectoryIO> DirectoryEff => from n in Time<Runtime>.now from r in Eff<Runtime, Traits.DirectoryIO>(rt => new Test.DirectoryIO(rt.Env.FileSystem, n)) select r; /// <summary> /// Access the TextReader environment /// </summary> /// <returns>TextReader environment</returns> public Eff<Runtime, Traits.TextReadIO> TextReadEff => SuccessEff(Test.TextReadIO.Default); /// <summary> /// Access the time environment /// </summary> /// <returns>Time environment</returns> public Eff<Runtime, Traits.TimeIO> TimeEff => Eff<Runtime, Traits.TimeIO>(rt => new Test.TimeIO(rt.Env.TimeSpec)); /// <summary> /// Access the operating-system environment /// </summary> /// <returns>Operating-system environment environment</returns> public Eff<Runtime, Traits.EnvironmentIO> EnvironmentEff => Eff<Runtime, Traits.EnvironmentIO>(rt => new Test.EnvironmentIO(rt.Env.SysEnv)); } public class RuntimeEnv { public readonly CancellationTokenSource Source; public readonly CancellationToken Token; public readonly Encoding Encoding; public readonly MemoryConsole Console; public readonly MemoryFS FileSystem; public readonly TestTimeSpec TimeSpec; public readonly MemorySystemEnvironment SysEnv; public RuntimeEnv( CancellationTokenSource source, CancellationToken token, Encoding encoding, MemoryConsole console, MemoryFS fileSystem, TestTimeSpec? timeSpec, MemorySystemEnvironment sysEnv) { Source = source; Token = token; Encoding = encoding; Console = console; FileSystem = fileSystem; TimeSpec = timeSpec ?? TestTimeSpec.RunningFromNow(); SysEnv = sysEnv; } public RuntimeEnv( CancellationTokenSource source, Encoding encoding, MemoryConsole console, MemoryFS fileSystem, TestTimeSpec? timeSpec, MemorySystemEnvironment sysEnv) : this(source, source.Token, encoding, console, fileSystem, timeSpec, sysEnv) { } public RuntimeEnv LocalCancel => new RuntimeEnv(new CancellationTokenSource(), Encoding, Console, FileSystem, TimeSpec, SysEnv); } }
// // ValaCompiler.cs: abstract class that provides some basic implementation for ICompiler // // Authors: // Levi Bard <[email protected]> // // Copyright (C) 2008 Levi Bard // Based on CBinding by Marcos David Marin Amador <[email protected]> // // This source code is licenced under The MIT License: // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.CodeDom.Compiler; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Diagnostics; using Mono.Addins; using MonoDevelop.Core; using MonoDevelop.Core.Execution; using MonoDevelop.Ide.Gui; using MonoDevelop.Projects; using MonoDevelop.Core.ProgressMonitoring; namespace MonoDevelop.ValaBinding { [Extension ("/ValaBinding/Compilers")] public class ValaCompiler : ICompiler { protected string compilerCommand; bool compilerFound; bool appsChecked; public ValaCompiler () { compilerCommand = "valac"; } public string Name { get{ return "valac"; } } public string CompilerCommand { get { return compilerCommand; } } /// <summary> /// Compile the project /// </summary> public BuildResult Compile(ValaProject project, ConfigurationSelector solutionConfiguration, IProgressMonitor monitor) { var projectFiles = project.Files; var packages = project.Packages; var projectConfiguration = (ValaProjectConfiguration)project.GetConfiguration(solutionConfiguration); if (!appsChecked) { // Check for compiler appsChecked = true; compilerFound = CheckApp(compilerCommand); } if (!compilerFound) { // No compiler! BuildResult cres = new BuildResult (); cres.AddError("Compiler not found: " + compilerCommand); return cres; } // Build compiler params string string compilerArgs = GetCompilerFlags(projectConfiguration) + " " + GeneratePkgCompilerArgs(packages, solutionConfiguration); // Build executable name string outputName = Path.Combine( FileService.RelativeToAbsolutePath(projectConfiguration.SourceDirectory, projectConfiguration.OutputDirectory), projectConfiguration.CompiledOutputName); monitor.BeginTask(GettextCatalog.GetString ("Compiling source"), 1); CompilerResults cr = new CompilerResults(new TempFileCollection()); bool success = DoCompilation(projectFiles, compilerArgs, outputName, monitor, cr); GenerateDepfile(projectConfiguration, packages); if (success) { monitor.Step(1); } monitor.EndTask(); return new BuildResult(cr, ""); } string ICompiler.GetCompilerFlags(ValaProjectConfiguration configuration) { return ValaCompiler.GetCompilerFlags(configuration); } /// <summary> /// Generates compiler args for the current settings /// </summary> /// <param name="configuration"> /// Project configuration /// <see cref="ValaProjectConfiguration"/> /// </param> /// <returns> /// A compiler-interpretable string /// <see cref="System.String"/> /// </returns> public static string GetCompilerFlags(ValaProjectConfiguration configuration) { List<string> args = new List<string>(); ValaCompilationParameters cp = (ValaCompilationParameters)configuration.CompilationParameters; var outputDir = FileService.RelativeToAbsolutePath(configuration.SourceDirectory, configuration.OutputDirectory); var outputNameWithoutExt = Path.GetFileNameWithoutExtension(configuration.Output); args.Add(string.Format("-d \"{0}\"", outputDir)); if (configuration.DebugMode) args.Add("-g"); switch (configuration.CompileTarget) { case ValaBinding.CompileTarget.Bin: if (cp.EnableMultithreading) { args.Add("--thread"); } break; case ValaBinding.CompileTarget.SharedLibrary: if (Platform.IsWindows) { args.Add(string.Format("--Xcc=\"-shared\" --Xcc=-I\"{0}\" -H \"{1}.h\" --library \"{1}\"", outputDir, outputNameWithoutExt)); } else { args.Add(string.Format("--Xcc=\"-shared\" --Xcc=\"-fPIC\" --Xcc=\"-I'{0}'\" -H \"{1}.h\" --library \"{1}\"", outputDir, outputNameWithoutExt)); } break; } // Valac will get these sooner or later // switch (cp.WarningLevel) // { // case WarningLevel.None: // args.Append ("-w "); // break; // case WarningLevel.Normal: // // nothing // break; // case WarningLevel.All: // args.Append ("-Wall "); // break; // } // // if (cp.WarningsAsErrors) // args.Append ("-Werror "); // if (0 < cp.OptimizationLevel) { args.Add("--Xcc=\"-O" + cp.OptimizationLevel + "\""); } // global extra compiler arguments string globalExtraCompilerArgs = PropertyService.Get("ValaBinding.ExtraCompilerOptions", ""); if (!string.IsNullOrEmpty(globalExtraCompilerArgs)) { args.Add(globalExtraCompilerArgs.Replace(Environment.NewLine, " ")); } // extra compiler arguments specific to project if (cp.ExtraCompilerArguments != null && cp.ExtraCompilerArguments.Length > 0) { args.Add(cp.ExtraCompilerArguments.Replace(Environment.NewLine, " ")); } if (cp.DefineSymbols != null && cp.DefineSymbols.Length > 0) { args.Add(ProcessDefineSymbols(cp.DefineSymbols)); } if (configuration.Includes != null) { foreach (string inc in configuration.Includes) { var includeDir = FileService.RelativeToAbsolutePath(configuration.SourceDirectory, inc); args.Add("--vapidir \"" + includeDir + "\""); } } if (configuration.Libs != null) foreach (string lib in configuration.Libs) args.Add("--pkg \"" + lib + "\""); return string.Join(" ", args.ToArray()); } /// <summary> /// Generates compiler args for depended packages /// </summary> /// <param name="packages"> /// The collection of packages for this project /// <see cref="ProjectPackageCollection"/> /// </param> /// <returns> /// The string needed by the compiler to reference the necessary packages /// <see cref="System.String"/> /// </returns> public static string GeneratePkgCompilerArgs(ProjectPackageCollection packages, ConfigurationSelector solutionConfiguration) { if (packages == null || packages.Count < 1) return string.Empty; StringBuilder libs = new StringBuilder(); foreach (ProjectPackage p in packages) { if (p.IsProject) { var proj = p.GetProject(); var projectConfiguration = (ValaProjectConfiguration)proj.GetConfiguration(solutionConfiguration); var outputDir = FileService.RelativeToAbsolutePath(projectConfiguration.SourceDirectory, projectConfiguration.OutputDirectory); var outputNameWithoutExt = Path.GetFileNameWithoutExtension(projectConfiguration.Output); var vapifile = Path.Combine(outputDir, outputNameWithoutExt + ".vapi"); libs.AppendFormat(" --Xcc=-I\"{0}\" --Xcc=-L\"{0}\" --Xcc=-l\"{1}\" \"{2}\" ", outputDir, outputNameWithoutExt, vapifile); } else { libs.AppendFormat(" --pkg \"{0}\" ", p.Name); } } return libs.ToString(); } /// <summary> /// Generates compilers flags for selected defines /// </summary> /// <param name="configuration"> /// Project configuration /// <see cref="ValaProjectConfiguration"/> /// </param> /// <returns> /// A compiler-interpretable string /// <see cref="System.String"/> /// </returns> public string GetDefineFlags (ValaProjectConfiguration configuration) { string defines = ((ValaCompilationParameters)configuration.CompilationParameters).DefineSymbols; return ProcessDefineSymbols (defines); } /// <summary> /// Determines whether a file needs to be compiled /// </summary> /// <param name="file"> /// The file in question /// <see cref="ProjectFile"/> /// </param> /// <returns> /// true if the file needs to be compiled /// <see cref="System.Boolean"/> /// </returns> private bool NeedsCompiling (ProjectFile file) { return true; } /// <summary> /// Executes a build command /// </summary> /// <param name="command"> /// The executable to be launched /// <see cref="System.String"/> /// </param> /// <param name="args"> /// The arguments to command /// <see cref="System.String"/> /// </param> /// <param name="baseDirectory"> /// The directory in which the command will be executed /// <see cref="System.String"/> /// </param> /// <param name="monitor"> /// The progress monitor to be used /// <see cref="IProgressMonitor"/> /// </param> /// <param name="errorOutput"> /// Error output will be stored here /// <see cref="System.String"/> /// </param> /// <returns> /// The exit code of the command /// <see cref="System.Int32"/> /// </returns> int ExecuteCommand (string command, string args, string baseDirectory, IProgressMonitor monitor, out string errorOutput) { errorOutput = string.Empty; int exitCode = -1; StringWriter swError = new StringWriter (); LogTextWriter chainedError = new LogTextWriter (); chainedError.ChainWriter (monitor.Log); chainedError.ChainWriter (swError); monitor.Log.WriteLine ("{0} {1}", command, args); AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor (monitor); try { ProcessWrapper p = Runtime.ProcessService.StartProcess (command, args, baseDirectory, monitor.Log, chainedError, null); operationMonitor.AddOperation (p); //handles cancellation p.WaitForOutput (); errorOutput = swError.ToString (); exitCode = p.ExitCode; p.Dispose (); if (monitor.IsCancelRequested) { monitor.Log.WriteLine (GettextCatalog.GetString ("Build cancelled")); monitor.ReportError (GettextCatalog.GetString ("Build cancelled"), null); if (exitCode == 0) exitCode = -1; } } finally { chainedError.Close (); swError.Close (); operationMonitor.Dispose (); } return exitCode; } /// <summary> /// Transforms a whitespace-delimited string of /// symbols into a set of compiler flags /// </summary> /// <param name="symbols"> /// A whitespace-delimited string of symbols, /// e.g., "DEBUG MONODEVELOP" /// <see cref="System.String"/> /// </param> /// <returns> /// A <see cref="System.String"/> /// </returns> private static string ProcessDefineSymbols (string symbols) { return ((null == symbols) || (0 == symbols.Length))? string.Empty: "-D " + Regex.Replace (symbols, " +", " -D "); } /// <summary> /// Compiles the project /// </summary> private bool DoCompilation (ProjectFileCollection projectFiles, string args, string outputName, IProgressMonitor monitor, CompilerResults cr) { StringBuilder filelist = new StringBuilder (); foreach (ProjectFile f in projectFiles) { if (f.Subtype != Subtype.Directory && f.BuildAction == BuildAction.Compile) { filelist.AppendFormat ("\"{0}\" ", f.FilePath); } }/// Build file list string compiler_args = string.Format ("{0} {1} -o \"{2}\"", args, filelist.ToString (), Path.GetFileName (outputName)); string errorOutput = string.Empty; int exitCode = ExecuteCommand (compilerCommand, compiler_args, Path.GetDirectoryName (outputName), monitor, out errorOutput); ParseCompilerOutput(errorOutput, cr, projectFiles); if (exitCode != 0 && cr.Errors.Count == 0) { // error isn't recognized but cannot ignore it because exitCode != 0 cr.Errors.Add(new CompilerError() { ErrorText = errorOutput }); } return exitCode == 0; } /// <summary> /// Cleans up intermediate files /// </summary> /// <param name="projectFiles"> /// The project's files /// <see cref="ProjectFileCollection"/> /// </param> /// <param name="configuration"> /// Project configuration /// <see cref="ValaProjectConfiguration"/> /// </param> /// <param name="monitor"> /// The progress monitor to be used /// <see cref="IProgressMonitor"/> /// </param> public void Clean(ProjectFileCollection projectFiles, ValaProjectConfiguration configuration, IProgressMonitor monitor) { /// Clean up intermediate files /// These should only be generated for libraries, but we'll check for them in all cases foreach (ProjectFile file in projectFiles) { if (file.BuildAction == BuildAction.Compile) { string cFile = Path.Combine( FileService.RelativeToAbsolutePath(configuration.SourceDirectory, configuration.OutputDirectory), Path.GetFileNameWithoutExtension(file.Name) + ".c"); if (File.Exists(cFile)) { File.Delete(cFile); } string hFile = Path.Combine( FileService.RelativeToAbsolutePath(configuration.SourceDirectory, configuration.OutputDirectory), Path.GetFileNameWithoutExtension(file.Name) + ".h"); if (File.Exists(hFile)) { File.Delete(hFile); } } } string vapiFile = Path.Combine( FileService.RelativeToAbsolutePath(configuration.SourceDirectory, configuration.OutputDirectory), configuration.Output + ".vapi"); if (File.Exists(vapiFile)) { File.Delete(vapiFile); } } /// <summary> /// Determines whether the target needs to be updated /// </summary> /// <param name="projectFiles"> /// The project's files /// <see cref="ProjectFileCollection"/> /// </param> /// <param name="target"> /// The target /// <see cref="System.String"/> /// </param> /// <returns> /// true if target needs to be updated /// <see cref="System.Boolean"/> /// </returns> private bool NeedsUpdate (ProjectFileCollection projectFiles, string target) { return true; } /// <summary> /// Parses a compiler output string into CompilerResults /// </summary> /// <param name="errorString"> /// The string output by the compiler /// <see cref="System.String"/> /// </param> /// <param name="cr"> /// The CompilerResults into which to parse errorString /// <see cref="CompilerResults"/> /// </param> protected void ParseCompilerOutput(string errorString, CompilerResults cr, ProjectFileCollection projectFiles) { TextReader reader = new StringReader(errorString); string next; while ((next = reader.ReadLine()) != null) { CompilerError error = CreateErrorFromErrorString(next, projectFiles); // System.Console.WriteLine ("Creating error from string \"{0}\"", next); if (error != null) { cr.Errors.Insert(0, error); // System.Console.WriteLine ("Adding error"); } } reader.Close(); } /// Error regex for valac /// Sample output: "/home/user/project/src/blah.vala:23.5-23.5: error: syntax error, unexpected }, expecting ;" private static Regex errorRegex = new Regex ( @"^\s*(?<file>.*):(?<line>\d*)\.(?<column>\d*)-\d*\.\d*: (?<level>[^:]*): (?<message>.*)", RegexOptions.Compiled | RegexOptions.ExplicitCapture); private static Regex gccRegex = new Regex ( @"^\s*(?<file>.*\.c):(?<line>\d*):((?<column>\d*):)?\s*(?<level>[^:]*):\s(?<message>.*)", RegexOptions.Compiled | RegexOptions.ExplicitCapture); /// Error regex for gnu linker - this could still be pertinent for vala private static Regex linkerRegex = new Regex ( @"^\s*(?<file>[^:]*):(?<line>\d*):\s*(?<message>[^:]*)", RegexOptions.Compiled | RegexOptions.ExplicitCapture); /// <summary> /// Creates a compiler error from an output string /// </summary> /// <param name="errorString"> /// The error string to be parsed /// <see cref="System.String"/> /// </param> /// <returns> /// A newly created CompilerError /// <see cref="CompilerError"/> /// </returns> private CompilerError CreateErrorFromErrorString (string errorString, ProjectFileCollection projectFiles) { Match errorMatch = null; foreach (Regex regex in new Regex[]{errorRegex, gccRegex}) if ((errorMatch = regex.Match (errorString)).Success) break; if (!errorMatch.Success) { return null; } CompilerError error = new CompilerError(); foreach (ProjectFile pf in projectFiles) { if (Path.GetFileName (pf.Name) == errorMatch.Groups["file"].Value) { error.FileName = pf.FilePath; break; } }// check for fully pathed file if (string.Empty == error.FileName) { error.FileName = errorMatch.Groups["file"].Value; }// fallback to exact match error.Line = int.Parse (errorMatch.Groups["line"].Value); if (errorMatch.Groups["column"].Success) error.Column = int.Parse (errorMatch.Groups["column"].Value); error.IsWarning = !errorMatch.Groups["level"].Value.Equals(GettextCatalog.GetString ("error"), StringComparison.Ordinal) && !errorMatch.Groups["level"].Value.StartsWith("fatal error"); error.ErrorText = errorMatch.Groups["message"].Value; return error; } /// <summary> /// Parses linker output into compiler results /// </summary> /// <param name="errorString"> /// The linker output to be parsed /// <see cref="System.String"/> /// </param> /// <param name="cr"> /// Results will be stored here /// <see cref="CompilerResults"/> /// </param> protected void ParseLinkerOutput (string errorString, CompilerResults cr) { TextReader reader = new StringReader (errorString); string next; while ((next = reader.ReadLine ()) != null) { CompilerError error = CreateLinkerErrorFromErrorString (next); if (error != null) cr.Errors.Add (error); } reader.Close (); } /// <summary> /// Creates a linker error from an output string /// </summary> /// <param name="errorString"> /// The error string to be parsed /// <see cref="System.String"/> /// </param> /// <returns> /// A newly created LinkerError /// <see cref="LinkerError"/> /// </returns> private CompilerError CreateLinkerErrorFromErrorString (string errorString) { CompilerError error = new CompilerError (); Match linkerMatch = linkerRegex.Match (errorString); if (linkerMatch.Success) { error.FileName = linkerMatch.Groups["file"].Value; error.Line = int.Parse (linkerMatch.Groups["line"].Value); error.ErrorText = linkerMatch.Groups["message"].Value; return error; } return null; } /// <summary> /// Check to see if we have a given app /// </summary> /// <param name="app"> /// The app to check /// <see cref="System.String"/> /// </param> /// <returns> /// true if the app is found /// <see cref="System.Boolean"/> /// </returns> bool CheckApp (string app) { try { ProcessWrapper p = Runtime.ProcessService.StartProcess (app, "--version", null, null); p.WaitForOutput (); return true; } catch { return false; } } public void GenerateDepfile(ValaProjectConfiguration configuration, ProjectPackageCollection packages) { try { if (configuration.CompileTarget != CompileTarget.SharedLibrary) { return; } using (StreamWriter writer = new StreamWriter(Path.Combine( FileService.RelativeToAbsolutePath(configuration.SourceDirectory, configuration.OutputDirectory), Path.ChangeExtension(configuration.Output, ".deps")))) { foreach (ProjectPackage package in packages) { writer.WriteLine(package.Name); } } } catch { /* Don't care */ } } } }
// 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. #if !NET46 using System.Buffers; #endif using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public abstract class HttpContent : IDisposable { private HttpContentHeaders _headers; private MemoryStream _bufferedContent; private bool _disposed; private Task<Stream> _contentReadStream; private bool _canCalculateLength; internal const int MaxBufferSize = int.MaxValue; internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8; private const int UTF8CodePage = 65001; private const int UTF8PreambleLength = 3; private const byte UTF8PreambleByte0 = 0xEF; private const byte UTF8PreambleByte1 = 0xBB; private const byte UTF8PreambleByte2 = 0xBF; private const int UTF8PreambleFirst2Bytes = 0xEFBB; #if !uap // UTF32 not supported on Phone private const int UTF32CodePage = 12000; private const int UTF32PreambleLength = 4; private const byte UTF32PreambleByte0 = 0xFF; private const byte UTF32PreambleByte1 = 0xFE; private const byte UTF32PreambleByte2 = 0x00; private const byte UTF32PreambleByte3 = 0x00; #endif private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE; private const int UnicodeCodePage = 1200; private const int UnicodePreambleLength = 2; private const byte UnicodePreambleByte0 = 0xFF; private const byte UnicodePreambleByte1 = 0xFE; private const int BigEndianUnicodeCodePage = 1201; private const int BigEndianUnicodePreambleLength = 2; private const byte BigEndianUnicodePreambleByte0 = 0xFE; private const byte BigEndianUnicodePreambleByte1 = 0xFF; private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF; #if DEBUG static HttpContent() { // Ensure the encoding constants used in this class match the actual data from the Encoding class AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes, UTF8PreambleByte0, UTF8PreambleByte1, UTF8PreambleByte2); #if !uap // UTF32 not supported on Phone AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UTF32PreambleByte0, UTF32PreambleByte1, UTF32PreambleByte2, UTF32PreambleByte3); #endif AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UnicodePreambleByte0, UnicodePreambleByte1); AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes, BigEndianUnicodePreambleByte0, BigEndianUnicodePreambleByte1); } private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble) { Debug.Assert(encoding != null); Debug.Assert(preamble != null); Debug.Assert(codePage == encoding.CodePage, "Encoding code page mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage); byte[] actualPreamble = encoding.GetPreamble(); Debug.Assert(preambleLength == actualPreamble.Length, "Encoding preamble length mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length); Debug.Assert(actualPreamble.Length >= 2); int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1]; Debug.Assert(first2Bytes == actualFirst2Bytes, "Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes); Debug.Assert(preamble.Length == actualPreamble.Length, "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); for (int i = 0; i < preamble.Length; i++) { Debug.Assert(preamble[i] == actualPreamble[i], "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); } } #endif public HttpContentHeaders Headers { get { if (_headers == null) { _headers = new HttpContentHeaders(this); } return _headers; } } private bool IsBuffered { get { return _bufferedContent != null; } } internal void SetBuffer(byte[] buffer, int offset, int count) { _bufferedContent = new MemoryStream(buffer, offset, count, writable: false, publiclyVisible: true); } internal bool TryGetBuffer(out ArraySegment<byte> buffer) { #if NET46 buffer = default(ArraySegment<byte>); #endif return _bufferedContent != null && _bufferedContent.TryGetBuffer(out buffer); } protected HttpContent() { // Log to get an ID for the current content. This ID is used when the content gets associated to a message. if (NetEventSource.IsEnabled) NetEventSource.Enter(this); // We start with the assumption that we can calculate the content length. _canCalculateLength = true; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } public Task<string> ReadAsStringAsync() { CheckDisposed(); return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsString()); } private string ReadBufferedContentAsString() { Debug.Assert(IsBuffered); if (_bufferedContent.Length == 0) { return string.Empty; } ArraySegment<byte> buffer; if (!TryGetBuffer(out buffer)) { buffer = new ArraySegment<byte>(_bufferedContent.ToArray()); } return ReadBufferAsString(buffer, Headers); } internal static string ReadBufferAsString(ArraySegment<byte> buffer, HttpContentHeaders headers) { // We don't validate the Content-Encoding header: If the content was encoded, it's the caller's // responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the // Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a // decoded response stream. Encoding encoding = null; int bomLength = -1; // If we do have encoding information in the 'Content-Type' header, use that information to convert // the content to a string. if ((headers.ContentType != null) && (headers.ContentType.CharSet != null)) { try { encoding = Encoding.GetEncoding(headers.ContentType.CharSet); // Byte-order-mark (BOM) characters may be present even if a charset was specified. bomLength = GetPreambleLength(buffer, encoding); } catch (ArgumentException e) { throw new InvalidOperationException(SR.net_http_content_invalid_charset, e); } } // If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present, // then check for a BOM in the data to figure out the encoding. if (encoding == null) { if (!TryDetectEncoding(buffer, out encoding, out bomLength)) { // Use the default encoding (UTF8) if we couldn't detect one. encoding = DefaultStringEncoding; // We already checked to see if the data had a UTF8 BOM in TryDetectEncoding // and DefaultStringEncoding is UTF8, so the bomLength is 0. bomLength = 0; } } // Drop the BOM when decoding the data. return encoding.GetString(buffer.Array, buffer.Offset + bomLength, buffer.Count - bomLength); } public Task<byte[]> ReadAsByteArrayAsync() { CheckDisposed(); return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsByteArray()); } internal byte[] ReadBufferedContentAsByteArray() { // The returned array is exposed out of the library, so use ToArray rather // than TryGetBuffer in order to make a copy. return _bufferedContent.ToArray(); } public Task<Stream> ReadAsStreamAsync() { CheckDisposed(); ArraySegment<byte> buffer; if (_contentReadStream == null && TryGetBuffer(out buffer)) { _contentReadStream = Task.FromResult<Stream>(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false)); } if (_contentReadStream != null) { return _contentReadStream; } _contentReadStream = CreateContentReadStreamAsync(); return _contentReadStream; } protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context); public Task CopyToAsync(Stream stream, TransportContext context) { CheckDisposed(); if (stream == null) { throw new ArgumentNullException(nameof(stream)); } try { Task task = null; ArraySegment<byte> buffer; if (TryGetBuffer(out buffer)) { task = stream.WriteAsync(buffer.Array, buffer.Offset, buffer.Count); } else { task = SerializeToStreamAsync(stream, context); CheckTaskNotNull(task); } return CopyToAsyncCore(task); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { return Task.FromException(GetStreamCopyException(e)); } } private static async Task CopyToAsyncCore(Task copyTask) { try { await copyTask.ConfigureAwait(false); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { throw GetStreamCopyException(e); } } public Task CopyToAsync(Stream stream) { return CopyToAsync(stream, null); } #if NET46 // Workaround for HttpWebRequest synchronous resubmit. This code is required because the underlying // .NET Framework HttpWebRequest implementation cannot use CopyToAsync and only uses sync based CopyTo. internal void CopyTo(Stream stream) { CopyToAsync(stream).Wait(); } #endif public Task LoadIntoBufferAsync() { return LoadIntoBufferAsync(MaxBufferSize); } // No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting // in an exception being thrown while we're buffering. // If buffering is used without a connection, it is supposed to be fast, thus no cancellation required. public Task LoadIntoBufferAsync(long maxBufferSize) { CheckDisposed(); if (maxBufferSize > HttpContent.MaxBufferSize) { // This should only be hit when called directly; HttpClient/HttpClientHandler // will not exceed this limit. throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } if (IsBuffered) { // If we already buffered the content, just return a completed task. return Task.CompletedTask; } Exception error = null; MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error); if (tempBuffer == null) { // We don't throw in LoadIntoBufferAsync(): return a faulted task. return Task.FromException(error); } try { Task task = SerializeToStreamAsync(tempBuffer, null); CheckTaskNotNull(task); return LoadIntoBufferAsyncCore(task, tempBuffer); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { return Task.FromException(GetStreamCopyException(e)); } // other synchronous exceptions from SerializeToStreamAsync/CheckTaskNotNull will propagate } private async Task LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer) { try { await serializeToStreamTask.ConfigureAwait(false); } catch (Exception e) { tempBuffer.Dispose(); // Cleanup partially filled stream. Exception we = GetStreamCopyException(e); if (we != e) throw we; throw; } try { tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data. _bufferedContent = tempBuffer; } catch (Exception e) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); throw; } } protected virtual Task<Stream> CreateContentReadStreamAsync() { // By default just buffer the content to a memory stream. Derived classes can override this behavior // if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient // way, like wrapping a read-only MemoryStream around the bytes/string) return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => (Stream)s._bufferedContent); } // Derived types return true if they're able to compute the length. It's OK if derived types return false to // indicate that they're not able to compute the length. The transport channel needs to decide what to do in // that case (send chunked, buffer first, etc.). protected internal abstract bool TryComputeLength(out long length); internal long? GetComputedOrBufferLength() { CheckDisposed(); if (IsBuffered) { return _bufferedContent.Length; } // If we already tried to calculate the length, but the derived class returned 'false', then don't try // again; just return null. if (_canCalculateLength) { long length = 0; if (TryComputeLength(out length)) { return length; } // Set flag to make sure next time we don't try to compute the length, since we know that we're unable // to do so. _canCalculateLength = false; } return null; } private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error) { Contract.Ensures((Contract.Result<MemoryStream>() != null) || (Contract.ValueAtReturn<Exception>(out error) != null)); error = null; // If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the // content length exceeds the max. buffer size. long? contentLength = Headers.ContentLength; if (contentLength != null) { Debug.Assert(contentLength >= 0); if (contentLength > maxBufferSize) { error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize)); return null; } // We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize. return new LimitMemoryStream((int)maxBufferSize, (int)contentLength); } // We couldn't determine the length of the buffer. Create a memory stream with an empty buffer. return new LimitMemoryStream((int)maxBufferSize, 0); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_contentReadStream != null && _contentReadStream.Status == TaskStatus.RanToCompletion) { _contentReadStream.Result.Dispose(); _contentReadStream = null; } if (IsBuffered) { _bufferedContent.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Helpers private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } private void CheckTaskNotNull(Task task) { if (task == null) { var e = new InvalidOperationException(SR.net_http_content_no_task_returned); if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); throw e; } } private static bool StreamCopyExceptionNeedsWrapping(Exception e) => e is IOException || e is ObjectDisposedException; private static Exception GetStreamCopyException(Exception originalException) { // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple // exceptions (depending on the underlying transport), but just HttpRequestExceptions // Custom stream should throw either IOException or HttpRequestException. // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we // don't want to hide such "usage error" exceptions in HttpRequestException. // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in // the response stream being closed. return StreamCopyExceptionNeedsWrapping(originalException) ? new HttpRequestException(SR.net_http_content_stream_copy_error, originalException) : originalException; } private static int GetPreambleLength(ArraySegment<byte> buffer, Encoding encoding) { byte[] data = buffer.Array; int offset = buffer.Offset; int dataLength = buffer.Count; Debug.Assert(data != null); Debug.Assert(encoding != null); switch (encoding.CodePage) { case UTF8CodePage: return (dataLength >= UTF8PreambleLength && data[offset + 0] == UTF8PreambleByte0 && data[offset + 1] == UTF8PreambleByte1 && data[offset + 2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0; #if !uap // UTF32 not supported on Phone case UTF32CodePage: return (dataLength >= UTF32PreambleLength && data[offset + 0] == UTF32PreambleByte0 && data[offset + 1] == UTF32PreambleByte1 && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0; #endif case UnicodeCodePage: return (dataLength >= UnicodePreambleLength && data[offset + 0] == UnicodePreambleByte0 && data[offset + 1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0; case BigEndianUnicodeCodePage: return (dataLength >= BigEndianUnicodePreambleLength && data[offset + 0] == BigEndianUnicodePreambleByte0 && data[offset + 1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0; default: byte[] preamble = encoding.GetPreamble(); return BufferHasPrefix(buffer, preamble) ? preamble.Length : 0; } } private static bool TryDetectEncoding(ArraySegment<byte> buffer, out Encoding encoding, out int preambleLength) { byte[] data = buffer.Array; int offset = buffer.Offset; int dataLength = buffer.Count; Debug.Assert(data != null); if (dataLength >= 2) { int first2Bytes = data[offset + 0] << 8 | data[offset + 1]; switch (first2Bytes) { case UTF8PreambleFirst2Bytes: if (dataLength >= UTF8PreambleLength && data[offset + 2] == UTF8PreambleByte2) { encoding = Encoding.UTF8; preambleLength = UTF8PreambleLength; return true; } break; case UTF32OrUnicodePreambleFirst2Bytes: #if !uap // UTF32 not supported on Phone if (dataLength >= UTF32PreambleLength && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3) { encoding = Encoding.UTF32; preambleLength = UTF32PreambleLength; } else #endif { encoding = Encoding.Unicode; preambleLength = UnicodePreambleLength; } return true; case BigEndianUnicodePreambleFirst2Bytes: encoding = Encoding.BigEndianUnicode; preambleLength = BigEndianUnicodePreambleLength; return true; } } encoding = null; preambleLength = 0; return false; } private static bool BufferHasPrefix(ArraySegment<byte> buffer, byte[] prefix) { byte[] byteArray = buffer.Array; if (prefix == null || byteArray == null || prefix.Length > buffer.Count || prefix.Length == 0) return false; for (int i = 0, j = buffer.Offset; i < prefix.Length; i++, j++) { if (prefix[i] != byteArray[j]) return false; } return true; } #endregion Helpers private static async Task<TResult> WaitAndReturnAsync<TState, TResult>(Task waitTask, TState state, Func<TState, TResult> returnFunc) { await waitTask.ConfigureAwait(false); return returnFunc(state); } private static Exception CreateOverCapacityException(int maxBufferSize) { return new HttpRequestException(SR.Format(SR.net_http_content_buffersize_exceeded, maxBufferSize)); } internal sealed class LimitMemoryStream : MemoryStream { private readonly int _maxSize; public LimitMemoryStream(int maxSize, int capacity) : base(capacity) { Debug.Assert(capacity <= maxSize); _maxSize = maxSize; } public int MaxSize => _maxSize; public byte[] GetSizedBuffer() { ArraySegment<byte> buffer; return TryGetBuffer(out buffer) && buffer.Offset == 0 && buffer.Count == buffer.Array.Length ? buffer.Array : ToArray(); } public override void Write(byte[] buffer, int offset, int count) { CheckSize(count); base.Write(buffer, offset, count); } public override void WriteByte(byte value) { CheckSize(1); base.WriteByte(value); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckSize(count); return base.WriteAsync(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { CheckSize(count); return base.BeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { base.EndWrite(asyncResult); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ArraySegment<byte> buffer; if (TryGetBuffer(out buffer)) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); long pos = Position; long length = Length; Position = length; long bytesToWrite = length - pos; return destination.WriteAsync(buffer.Array, (int)(buffer.Offset + pos), (int)bytesToWrite, cancellationToken); } return base.CopyToAsync(destination, bufferSize, cancellationToken); } private void CheckSize(int countToAdd) { if (_maxSize - Length < countToAdd) { throw CreateOverCapacityException(_maxSize); } } } #if !NET46 internal sealed class LimitArrayPoolWriteStream : Stream { private const int MaxByteArrayLength = 0x7FFFFFC7; private const int InitialLength = 256; private readonly int _maxBufferSize; private byte[] _buffer; private int _length; public LimitArrayPoolWriteStream(int maxBufferSize) : this(maxBufferSize, InitialLength) { } public LimitArrayPoolWriteStream(int maxBufferSize, long capacity) { if (capacity < InitialLength) { capacity = InitialLength; } else if (capacity > maxBufferSize) { throw CreateOverCapacityException(maxBufferSize); } _maxBufferSize = maxBufferSize; _buffer = ArrayPool<byte>.Shared.Rent((int)capacity); } protected override void Dispose(bool disposing) { Debug.Assert(_buffer != null); ArrayPool<byte>.Shared.Return(_buffer); _buffer = null; base.Dispose(disposing); } public ArraySegment<byte> GetBuffer() => new ArraySegment<byte>(_buffer, 0, _length); public byte[] ToArray() { var arr = new byte[_length]; Buffer.BlockCopy(_buffer, 0, arr, 0, _length); return arr; } private void EnsureCapacity(int value) { if (value > _buffer.Length) { Grow(value); } else if (value < 0) // overflow { throw CreateOverCapacityException(_maxBufferSize); } } private void Grow(int value) { Debug.Assert(value > _buffer.Length); if (value > _maxBufferSize) { throw CreateOverCapacityException(_maxBufferSize); } // Extract the current buffer to be replaced. byte[] currentBuffer = _buffer; _buffer = null; // Determine the capacity to request for the new buffer. It should be // at least twice as long as the current one, if not more if the requested // value is more than that. If the new value would put it longer than the max // allowed byte array, than shrink to that (and if the required length is actually // longer than that, we'll let the runtime throw). uint twiceLength = 2 * (uint)currentBuffer.Length; int newCapacity = twiceLength > MaxByteArrayLength ? (value > MaxByteArrayLength ? value : MaxByteArrayLength) : Math.Max(value, (int)twiceLength); // Get a new buffer, copy the current one to it, return the current one, and // set the new buffer as current. byte[] newBuffer = ArrayPool<byte>.Shared.Rent(newCapacity); Buffer.BlockCopy(currentBuffer, 0, newBuffer, 0, _length); ArrayPool<byte>.Shared.Return(currentBuffer); _buffer = newBuffer; } public override void Write(byte[] buffer, int offset, int count) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); EnsureCapacity(_length + count); Buffer.BlockCopy(buffer, offset, _buffer, _length, count); _length += count; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Write(buffer, offset, count); return Task.CompletedTask; } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override void WriteByte(byte value) { int newLength = _length + 1; EnsureCapacity(newLength); _buffer[_length] = value; _length = newLength; } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; public override long Length => _length; public override bool CanWrite => true; public override bool CanRead => false; public override bool CanSeek => false; public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } #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 System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Mail; using System.Text; namespace System.Net.Http.Headers { internal static class HeaderUtilities { private const string qualityName = "q"; internal const string ConnectionClose = "close"; internal static readonly TransferCodingHeaderValue TransferEncodingChunked = new TransferCodingHeaderValue("chunked"); internal static readonly NameValueWithParametersHeaderValue ExpectContinue = new NameValueWithParametersHeaderValue("100-continue"); internal const string BytesUnit = "bytes"; // Validator internal static readonly Action<HttpHeaderValueCollection<string>, string> TokenValidator = ValidateToken; private static readonly char[] s_hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; internal static void SetQuality(ObjectCollection<NameValueHeaderValue> parameters, double? value) { Debug.Assert(parameters != null); NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName); if (value.HasValue) { // Note that even if we check the value here, we can't prevent a user from adding an invalid quality // value using Parameters.Add(). Even if we would prevent the user from adding an invalid value // using Parameters.Add() he could always add invalid values using HttpHeaders.AddWithoutValidation(). // So this check is really for convenience to show users that they're trying to add an invalid // value. if ((value < 0) || (value > 1)) { throw new ArgumentOutOfRangeException(nameof(value)); } string qualityString = ((double)value).ToString("0.0##", NumberFormatInfo.InvariantInfo); if (qualityParameter != null) { qualityParameter.Value = qualityString; } else { parameters.Add(new NameValueHeaderValue(qualityName, qualityString)); } } else { // Remove quality parameter if (qualityParameter != null) { parameters.Remove(qualityParameter); } } } internal static bool ContainsNonAscii(string input) { Debug.Assert(input != null); foreach (char c in input) { if ((int)c > 0x7f) { return true; } } return false; } // Encode a string using RFC 5987 encoding. // encoding'lang'PercentEncodedSpecials internal static string Encode5987(string input) { // Encode a string using RFC 5987 encoding. // encoding'lang'PercentEncodedSpecials StringBuilder builder = StringBuilderCache.Acquire(); byte[] utf8bytes = ArrayPool<byte>.Shared.Rent(Encoding.UTF8.GetMaxByteCount(input.Length)); int utf8length = Encoding.UTF8.GetBytes(input, 0, input.Length, utf8bytes, 0); builder.Append("utf-8\'\'"); for (int i = 0; i < utf8length; i++) { byte utf8byte = utf8bytes[i]; // attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" // ; token except ( "*" / "'" / "%" ) if (utf8byte > 0x7F) // Encodes as multiple utf-8 bytes { AddHexEscaped(utf8byte, builder); } else if (!HttpRuleParser.IsTokenChar((char)utf8byte) || utf8byte == '*' || utf8byte == '\'' || utf8byte == '%') { // ASCII - Only one encoded byte. AddHexEscaped(utf8byte, builder); } else { builder.Append((char)utf8byte); } } Array.Clear(utf8bytes, 0, utf8length); ArrayPool<byte>.Shared.Return(utf8bytes); return StringBuilderCache.GetStringAndRelease(builder); } /// <summary>Transforms an ASCII character into its hexadecimal representation, adding the characters to a StringBuilder.</summary> private static void AddHexEscaped(byte c, StringBuilder destination) { Debug.Assert(destination != null); destination.Append('%'); destination.Append(s_hexUpperChars[(c & 0xf0) >> 4]); destination.Append(s_hexUpperChars[c & 0xf]); } internal static double? GetQuality(ObjectCollection<NameValueHeaderValue> parameters) { Debug.Assert(parameters != null); NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName); if (qualityParameter != null) { // Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal // separator is considered invalid (even if the current culture would allow it). double qualityValue = 0; if (double.TryParse(qualityParameter.Value, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out qualityValue)) { return qualityValue; } // If the stored value is an invalid quality value, just return null and log a warning. if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_invalid_quality, qualityParameter.Value)); } return null; } internal static void CheckValidToken(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } if (HttpRuleParser.GetTokenLength(value, 0) != value.Length) { throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static void CheckValidComment(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } int length = 0; if ((HttpRuleParser.GetCommentLength(value, 0, out length) != HttpParseResult.Parsed) || (length != value.Length)) // no trailing spaces allowed { throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static void CheckValidQuotedString(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } int length = 0; if ((HttpRuleParser.GetQuotedStringLength(value, 0, out length) != HttpParseResult.Parsed) || (length != value.Length)) // no trailing spaces allowed { throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y) where T : class { return AreEqualCollections(x, y, null); } internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y, IEqualityComparer<T> comparer) where T : class { if (x == null) { return (y == null) || (y.Count == 0); } if (y == null) { return (x.Count == 0); } if (x.Count != y.Count) { return false; } if (x.Count == 0) { return true; } // We have two unordered lists. So comparison is an O(n*m) operation which is expensive. Usually // headers have 1-2 parameters (if any), so this comparison shouldn't be too expensive. bool[] alreadyFound = new bool[x.Count]; int i = 0; foreach (var xItem in x) { Debug.Assert(xItem != null); i = 0; bool found = false; foreach (var yItem in y) { if (!alreadyFound[i]) { if (((comparer == null) && xItem.Equals(yItem)) || ((comparer != null) && comparer.Equals(xItem, yItem))) { alreadyFound[i] = true; found = true; break; } } i++; } if (!found) { return false; } } // Since we never re-use a "found" value in 'y', we expect 'alreadyFound' to have all fields set to 'true'. // Otherwise the two collections can't be equal and we should not get here. Debug.Assert(Array.TrueForAll(alreadyFound, value => value), "Expected all values in 'alreadyFound' to be true since collections are considered equal."); return true; } internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startIndex, bool skipEmptyValues, out bool separatorFound) { Debug.Assert(input != null); Debug.Assert(startIndex <= input.Length); // it's OK if index == value.Length. separatorFound = false; int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex); if ((current == input.Length) || (input[current] != ',')) { return current; } // If we have a separator, skip the separator and all following whitespace. If we support // empty values, continue until the current character is neither a separator nor a whitespace. separatorFound = true; current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (skipEmptyValues) { while ((current < input.Length) && (input[current] == ',')) { current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } } return current; } internal static DateTimeOffset? GetDateTimeOffsetValue(HeaderDescriptor descriptor, HttpHeaders store, DateTimeOffset? defaultValue = null) { Debug.Assert(store != null); object storedValue = store.GetParsedValues(descriptor); if (storedValue != null) { return (DateTimeOffset)storedValue; } else if (defaultValue != null && store.Contains(descriptor)) { return defaultValue; } return null; } internal static TimeSpan? GetTimeSpanValue(HeaderDescriptor descriptor, HttpHeaders store) { Debug.Assert(store != null); object storedValue = store.GetParsedValues(descriptor); if (storedValue != null) { return (TimeSpan)storedValue; } return null; } internal static bool TryParseInt32(string value, out int result) => TryParseInt32(value, 0, value.Length, out result); internal static bool TryParseInt32(string value, int offset, int length, out int result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available { if (offset < 0 || length < 0 || offset > value.Length - length) { result = 0; return false; } int tmpResult = 0; int pos = offset, endPos = offset + length; while (pos < endPos) { char c = value[pos++]; int digit = c - '0'; if ((uint)digit > 9 || // invalid digit tmpResult > int.MaxValue / 10 || // will overflow when shifting digits (tmpResult == int.MaxValue / 10 && digit > 7)) // will overflow when adding in digit { result = 0; return false; } tmpResult = (tmpResult * 10) + digit; } result = tmpResult; return true; } internal static bool TryParseInt64(string value, int offset, int length, out long result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available { if (offset < 0 || length < 0 || offset > value.Length - length) { result = 0; return false; } long tmpResult = 0; int pos = offset, endPos = offset + length; while (pos < endPos) { char c = value[pos++]; int digit = c - '0'; if ((uint)digit > 9 || // invalid digit tmpResult > long.MaxValue / 10 || // will overflow when shifting digits (tmpResult == long.MaxValue / 10 && digit > 7)) // will overflow when adding in digit { result = 0; return false; } tmpResult = (tmpResult * 10) + digit; } result = tmpResult; return true; } internal static void DumpHeaders(StringBuilder sb, params HttpHeaders[] headers) { // Appends all headers as string similar to: // { // HeaderName1: Value1 // HeaderName1: Value2 // HeaderName2: Value1 // ... // } sb.Append("{\r\n"); for (int i = 0; i < headers.Length; i++) { if (headers[i] != null) { foreach (var header in headers[i]) { foreach (var headerValue in header.Value) { sb.Append(" "); sb.Append(header.Key); sb.Append(": "); sb.Append(headerValue); sb.Append("\r\n"); } } } } sb.Append('}'); } internal static bool IsValidEmailAddress(string value) { try { #if uap new MailAddress(value); #else MailAddressParser.ParseAddress(value); #endif return true; } catch (FormatException e) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_wrong_email_format, value, e.Message)); } return false; } private static void ValidateToken(HttpHeaderValueCollection<string> collection, string value) { CheckValidToken(value, "item"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Web.Script.Services; using System.Web.Services; using System.Xml; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Web.WebServices; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.web; namespace umbraco.presentation.webservices { /// <summary> /// Summary description for nodeSorter /// </summary> [WebService(Namespace = "http://umbraco.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] [ScriptService] public class nodeSorter : UmbracoAuthorizedWebService { [WebMethod] public SortNode GetNodes(int ParentId, string App) { if (BasePage.ValidateUserContextID(BasePage.umbracoUserContextID)) { var parent = new SortNode { Id = ParentId }; var nodes = new List<SortNode>(); var entityService = base.ApplicationContext.Services.EntityService; // Root nodes? if (ParentId == -1) { if (App == "media") { var rootMedia = entityService.GetRootEntities(UmbracoObjectTypes.Media); nodes.AddRange(rootMedia.Select(media => new SortNode(media.Id, media.SortOrder, media.Name, media.CreateDate))); } else { var rootContent = entityService.GetRootEntities(UmbracoObjectTypes.Document); nodes.AddRange(rootContent.Select(content => new SortNode(content.Id, content.SortOrder, content.Name, content.CreateDate))); } } else { // "hack for stylesheet" if (App == "settings") { var cmsNode = new cms.businesslogic.CMSNode(ParentId); var styleSheet = new StyleSheet(cmsNode.Id); nodes.AddRange(styleSheet.Properties.Select(child => new SortNode(child.Id, child.sortOrder, child.Text, child.CreateDateTime))); } else { var children = entityService.GetChildren(ParentId); nodes.AddRange(children.Select(child => new SortNode(child.Id, child.SortOrder, child.Name, child.CreateDate))); } } parent.SortNodes = nodes.ToArray(); return parent; } throw new ArgumentException("User not logged in"); } [WebMethod] public void UpdateSortOrder(int ParentId, string SortOrder) { if (AuthorizeRequest() == false) return; if (SortOrder.Trim().Length <= 0) return; var isContent = helper.Request("app") == "content" | helper.Request("app") == ""; var isMedia = helper.Request("app") == "media"; //ensure user is authorized for the app requested if (isContent && AuthorizeRequest(DefaultApps.content.ToString()) == false) return; if (isMedia && AuthorizeRequest(DefaultApps.media.ToString()) == false) return; var ids = SortOrder.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (isContent) SortContent(ids, ParentId); if (isMedia) SortMedia(ids); } private void SortMedia(string[] ids) { var mediaService = base.ApplicationContext.Services.MediaService; var sortedMedia = new List<IMedia>(); try { for (var i = 0; i < ids.Length; i++) { var id = int.Parse(ids[i]); var m = mediaService.GetById(id); sortedMedia.Add(m); } // Save Media with new sort order and update content xml in db accordingly var sorted = mediaService.Sort(sortedMedia); } catch (Exception ex) { LogHelper.Error<nodeSorter>("Could not update media sort order", ex); } } private void SortContent(string[] ids, int parentId) { var contentService = base.ApplicationContext.Services.ContentService; var sortedContent = new List<IContent>(); try { for (var i = 0; i < ids.Length; i++) { var id = int.Parse(ids[i]); var c = contentService.GetById(id); sortedContent.Add(c); } // Save content with new sort order and update db+cache accordingly var sorted = contentService.Sort(sortedContent); // Refresh sort order on cached xml XmlNode parentNode = parentId == -1 ? content.Instance.XmlContent.DocumentElement : content.Instance.XmlContent.GetElementById(parentId.ToString(CultureInfo.InvariantCulture)); //only try to do the content sort if the the parent node is available... if (parentNode != null) content.SortNodes(ref parentNode); // Load balancing - then refresh entire cache // NOTE: SD: This seems a bit excessive to do simply for sorting! I'm going to leave this here for now but // the sort order should be updated in distributed calls when an item is Published (and it most likely is) // but I guess this was put here for a reason at some point. if (UmbracoSettings.UseDistributedCalls) library.RefreshContent(); // fire actionhandler, check for content BusinessLogic.Actions.Action.RunActionHandlers(new Document(parentId), ActionSort.Instance); } catch (Exception ex) { LogHelper.Error<nodeSorter>("Could not update content sort order", ex); } } } [Serializable] public class SortNode { public SortNode() { } private SortNode[] _sortNodes; public SortNode[] SortNodes { get { return _sortNodes; } set { _sortNodes = value; } } public int TotalNodes { get { return _sortNodes != null ? _sortNodes.Length : 0; } set { int test = value; } } public SortNode(int Id, int SortOrder, string Name, DateTime CreateDate) { _id = Id; _sortOrder = SortOrder; _name = Name; _createDate = CreateDate; } private DateTime _createDate; public DateTime CreateDate { get { return _createDate; } set { _createDate = value; } } private string _name; public string Name { get { return _name; } set { _name = value; } } private int _sortOrder; public int SortOrder { get { return _sortOrder; } set { _sortOrder = value; } } private int _id; public int Id { get { return _id; } set { _id = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections.Generic; using System.Text; // TPL namespaces using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Linq; using System.Reflection; namespace System.Threading.Tasks.Tests { public static class TaskRtTests { [Fact] [OuterLoop] public static void RunRunTests() { // // Test that AttachedToParent is ignored in Task.Run delegate // { Task tInner = null; // Test Run(Action) Task t1 = Task.Run(() => { tInner = new Task(() => { }, TaskCreationOptions.AttachedToParent); }); Debug.WriteLine("RunRunTests - AttachToParentIgnored: -- Waiting on outer Task. If we hang, that's a failure"); t1.Wait(); tInner.Start(); tInner.Wait(); // Test Run(Func<int>) Task<int> f1 = Task.Run(() => { tInner = new Task(() => { }, TaskCreationOptions.AttachedToParent); return 42; }); Debug.WriteLine("RunRunTests - AttachToParentIgnored: -- Waiting on outer Task<int>. If we hang, that's a failure"); f1.Wait(); tInner.Start(); tInner.Wait(); // Test Run(Func<Task>) Task t2 = Task.Run(() => { tInner = new Task(() => { }, TaskCreationOptions.AttachedToParent); Task returnTask = Task.Factory.StartNew(() => { }); return returnTask; }); Debug.WriteLine("RunRunTests - AttachToParentIgnored: -- Waiting on outer Task (unwrap-style). If we hang, that's a failure"); t2.Wait(); tInner.Start(); tInner.Wait(); Task<int> fInner = null; // Test Run(Func<Task<int>>) Task<int> f2 = Task.Run(() => { // Make sure AttachedToParent is ignored for futures as well as tasks fInner = new Task<int>(() => { return 42; }, TaskCreationOptions.AttachedToParent); Task<int> returnTask = Task<int>.Factory.StartNew(() => 11); return returnTask; }); Debug.WriteLine("RunRunTests - AttachToParentIgnored: Waiting on outer Task<int> (unwrap-style). If we hang, that's a failure"); f2.Wait(); fInner.Start(); fInner.Wait(); } // // Test basic functionality w/o cancellation token // int count = 0; Task task1 = Task.Run(() => { count = 1; }); Debug.WriteLine("RunRunTests: waiting for a task. If we hang, something went wrong."); task1.Wait(); Assert.True(count == 1, " > FAILED. Task completed but did not run."); Assert.True(task1.Status == TaskStatus.RanToCompletion, " > FAILED. Task did not end in RanToCompletion state."); Task<int> future1 = Task.Run(() => { return 7; }); Debug.WriteLine("RunRunTests - Basic w/o CT: waiting for a future. If we hang, something went wrong."); future1.Wait(); Assert.True(future1.Result == 7, " > FAILED. Future completed but did not run."); Assert.True(future1.Status == TaskStatus.RanToCompletion, " > FAILED. Future did not end in RanToCompletion state."); task1 = Task.Run(() => { return Task.Run(() => { count = 11; }); }); Debug.WriteLine("RunRunTests - Basic w/o CT: waiting for a task(unwrapped). If we hang, something went wrong."); task1.Wait(); Assert.True(count == 11, " > FAILED. Task(unwrapped) completed but did not run."); Assert.True(task1.Status == TaskStatus.RanToCompletion, " > FAILED. Task(unwrapped) did not end in RanToCompletion state."); future1 = Task.Run(() => { return Task.Run(() => 17); }); Debug.WriteLine("RunRunTests - Basic w/o CT: waiting for a future(unwrapped). If we hang, something went wrong."); future1.Wait(); Assert.True(future1.Result == 17, " > FAILED. Future(unwrapped) completed but did not run."); Assert.True(future1.Status == TaskStatus.RanToCompletion, " > FAILED. Future(unwrapped) did not end in RanToCompletion state."); // // Test basic functionality w/ uncancelled cancellation token // CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; Task task2 = Task.Run(() => { count = 21; }, token); Debug.WriteLine("RunRunTests: waiting for a task w/ uncanceled token. If we hang, something went wrong."); task2.Wait(); Assert.True(count == 21, " > FAILED. Task w/ uncanceled token completed but did not run."); Assert.True(task2.Status == TaskStatus.RanToCompletion, " > FAILED. Task w/ uncanceled token did not end in RanToCompletion state."); Task<int> future2 = Task.Run(() => 27, token); Debug.WriteLine("RunRunTests: waiting for a future w/ uncanceled token. If we hang, something went wrong."); future2.Wait(); Assert.True(future2.Result == 27, " > FAILED. Future w/ uncanceled token completed but did not run."); Assert.True(future2.Status == TaskStatus.RanToCompletion, " > FAILED. Future w/ uncanceled token did not end in RanToCompletion state."); task2 = Task.Run(() => { return Task.Run(() => { count = 31; }); }, token); Debug.WriteLine("RunRunTests: waiting for a task(unwrapped) w/ uncanceled token. If we hang, something went wrong."); task2.Wait(); Assert.True(count == 31, " > FAILED. Task(unwrapped) w/ uncanceled token completed but did not run."); Assert.True(task2.Status == TaskStatus.RanToCompletion, " > FAILED. Task(unwrapped) w/ uncanceled token did not end in RanToCompletion state."); future2 = Task.Run(() => Task.Run(() => 37), token); Debug.WriteLine("RunRunTests: waiting for a future(unwrapped) w/ uncanceled token. If we hang, something went wrong."); future2.Wait(); Assert.True(future2.Result == 37, " > FAILED. Future(unwrapped) w/ uncanceled token completed but did not run."); Assert.True(future2.Status == TaskStatus.RanToCompletion, " > FAILED. Future(unwrapped) w/ uncanceled token did not end in RanToCompletion state."); } [Fact] [OuterLoop] public static void RunRunTests_Cancellation_Negative() { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; int count = 0; // // Test that the right thing is done with a canceled cancellation token // cts.Cancel(); Task task3 = Task.Run(() => { count = 41; }, token); Debug.WriteLine("RunRunTests: waiting for a task w/ canceled token. If we hang, something went wrong."); Assert.Throws<AggregateException>( () => { task3.Wait(); }); Assert.False(count == 41, " > FAILED. Task w/ canceled token ran when it should not have."); Assert.True(task3.IsCanceled, " > FAILED. Task w/ canceled token should have ended in Canceled state"); Task future3 = Task.Run(() => { count = 47; return count; }, token); Debug.WriteLine("RunRunTests: waiting for a future w/ canceled token. If we hang, something went wrong."); Assert.Throws<AggregateException>( () => { future3.Wait(); }); Assert.False(count == 47, " > FAILED. Future w/ canceled token ran when it should not have."); Assert.True(future3.IsCanceled, " > FAILED. Future w/ canceled token should have ended in Canceled state"); task3 = Task.Run(() => { return Task.Run(() => { count = 51; }); }, token); Debug.WriteLine("RunRunTests: waiting for a task(unwrapped) w/ canceled token. If we hang, something went wrong."); Assert.Throws<AggregateException>( () => { task3.Wait(); }); Assert.False(count == 51, " > FAILED. Task(unwrapped) w/ canceled token ran when it should not have."); Assert.True(task3.IsCanceled, " > FAILED. Task(unwrapped) w/ canceled token should have ended in Canceled state"); future3 = Task.Run(() => { return Task.Run(() => { count = 57; return count; }); }, token); Debug.WriteLine("RunRunTests: waiting for a future(unwrapped) w/ canceled token. If we hang, something went wrong."); Assert.Throws<AggregateException>( () => { future3.Wait(); }); Assert.False(count == 57, " > FAILED. Future(unwrapped) w/ canceled token ran when it should not have."); Assert.True(future3.IsCanceled, " > FAILED. Future(unwrapped) w/ canceled token should have ended in Canceled state"); } [Fact] public static void RunRunTests_FastPathTests() { CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); CancellationToken token = cts.Token; // // Test that "fast paths" operate correctly // { // Create some pre-completed Tasks Task alreadyCompletedTask = Task.Factory.StartNew(() => { }); alreadyCompletedTask.Wait(); Task alreadyFaultedTask = Task.Factory.StartNew(() => { throw new Exception("FAULTED!"); }); try { alreadyFaultedTask.Wait(); } catch { } Task alreadyCanceledTask = new Task(() => { }, cts.Token); // should result in cancellation try { alreadyCanceledTask.Wait(); } catch { } // Now run them through Task.Run Task fastPath1 = Task.Run(() => alreadyCompletedTask); fastPath1.Wait(); Assert.True(fastPath1.Status == TaskStatus.RanToCompletion, "RunRunTests: Expected proxy for already-ran-to-completion task to be in RanToCompletion status"); fastPath1 = Task.Run(() => alreadyFaultedTask); try { fastPath1.Wait(); Assert.True(false, string.Format("RunRunTests: > FAILURE: Expected proxy for already-faulted Task to throw on Wait()")); } catch { } Assert.True(fastPath1.Status == TaskStatus.Faulted, "Expected proxy for already-faulted task to be in Faulted status"); fastPath1 = Task.Run(() => alreadyCanceledTask); try { fastPath1.Wait(); Assert.True(false, string.Format("RunRunTests: > FAILURE: Expected proxy for already-canceled Task to throw on Wait()")); } catch { } Assert.True(fastPath1.Status == TaskStatus.Canceled, "RunRunTests: Expected proxy for already-canceled task to be in Canceled status"); } { // Create some pre-completed Task<int>s Task<int> alreadyCompletedTask = Task<int>.Factory.StartNew(() => 42); alreadyCompletedTask.Wait(); bool doIt = true; Task<int> alreadyFaultedTask = Task<int>.Factory.StartNew(() => { if (doIt) throw new Exception("FAULTED!"); return 42; }); try { alreadyFaultedTask.Wait(); } catch { } Task<int> alreadyCanceledTask = new Task<int>(() => 42, cts.Token); // should result in cancellation try { alreadyCanceledTask.Wait(); } catch { } // Now run them through Task.Run Task<int> fastPath1 = Task.Run(() => alreadyCompletedTask); fastPath1.Wait(); Assert.True(fastPath1.Status == TaskStatus.RanToCompletion, "RunRunTests: Expected proxy for already-ran-to-completion future to be in RanToCompletion status"); fastPath1 = Task.Run(() => alreadyFaultedTask); try { fastPath1.Wait(); Assert.True(false, string.Format("RunRunTests: > FAILURE: Expected proxy for already-faulted future to throw on Wait()")); } catch { } Assert.True(fastPath1.Status == TaskStatus.Faulted, "Expected proxy for already-faulted future to be in Faulted status"); fastPath1 = Task.Run(() => alreadyCanceledTask); try { fastPath1.Wait(); Assert.True(false, string.Format("RunRunTests: > FAILURE: Expected proxy for already-canceled future to throw on Wait()")); } catch { } Assert.True(fastPath1.Status == TaskStatus.Canceled, "RunRunTests: Expected proxy for already-canceled future to be in Canceled status"); } } [Fact] public static void RunRunTests_Unwrap_NegativeCases() { // // Test cancellation/exceptions behavior in the unwrap overloads // Action<UnwrappedScenario> TestUnwrapped = delegate (UnwrappedScenario scenario) { Debug.WriteLine("RunRunTests: testing Task unwrap (scenario={0})", scenario); CancellationTokenSource cts1 = new CancellationTokenSource(); CancellationToken token1 = cts1.Token; int something = 0; Task t1 = Task.Run(() => { if (scenario == UnwrappedScenario.ThrowExceptionInDelegate) throw new Exception("thrownInDelegate"); if (scenario == UnwrappedScenario.ThrowOceInDelegate) throw new OperationCanceledException("thrownInDelegate"); return Task.Run(() => { if (scenario == UnwrappedScenario.ThrowExceptionInTask) throw new Exception("thrownInTask"); if (scenario == UnwrappedScenario.ThrowTargetOceInTask) { cts1.Cancel(); throw new OperationCanceledException(token1); } if (scenario == UnwrappedScenario.ThrowOtherOceInTask) throw new OperationCanceledException(CancellationToken.None); something = 1; }, token1); }); bool cancellationExpected = (scenario == UnwrappedScenario.ThrowOceInDelegate) || (scenario == UnwrappedScenario.ThrowTargetOceInTask); bool exceptionExpected = (scenario == UnwrappedScenario.ThrowExceptionInDelegate) || (scenario == UnwrappedScenario.ThrowExceptionInTask) || (scenario == UnwrappedScenario.ThrowOtherOceInTask); try { t1.Wait(); Assert.False(cancellationExpected || exceptionExpected, "TaskRtTests.RunRunTests: Expected exception or cancellation"); Assert.True(something == 1, "TaskRtTests.RunRunTests: Task completed but apparantly did not run"); } catch (AggregateException ae) { Assert.True(cancellationExpected || exceptionExpected, "TaskRtTests.RunRunTests: Didn't expect exception, got " + ae); } if (cancellationExpected) { Assert.True(t1.IsCanceled, "TaskRtTests.RunRunTests: Expected t1 to be Canceled, was " + t1.Status); } else if (exceptionExpected) { Assert.True(t1.IsFaulted, "TaskRtTests.RunRunTests: Expected t1 to be Faulted, was " + t1.Status); } else { Assert.True(t1.Status == TaskStatus.RanToCompletion, "TaskRtTests.RunRunTests: Expected t1 to be RanToCompletion, was " + t1.Status); } Debug.WriteLine("RunRunTests: -- testing Task<int> unwrap (scenario={0})", scenario); CancellationTokenSource cts2 = new CancellationTokenSource(); CancellationToken token2 = cts2.Token; Task<int> f1 = Task.Run(() => { if (scenario == UnwrappedScenario.ThrowExceptionInDelegate) throw new Exception("thrownInDelegate"); if (scenario == UnwrappedScenario.ThrowOceInDelegate) throw new OperationCanceledException("thrownInDelegate"); return Task.Run(() => { if (scenario == UnwrappedScenario.ThrowExceptionInTask) throw new Exception("thrownInTask"); if (scenario == UnwrappedScenario.ThrowTargetOceInTask) { cts2.Cancel(); throw new OperationCanceledException(token2); } if (scenario == UnwrappedScenario.ThrowOtherOceInTask) throw new OperationCanceledException(CancellationToken.None); return 10; }, token2); }); try { f1.Wait(); Assert.False(cancellationExpected || exceptionExpected, "RunRunTests: Expected exception or cancellation"); Assert.True(f1.Result == 10, "RunRunTests: Expected f1.Result to be 10, and it was " + f1.Result); } catch (AggregateException ae) { Assert.True(cancellationExpected || exceptionExpected, "RunRunTests: Didn't expect exception, got " + ae); } if (cancellationExpected) { Assert.True(f1.IsCanceled, "RunRunTests: Expected f1 to be Canceled, was " + f1.Status); } else if (exceptionExpected) { Assert.True(f1.IsFaulted, "RunRunTests: Expected f1 to be Faulted, was " + f1.Status); } else { Assert.True(f1.Status == TaskStatus.RanToCompletion, "RunRunTests: Expected f1 to be RanToCompletion, was " + f1.Status); } }; TestUnwrapped(UnwrappedScenario.CleanRun); // no exceptions or cancellation TestUnwrapped(UnwrappedScenario.ThrowExceptionInDelegate); // exception in delegate TestUnwrapped(UnwrappedScenario.ThrowOceInDelegate); // delegate throws OCE TestUnwrapped(UnwrappedScenario.ThrowExceptionInTask); // user-produced Task throws exception TestUnwrapped(UnwrappedScenario.ThrowTargetOceInTask); // user-produced Task throws OCE(target) TestUnwrapped(UnwrappedScenario.ThrowOtherOceInTask); // user-produced Task throws OCE(random) } [Fact] public static void RunFromResult() { // Test FromResult with value type { var results = new[] { -1, 0, 1, 1, 42, Int32.MaxValue, Int32.MinValue, 42, -42 }; // includes duplicate values to ensure that tasks from these aren't the same object Task<int>[] tasks = new Task<int>[results.Length]; for (int i = 0; i < results.Length; i++) tasks[i] = Task.FromResult(results[i]); // Make sure they've all completed for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].IsCompleted, "TaskRtTests.RunFromResult: > FAILED: Task " + i + " should have already completed (value)"); // Make sure they all completed successfully for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Status == TaskStatus.RanToCompletion, "TaskRtTests.RunFromResult: > FAILED: Task " + i + " should have already completed successfully (value)"); // Make sure no two are the same instance for (int i = 0; i < tasks.Length; i++) { for (int j = i + 1; j < tasks.Length; j++) { Assert.False(tasks[i] == tasks[j], "TaskRtTests.RunFromResult: > FAILED: " + i + " and " + j + " created tasks should not be equal (value)"); } } // Make sure they all have the correct results for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Result == results[i], "TaskRtTests.RunFromResult: > FAILED: Task " + i + " had the result " + tasks[i].Result + " but should have had " + results[i] + " (value)"); } // Test FromResult with reference type { var results = new[] { new object(), null, new object(), null, new object() }; // includes duplicate values to ensure that tasks from these aren't the same object Task<Object>[] tasks = new Task<Object>[results.Length]; for (int i = 0; i < results.Length; i++) tasks[i] = Task.FromResult(results[i]); // Make sure they've all completed for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].IsCompleted, "TaskRtTests.RunFromResult: > FAILED: Task " + i + " should have already completed (ref)"); // Make sure they all completed successfully for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Status == TaskStatus.RanToCompletion, "TaskRtTests.RunFromResult: > FAILED: Task " + i + " should have already completed successfully (ref)"); // Make sure no two are the same instance for (int i = 0; i < tasks.Length; i++) { for (int j = i + 1; j < tasks.Length; j++) { Assert.False(tasks[i] == tasks[j], "TaskRtTests.RunFromResult: > FAILED: " + i + " and " + j + " created tasks should not be equal (ref)"); } } // Make sure they all have the correct results for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Result == results[i], "TaskRtTests.RunFromResult: > FAILED: Task " + i + " had the wrong result (ref)"); } // Test FromException { var exceptions = new Exception[] { new InvalidOperationException(), new OperationCanceledException(), new Exception(), new Exception() }; // includes duplicate values to ensure that tasks from these aren't the same object var tasks = exceptions.Select(e => Task.FromException<int>(e)).ToArray(); // Make sure they've all completed for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].IsCompleted, "Task " + i + " should have already completed"); // Make sure they all completed with an error for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Status == TaskStatus.Faulted, " > FAILED: Task " + i + " should have already faulted"); // Make sure no two are the same instance for (int i = 0; i < tasks.Length; i++) { for (int j = i + 1; j < tasks.Length; j++) { Assert.True(tasks[i] != tasks[j], " > FAILED: " + i + " and " + j + " created tasks should not be equal"); } } // Make sure they all have the correct exceptions for (int i = 0; i < tasks.Length; i++) { Assert.NotNull(tasks[i].Exception); Assert.Equal(1, tasks[i].Exception.InnerExceptions.Count); Assert.Equal(exceptions[i], tasks[i].Exception.InnerException); } // Make sure we handle invalid exceptions correctly Assert.Throws<ArgumentNullException>(() => { Task.FromException<int>(null); }); // Make sure we throw from waiting on a faulted task Assert.Throws<AggregateException>(() => { var result = Task.FromException<object>(new InvalidOperationException()).Result; }); // Make sure faulted tasks are actually faulted. We have little choice for this test but to use reflection, // as the harness will crash by throwing from the unobserved event if a task goes unhandled (everywhere // other than here it's a bad thing for an exception to go unobserved) var faultedTask = Task.FromException<object>(new InvalidOperationException("uh oh")); object holderObject = null; FieldInfo isHandledField = null; var contingentPropertiesField = typeof(Task).GetField("m_contingentProperties", BindingFlags.NonPublic | BindingFlags.Instance); if (contingentPropertiesField != null) { var contingentProperties = contingentPropertiesField.GetValue(faultedTask); if (contingentProperties != null) { var exceptionsHolderField = contingentProperties.GetType().GetField("m_exceptionsHolder", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (exceptionsHolderField != null) { holderObject = exceptionsHolderField.GetValue(contingentProperties); if (holderObject != null) { isHandledField = holderObject.GetType().GetField("m_isHandled", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); } } } } Assert.NotNull(holderObject); Assert.NotNull(isHandledField); Assert.False((bool)isHandledField.GetValue(holderObject), "Expected FromException task to be unobserved before accessing Exception"); var ignored = faultedTask.Exception; Assert.True((bool)isHandledField.GetValue(holderObject), "Expected FromException task to be observed after accessing Exception"); } } [Fact] public static void RunDelayTests() { // // Test basic functionality // CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; // These should all complete quickly, with RAN_TO_COMPLETION status. Task task1 = Task.Delay(0); Task task2 = Task.Delay(new TimeSpan(0)); Task task3 = Task.Delay(0, token); Task task4 = Task.Delay(new TimeSpan(0), token); Debug.WriteLine("RunDelayTests: > Waiting for 0-delayed uncanceled tasks to complete. If we hang, something went wrong."); try { Task.WaitAll(task1, task2, task3, task4); } catch (Exception e) { Assert.True(false, string.Format("RunDelayTests: > FAILED. Unexpected exception on WaitAll(simple tasks): {0}", e)); } Assert.True(task1.Status == TaskStatus.RanToCompletion, " > FAILED. Expected Delay(0) to run to completion"); Assert.True(task2.Status == TaskStatus.RanToCompletion, " > FAILED. Expected Delay(TimeSpan(0)) to run to completion"); Assert.True(task3.Status == TaskStatus.RanToCompletion, " > FAILED. Expected Delay(0,uncanceledToken) to run to completion"); Assert.True(task4.Status == TaskStatus.RanToCompletion, " > FAILED. Expected Delay(TimeSpan(0),uncanceledToken) to run to completion"); // This should take some time Task task7 = Task.Delay(10000); Assert.False(task7.IsCompleted, "RunDelayTests: > FAILED. Delay(10000) appears to have completed too soon(1)."); Task t2 = Task.Delay(10); Assert.False(task7.IsCompleted, "RunDelayTests: > FAILED. Delay(10000) appears to have completed too soon(2)."); } [Fact] public static void RunDelayTests_NegativeCases() { CancellationTokenSource disposedCTS = new CancellationTokenSource(); CancellationToken disposedToken = disposedCTS.Token; disposedCTS.Dispose(); // // Test for exceptions // Assert.Throws<ArgumentOutOfRangeException>( () => { Task.Delay(-2); }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task.Delay(new TimeSpan(1000, 0, 0, 0)); }); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; cts.Cancel(); // These should complete quickly, in Canceled status Task task5 = Task.Delay(0, token); Task task6 = Task.Delay(new TimeSpan(0), token); Debug.WriteLine("RunDelayTests: > Waiting for 0-delayed canceled tasks to complete. If we hang, something went wrong."); try { Task.WaitAll(task5, task6); } catch { } Assert.True(task5.Status == TaskStatus.Canceled, "RunDelayTests: > FAILED. Expected Delay(0,canceledToken) to end up Canceled"); Assert.True(task6.Status == TaskStatus.Canceled, "RunDelayTests: > FAILED. Expected Delay(TimeSpan(0),canceledToken) to end up Canceled"); // Cancellation token on two tasks and waiting on a task a second time. CancellationTokenSource cts2 = new CancellationTokenSource(); Task task8 = Task.Delay(-1, cts2.Token); Task task9 = Task.Delay(new TimeSpan(1, 0, 0, 0), cts2.Token); Task.Factory.StartNew(() => { cts2.Cancel(); }); Debug.WriteLine("RunDelayTests: > Waiting for infinite-delayed, eventually-canceled tasks to complete. If we hang, something went wrong."); try { Task.WaitAll(task8, task9); } catch { } Assert.True(task8.IsCanceled, "RunDelayTests: > FAILED. Expected Delay(-1, token) to end up Canceled."); Assert.True(task9.IsCanceled, "RunDelayTests: > FAILED. Expected Delay(TimeSpan(1,0,0,0), token) to end up Canceled."); try { task8.Wait(); } catch (AggregateException ae) { Assert.True( ae.InnerException is OperationCanceledException && ((OperationCanceledException)ae.InnerException).CancellationToken == cts2.Token, "RunDelayTests: > FAILED. Expected resulting OCE to contain canceled token."); } } // Test that exceptions are properly wrapped when thrown in various scenarios. // Make sure that "indirect" logic does not add superfluous exception wrapping. [Fact] public static void RunExceptionWrappingTest() { Action throwException = delegate { throw new InvalidOperationException(); }; // // // Test Monadic ContinueWith() // // Action<Task, string> mcwExceptionChecker = delegate (Task mcwTask, string scenario) { try { mcwTask.Wait(); Assert.True(false, string.Format("RunExceptionWrappingTest: > FAILED. Wait-on-continuation did not throw for {0}", scenario)); } catch (Exception e) { int levels = NestedLevels(e); if (levels != 2) { Assert.True(false, string.Format("RunExceptionWrappingTest: > FAILED. Exception had {0} levels instead of 2 for {1}.", levels, scenario)); } } }; // Test mcw off of Task Task t = Task.Factory.StartNew(delegate { }); // Throw in the returned future Task<int> mcw1 = t.ContinueWith(delegate (Task antecedent) { Task<int> inner = Task<int>.Factory.StartNew(delegate { throw new InvalidOperationException(); }); return inner; }).Unwrap(); mcwExceptionChecker(mcw1, "Task antecedent, throw in ContinuationFunction"); // Throw in the continuationFunction Task<int> mcw2 = t.ContinueWith(delegate (Task antecedent) { throwException(); Task<int> inner = Task<int>.Factory.StartNew(delegate { return 0; }); return inner; }).Unwrap(); mcwExceptionChecker(mcw2, "Task antecedent, throw in returned Future"); // Test mcw off of future Task<int> f = Task<int>.Factory.StartNew(delegate { return 0; }); // Throw in the returned future mcw1 = f.ContinueWith(delegate (Task<int> antecedent) { Task<int> inner = Task<int>.Factory.StartNew(delegate { throw new InvalidOperationException(); }); return inner; }).Unwrap(); mcwExceptionChecker(mcw1, "Future antecedent, throw in ContinuationFunction"); // Throw in the continuationFunction mcw2 = f.ContinueWith(delegate (Task<int> antecedent) { throwException(); Task<int> inner = Task<int>.Factory.StartNew(delegate { return 0; }); return inner; }).Unwrap(); mcwExceptionChecker(mcw2, "Future antecedent, throw in returned Future"); // // // Test FromAsync() // // // Used to test APM-related functionality FakeAsyncClass fac = new FakeAsyncClass(); // Common logic for checking exception nesting Action<Task, string> AsyncExceptionChecker = delegate (Task _asyncTask, string msg) { try { _asyncTask.Wait(); Assert.True(false, string.Format("RunExceptionWrappingTest APM-Related Funct: > FAILED. {0} did not throw exception.", msg)); } catch (Exception e) { int levels = NestedLevels(e); if (levels != 2) { Assert.True(false, string.Format("RunExceptionWrappingTest APM-Related Funct: > FAILED. {0} exception had {1} levels instead of 2", msg, levels)); } } }; // Try Task.FromAsync(iar,...) Task asyncTask = Task.Factory.FromAsync(fac.StartWrite("1234567890", null, null), delegate (IAsyncResult iar) { throw new InvalidOperationException(); }); AsyncExceptionChecker(asyncTask, "Task-based FromAsync(iar, ...)"); // Try Task.FromAsync(beginMethod, endMethod, ...) asyncTask = Task.Factory.FromAsync(fac.StartWrite, delegate (IAsyncResult iar) { throw new InvalidOperationException(); }, "1234567890", null); AsyncExceptionChecker(asyncTask, "Task-based FromAsync(beginMethod, ...)"); // Try Task<string>.Factory.FromAsync(iar,...) Task<string> asyncFuture = Task<string>.Factory.FromAsync(fac.StartRead(10, null, null), delegate (IAsyncResult iar) { throwException(); return fac.EndRead(iar); }); AsyncExceptionChecker(asyncFuture, "Future-based FromAsync(iar, ...)"); asyncFuture = Task<string>.Factory.FromAsync(fac.StartRead, delegate (IAsyncResult iar) { throwException(); return fac.EndRead(iar); }, 10, null); AsyncExceptionChecker(asyncFuture, "Future-based FromAsync(beginMethod, ...)"); } [Fact] public static void RunHideSchedulerTests() { TaskScheduler[] schedules = new TaskScheduler[2]; schedules[0] = TaskScheduler.Default; for (int i = 0; i < schedules.Length; i++) { bool useCustomTs = (i == 1); TaskScheduler outerTs = schedules[i]; // useCustomTs ? customTs : TaskScheduler.Default; // If we are running CoreCLR, then schedules[1] = null, and we should continue in this case. if (i == 1 && outerTs == null) continue; for (int j = 0; j < 2; j++) { bool hideScheduler = (j == 0); TaskCreationOptions creationOptions = hideScheduler ? TaskCreationOptions.HideScheduler : TaskCreationOptions.None; TaskContinuationOptions continuationOptions = hideScheduler ? TaskContinuationOptions.HideScheduler : TaskContinuationOptions.None; TaskScheduler expectedInnerTs = hideScheduler ? TaskScheduler.Default : outerTs; Action<string> commonAction = delegate (string setting) { Assert.Equal(TaskScheduler.Current, expectedInnerTs); // And just for completeness, make sure that inner tasks are started on the correct scheduler TaskScheduler tsInner1 = null, tsInner2 = null; Task tInner = Task.Factory.StartNew(() => { tsInner1 = TaskScheduler.Current; }); Task continuation = tInner.ContinueWith(_ => { tsInner2 = TaskScheduler.Current; }); Task.WaitAll(tInner, continuation); Assert.Equal(tsInner1, expectedInnerTs); Assert.Equal(tsInner2, expectedInnerTs); }; Task outerTask = Task.Factory.StartNew(() => { commonAction("task"); }, CancellationToken.None, creationOptions, outerTs); Task outerContinuation = outerTask.ContinueWith(_ => { commonAction("continuation"); }, CancellationToken.None, continuationOptions, outerTs); Task.WaitAll(outerTask, outerContinuation); // Check that the option was internalized by the task/continuation Assert.True(hideScheduler == ((outerTask.CreationOptions & TaskCreationOptions.HideScheduler) != 0), "RunHideSchedulerTests: FAILED. CreationOptions mismatch on outerTask"); Assert.True(hideScheduler == ((outerContinuation.CreationOptions & TaskCreationOptions.HideScheduler) != 0), "RunHideSchedulerTests: FAILED. CreationOptions mismatch on outerContinuation"); } // end j-loop, for hideScheduler setting } // ending i-loop, for customTs setting } [Fact] public static void RunHideSchedulerTests_Negative() { // Test that HideScheduler is flagged as an illegal option when creating a TCS Assert.Throws<ArgumentOutOfRangeException>( () => { new TaskCompletionSource<int>(TaskCreationOptions.HideScheduler); }); } [Fact] public static void RunDenyChildAttachTests() { // StartNew, Task and Future Task i1 = null; Task t1 = Task.Factory.StartNew(() => { i1 = new Task(() => { }, TaskCreationOptions.AttachedToParent); }, TaskCreationOptions.DenyChildAttach); Task i2 = null; Task t2 = Task<int>.Factory.StartNew(() => { i2 = new Task(() => { }, TaskCreationOptions.AttachedToParent); return 42; }, TaskCreationOptions.DenyChildAttach); // ctor/Start, Task and Future Task i3 = null; Task t3 = new Task(() => { i3 = new Task(() => { }, TaskCreationOptions.AttachedToParent); }, TaskCreationOptions.DenyChildAttach); t3.Start(); Task i4 = null; Task t4 = new Task<int>(() => { i4 = new Task(() => { }, TaskCreationOptions.AttachedToParent); return 42; }, TaskCreationOptions.DenyChildAttach); t4.Start(); // continuations, Task and Future Task i5 = null; Task t5 = t3.ContinueWith(_ => { i5 = new Task(() => { }, TaskCreationOptions.AttachedToParent); }, TaskContinuationOptions.DenyChildAttach); Task i6 = null; Task t6 = t4.ContinueWith<int>(_ => { i6 = new Task(() => { }, TaskCreationOptions.AttachedToParent); return 42; }, TaskContinuationOptions.DenyChildAttach); // If DenyChildAttach doesn't work in any of the cases, then the associated "parent" // task will hang waiting for its child. Debug.WriteLine("RunDenyChildAttachTests: Waiting on 'parents' ... if we hang, something went wrong."); Task.WaitAll(t1, t2, t3, t4, t5, t6); // And clean up. i1.Start(); i1.Wait(); i2.Start(); i2.Wait(); i3.Start(); i3.Wait(); i4.Start(); i4.Wait(); i5.Start(); i5.Wait(); i6.Start(); i6.Wait(); } [Fact] public static void RunBasicFutureTest_Negative() { Task<int> future = new Task<int>(() => 1); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith((Action<Task<int>, Object>)null, null, CancellationToken.None)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith((Action<Task<int>, Object>)null, null, TaskContinuationOptions.None)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith((Action<Task<int>, Object>)null, null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith((t, s) => { }, null, CancellationToken.None, TaskContinuationOptions.None, null)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith<int>((Func<Task<int>, Object, int>)null, null, CancellationToken.None)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith<int>((Func<Task<int>, Object, int>)null, null, TaskContinuationOptions.None)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith<int>((Func<Task<int>, Object, int>)null, null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith<int>((t, s) => 2, null, CancellationToken.None, TaskContinuationOptions.None, null)); } #region Helper Methods / Classes private static int NestedLevels(Exception e) { int levels = 0; while (e != null) { levels++; AggregateException ae = e as AggregateException; if (ae != null) { e = ae.InnerExceptions[0]; } else break; } return levels; } internal enum UnwrappedScenario { CleanRun = 0, ThrowExceptionInDelegate = 1, ThrowOceInDelegate = 2, ThrowExceptionInTask = 3, ThrowTargetOceInTask = 4, ThrowOtherOceInTask = 5 }; // This class is used in testing APM Factory tests. private class FakeAsyncClass { private List<char> _list = new List<char>(); public override string ToString() { StringBuilder sb = new StringBuilder(); lock (_list) { for (int i = 0; i < _list.Count; i++) sb.Append(_list[i]); } return sb.ToString(); } // Silly use of Write, but I wanted to test no-argument StartXXX handling. public IAsyncResult StartWrite(AsyncCallback cb, object o) { return StartWrite("", 0, 0, cb, o); } public IAsyncResult StartWrite(string s, AsyncCallback cb, object o) { return StartWrite(s, 0, s.Length, cb, o); } public IAsyncResult StartWrite(string s, int length, AsyncCallback cb, object o) { return StartWrite(s, 0, length, cb, o); } public IAsyncResult StartWrite(string s, int offset, int length, AsyncCallback cb, object o) { myAsyncResult mar = new myAsyncResult(cb, o); // Allow for exception throwing to test our handling of that. if (s == null) throw new ArgumentNullException(nameof(s)); Task t = Task.Factory.StartNew(delegate { //Thread.Sleep(100); try { lock (_list) { for (int i = 0; i < length; i++) _list.Add(s[i + offset]); } mar.Signal(); } catch (Exception e) { mar.Signal(e); } }); return mar; } public void EndWrite(IAsyncResult iar) { myAsyncResult mar = iar as myAsyncResult; mar.Wait(); if (mar.IsFaulted) throw (mar.Exception); } public IAsyncResult StartRead(AsyncCallback cb, object o) { return StartRead(128 /*=maxbytes*/, null, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, AsyncCallback cb, object o) { return StartRead(maxBytes, null, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, char[] buf, AsyncCallback cb, object o) { return StartRead(maxBytes, buf, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, char[] buf, int offset, AsyncCallback cb, object o) { myAsyncResult mar = new myAsyncResult(cb, o); // Allow for exception throwing to test our handling of that. if (maxBytes == -1) throw new ArgumentException(nameof(maxBytes)); Task t = Task.Factory.StartNew(delegate { //Thread.Sleep(100); StringBuilder sb = new StringBuilder(); int bytesRead = 0; try { lock (_list) { while ((_list.Count > 0) && (bytesRead < maxBytes)) { sb.Append(_list[0]); if (buf != null) { buf[offset] = _list[0]; offset++; } _list.RemoveAt(0); bytesRead++; } } mar.SignalState(sb.ToString()); } catch (Exception e) { mar.Signal(e); } }); return mar; } public string EndRead(IAsyncResult iar) { myAsyncResult mar = iar as myAsyncResult; if (mar.IsFaulted) throw (mar.Exception); return (string)mar.AsyncState; } public void ResetStateTo(string s) { _list.Clear(); for (int i = 0; i < s.Length; i++) _list.Add(s[i]); } } // This is an internal class used for a concrete IAsyncResult in the APM Factory tests. private class myAsyncResult : IAsyncResult { private volatile int _isCompleted; private ManualResetEvent _asyncWaitHandle; private AsyncCallback _callback; private object _asyncState; private Exception _exception; public myAsyncResult(AsyncCallback cb, object o) { _isCompleted = 0; _asyncWaitHandle = new ManualResetEvent(false); _callback = cb; _asyncState = o; _exception = null; } public bool IsCompleted { get { return (_isCompleted == 1); } } public bool CompletedSynchronously { get { return false; } } public WaitHandle AsyncWaitHandle { get { return _asyncWaitHandle; } } public object AsyncState { get { return _asyncState; } } public void Signal() { _isCompleted = 1; _asyncWaitHandle.Set(); if (_callback != null) _callback(this); } public void Signal(Exception e) { _exception = e; Signal(); } public void SignalState(object o) { _asyncState = o; Signal(); } public void Wait() { _asyncWaitHandle.WaitOne(); if (_exception != null) throw (_exception); } public bool IsFaulted { get { return ((_isCompleted == 1) && (_exception != null)); } } public Exception Exception { get { return _exception; } } } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using NUnit.Framework; using SIL.Data; using SIL.DictionaryServices.Model; using SIL.IO; using SIL.TestUtilities; using SIL.WritingSystems; namespace SIL.DictionaryServices.Tests { [TestFixture] [OfflineSldr] public class LiftLexEntryRepositoryCachingTests { private TemporaryFolder _tempfolder; private TempFile _tempFile; private LiftLexEntryRepository _repository; [SetUp] public void Setup() { _tempfolder = new TemporaryFolder("LiftLexEntryRepositoryCachingTests"); _tempFile = _tempfolder.GetNewTempFile(true); _repository = new LiftLexEntryRepository(_tempFile.Path); } [TearDown] public void Teardown() { _repository.Dispose(); _tempFile.Dispose(); _tempfolder.Dispose(); } [Test] public void GetAllEntriesSortedByHeadWord_CreateItemAfterFirstCall_EntryIsReturnedAndSortedInResultSet() { CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 1"); _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.CreateItem(); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(2, results.Count); Assert.AreEqual(null, results[0]["Form"]); Assert.AreEqual("word 1", results[1]["Form"]); } private LexEntry CreateEntryWithLexicalFormBeforeFirstQuery(string writingSystem, string lexicalForm) { LexEntry entryBeforeFirstQuery = _repository.CreateItem(); entryBeforeFirstQuery.LexicalForm.SetAlternative(writingSystem, lexicalForm); _repository.SaveItem(entryBeforeFirstQuery); return entryBeforeFirstQuery; } private static WritingSystemDefinition WritingSystemDefinitionForTest(string languageIso, Font font) { return new WritingSystemDefinition { Language = languageIso, DefaultFont = new FontDefinition(font.Name), DefaultFontSize = font.Size, DefaultCollation = new IcuRulesCollationDefinition("standard") }; } [Test] public void GetAllEntriesSortedByHeadWord_ModifyAndSaveAfterFirstCall_EntryIsModifiedAndSortedInResultSet() { LexEntry entryBeforeFirstQuery = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); entryBeforeFirstQuery.LexicalForm.SetAlternative("de", "word 1"); _repository.SaveItem(entryBeforeFirstQuery); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(1, results.Count); Assert.AreEqual("word 1", results[0]["Form"]); } [Test] public void GetAllEntriesSortedByHeadWord_ModifyAndSaveMultipleAfterFirstCall_EntriesModifiedAndSortedInResultSet() { List<LexEntry> entriesToModify = new List<LexEntry>(); entriesToModify.Add(CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0")); entriesToModify.Add(CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 1")); _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); entriesToModify[0].LexicalForm["de"] = "word 3"; entriesToModify[1].LexicalForm["de"] = "word 2"; _repository.SaveItems(entriesToModify); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(2, results.Count); Assert.AreEqual("word 2", results[0]["Form"]); Assert.AreEqual("word 3", results[1]["Form"]); } [Test] public void GetAllEntriesSortedByHeadWord_DeleteAfterFirstCall_EntryIsDeletedInResultSet() { LexEntry entrytoBeDeleted = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteItem(entrytoBeDeleted); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } [Test] public void GetAllEntriesSortedByHeadWord_DeleteByIdAfterFirstCall_EntryIsDeletedInResultSet() { LexEntry entrytoBeDeleted = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteItem(_repository.GetId(entrytoBeDeleted)); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } [Test] public void GetAllEntriesSortedByHeadWord_DeleteAllItemsAfterFirstCall_EntryIsDeletedInResultSet() { CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteAllItems(); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } [Test] public void GetAllEntriesSortedByLexicalForm_CreateItemAfterFirstCall_EntryIsReturnedAndSortedInResultSet() { CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 1"); _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.CreateItem(); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(2, results.Count); Assert.AreEqual(null, results[0]["Form"]); Assert.AreEqual("word 1", results[1]["Form"]); } [Test] public void GetAllEntriesSortedByLexicalForm_ModifyAndSaveAfterFirstCall_EntryIsModifiedAndSortedInResultSet() { LexEntry entryBeforeFirstQuery = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); entryBeforeFirstQuery.LexicalForm.SetAlternative("de", "word 1"); _repository.SaveItem(entryBeforeFirstQuery); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(1, results.Count); Assert.AreEqual("word 1", results[0]["Form"]); } [Test] public void GetAllEntriesSortedByLexicalForm_ModifyAndSaveMultipleAfterFirstCall_EntriesModifiedAndSortedInResultSet() { var entriesToModify = new List<LexEntry>(); entriesToModify.Add(CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0")); entriesToModify.Add(CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 1")); _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); entriesToModify[0].LexicalForm["de"] = "word 3"; entriesToModify[1].LexicalForm["de"] = "word 2"; _repository.SaveItems(entriesToModify); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(2, results.Count); Assert.AreEqual("word 2", results[0]["Form"]); Assert.AreEqual("word 3", results[1]["Form"]); } [Test] public void GetAllEntriesSortedByLexicalForm_DeleteAfterFirstCall_EntryIsDeletedInResultSet() { LexEntry entrytoBeDeleted = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteItem(entrytoBeDeleted); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } [Test] public void GetAllEntriesSortedByLexicalForm_DeleteByIdAfterFirstCall_EntryIsDeletedInResultSet() { LexEntry entrytoBeDeleted = CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteItem(_repository.GetId(entrytoBeDeleted)); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } [Test] public void GetAllEntriesSortedByLexicalForm_DeleteAllItemsAfterFirstCall_EntryIsDeletedInResultSet() { CreateEntryWithLexicalFormBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteAllItems(); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } [Test] public void NotifyThatLexEntryHasBeenUpdated_LexEntry_CachesAreUpdated() { LexEntry entryToUpdate = _repository.CreateItem(); entryToUpdate.LexicalForm.SetAlternative("de", "word 0"); _repository.SaveItem(entryToUpdate); CreateCaches(); entryToUpdate.LexicalForm.SetAlternative("de", "word 1"); _repository.NotifyThatLexEntryHasBeenUpdated(entryToUpdate); var writingSystemToMatch = WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont); ResultSet<LexEntry> headWordResults = _repository.GetAllEntriesSortedByHeadword(writingSystemToMatch); ResultSet<LexEntry> lexicalFormResults = _repository.GetAllEntriesSortedByLexicalFormOrAlternative(writingSystemToMatch); Assert.AreEqual("word 1", headWordResults[0]["Form"]); Assert.AreEqual("word 1", lexicalFormResults[0]["Form"]); } private void CreateCaches() { var writingSystemToMatch = WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont); _repository.GetAllEntriesSortedByHeadword(writingSystemToMatch); _repository.GetAllEntriesSortedByLexicalFormOrAlternative(writingSystemToMatch); //_repository.GetAllEntriesSortedByDefinitionOrGloss(writingSystemToMatch); } [Test] public void NotifyThatLexEntryHasBeenUpdated_Null_Throws() { Assert.Throws<ArgumentNullException>(() => _repository.NotifyThatLexEntryHasBeenUpdated(null)); } [Test] public void NotifyThatLexEntryHasBeenUpdated_LexEntryDoesNotExistInRepository_Throws() { var entryToUpdate = new LexEntry(); Assert.Throws<ArgumentOutOfRangeException>(() => _repository.NotifyThatLexEntryHasBeenUpdated(entryToUpdate)); } private LexEntry CreateEntryWithDefinitionBeforeFirstQuery(string writingSystem, string lexicalForm) { LexEntry entryBeforeFirstQuery = _repository.CreateItem(); entryBeforeFirstQuery.Senses.Add(new LexSense()); entryBeforeFirstQuery.Senses[0].Definition.SetAlternative(writingSystem, lexicalForm); _repository.SaveItem(entryBeforeFirstQuery); return entryBeforeFirstQuery; } [Test] public void GetAllEntriesSortedByDefinition_CreateItemAfterFirstCall_EntryIsReturnedAndSortedInResultSet() { CreateEntryWithDefinitionBeforeFirstQuery("de", "word 1"); _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); CreateEntryWithDefinitionBeforeFirstQuery("de", "word 2"); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(2, results.Count); Assert.AreEqual("word 1", results[0]["Form"]); Assert.AreEqual("word 2", results[1]["Form"]); } [Test] public void GetAllEntriesSortedByDefinition_ModifyAndSaveAfterFirstCall_EntryIsModifiedAndSortedInResultSet() { LexEntry entryBeforeFirstQuery = CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); entryBeforeFirstQuery.Senses[0].Definition.SetAlternative("de", "word 1"); _repository.SaveItem(entryBeforeFirstQuery); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(1, results.Count); Assert.AreEqual("word 1", results[0]["Form"]); } [Test] public void GetAllEntriesSortedByDefinition_ModifyAndSaveMultipleAfterFirstCall_EntriesModifiedAndSortedInResultSet() { List<LexEntry> entriesToModify = new List<LexEntry>(); entriesToModify.Add(CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0")); entriesToModify.Add(CreateEntryWithDefinitionBeforeFirstQuery("de", "word 1")); _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); entriesToModify[0].Senses[0].Definition["de"] = "word 3"; entriesToModify[1].Senses[0].Definition["de"] = "word 2"; _repository.SaveItems(entriesToModify); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(2, results.Count); Assert.AreEqual("word 2", results[0]["Form"]); Assert.AreEqual("word 3", results[1]["Form"]); } [Test] public void GetAllEntriesSortedByDefinition_DeleteAfterFirstCall_EntryIsDeletedInResultSet() { LexEntry entrytoBeDeleted = CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteItem(entrytoBeDeleted); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } [Test] public void GetAllEntriesSortedByDefinition_DeleteByIdAfterFirstCall_EntryIsDeletedInResultSet() { LexEntry entrytoBeDeleted = CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteItem(_repository.GetId(entrytoBeDeleted)); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } [Test] public void GetAllEntriesSortedByDefinition_DeleteAllItemsAfterFirstCall_EntryIsDeletedInResultSet() { CreateEntryWithDefinitionBeforeFirstQuery("de", "word 0"); _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); _repository.DeleteAllItems(); ResultSet<LexEntry> results = _repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest("de", SystemFonts.DefaultFont)); Assert.AreEqual(0, results.Count); } } }
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; using System; public class BranchAndroidWrapper { #if UNITY_ANDROID public static void setBranchKey(String branchKey) { _runBlockOnThread(() => { _getBranchClass().CallStatic("setBranchKey", branchKey); }); } public static void getAutoInstance() { _runBlockOnThread(() => { _getBranchClass().CallStatic("getAutoInstance"); }); } #region InitSession methods public static void initSession() { _runBlockOnThread(() => { _getBranchClass().CallStatic("initSession"); }); } public static void initSessionAsReferrable(bool isReferrable) { _runBlockOnThread(() => { _getBranchClass().CallStatic("initSession", isReferrable); }); } public static void initSessionWithCallback(string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("initSession", callbackId); }); } public static void initSessionAsReferrableWithCallback(bool isReferrable, string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("initSession", callbackId, isReferrable); }); } public static void initSessionWithUniversalObjectCallback(string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("initSessionWithUniversalObjectCallback", callbackId); }); } #endregion #region Session Item methods public static string getFirstReferringBranchUniversalObject() { return _getBranchClass().CallStatic<string>("getFirstReferringBranchUniversalObject"); } public static string getFirstReferringBranchLinkProperties() { return _getBranchClass().CallStatic<string>("getFirstReferringBranchLinkProperties"); } public static string getLatestReferringBranchUniversalObject() { return _getBranchClass().CallStatic<string>("getLatestReferringBranchUniversalObject"); } public static string getLatestReferringBranchLinkProperties() { return _getBranchClass().CallStatic<string>("getLatestReferringBranchLinkProperties"); } public static void resetUserSession() { _runBlockOnThread(() => { _getBranchClass().CallStatic("resetUserSession"); }); } public static void setIdentity(string userId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("setIdentity", userId); }); } public static void setIdentityWithCallback(string userId, string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("setIdentity", userId, callbackId); }); } public static void logout() { _runBlockOnThread(() => { _getBranchClass().CallStatic("logout"); }); } #endregion #region Configuration methods public static void setDebug() { _runBlockOnThread(() => { _getBranchClass().CallStatic("setDebug"); }); } public static void setRetryInterval(int retryInterval) { _runBlockOnThread(() => { _getBranchClass().CallStatic("setRetryInterval", retryInterval); }); } public static void setMaxRetries(int maxRetries) { _runBlockOnThread(() => { _getBranchClass().CallStatic("setMaxRetries", maxRetries); }); } public static void setNetworkTimeout(int timeout) { _runBlockOnThread(() => { _getBranchClass().CallStatic("setNetworkTimeout", timeout); }); } public static void registerView(string universalObject) { _runBlockOnThread(() => { _getBranchClass().CallStatic("registerView", universalObject); }); } public static void listOnSpotlight(string universalObject) { _runBlockOnThread(() => { _getBranchClass().CallStatic("listOnSpotlight", universalObject); }); } public static void accountForFacebookSDKPreventingAppLaunch() { _runBlockOnThread(() => { _getBranchClass().CallStatic("accountForFacebookSDKPreventingAppLaunch"); }); } public static void setRequestMetadata(string key, string val) { _runBlockOnThread(() => { _getBranchClass().CallStatic("setRequestMetadata", key, val); }); } public static void setTrackingDisabled(bool value) { _runBlockOnThread(() => { _getBranchClass().CallStatic("setTrackingDisabled", value); }); } #endregion #region User Action methods public static void userCompletedAction(string action) { _runBlockOnThread(() => { _getBranchClass().CallStatic("userCompletedAction", action); }); } public static void userCompletedActionWithState(string action, string stateDict) { _runBlockOnThread(() => { _getBranchClass().CallStatic("userCompletedAction", action, stateDict); }); } public static void sendEvent(string eventName) { _runBlockOnThread(() => { _getBranchClass().CallStatic("sendEvent", eventName); }); } #endregion #region Credit methods public static void loadRewardsWithCallback(string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("loadRewards", callbackId); }); } public static int getCredits() { return _getBranchClass().CallStatic<int>("getCredits"); } public static void redeemRewards(int count) { _runBlockOnThread(() => { _getBranchClass().CallStatic("redeemRewards", count); }); } public static int getCreditsForBucket(string bucket) { return _getBranchClass().CallStatic<int>("getCreditsForBucket", bucket); } public static void redeemRewardsForBucket(int count, string bucket) { _runBlockOnThread(() => { _getBranchClass().CallStatic("redeemRewards", bucket, count); }); } public static void getCreditHistoryWithCallback(string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("getCreditHistory", callbackId); }); } public static void getCreditHistoryForBucketWithCallback(string bucket, string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("getCreditHistory", bucket, callbackId); }); } public static void getCreditHistoryForTransactionWithLengthOrderAndCallback(string creditTransactionId, int length, int order, string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("getCreditHistory", creditTransactionId, length, order, callbackId); }); } public static void getCreditHistoryForBucketWithTransactionLengthOrderAndCallback(string bucket, string creditTransactionId, int length, int order, string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("getCreditHistory", bucket, creditTransactionId, length, order, callbackId); }); } #endregion #region Share Link methods public static void shareLinkWithLinkProperties(string universalObject, string linkProperties, string message, string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("shareLinkWithLinkProperties", universalObject, linkProperties, message, callbackId); }); } #endregion #region Short URL Generation methods public static void getShortURLWithBranchUniversalObjectAndCallback(string universalObject, string linkProperties, string callbackId) { _runBlockOnThread(() => { _getBranchClass().CallStatic("getShortURLWithBranchUniversalObject", universalObject, linkProperties, callbackId); }); } #endregion #region Utility methods private static AndroidJavaClass _getBranchClass() { if (_branchClass == null) { _branchClass = new AndroidJavaClass("io/branch/unity/BranchUnityWrapper"); } return _branchClass; } private static void _runBlockOnThread(Action runBlock) { var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); var activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); activity.Call("runOnUiThread", new AndroidJavaRunnable(runBlock)); } #endregion private static AndroidJavaClass _branchClass; #endif }
using System.Collections; using System.Collections.Generic; using GameAPI; using GameAPI.BudgetBoy; using MiniJSON; namespace Games.RohBot { public class LoginStage : Stage { enum LoginState { EnterUsername, EnterPassword, LoginSent, LoginSuccess, LoginFailed } private Main _game; private Text _title; private Text _label; private Text _input; private VirtualKeyboard _keyboard; private string _keyboardStr; private LoginState _state; private string _username; private string _password; private WebSocket Socket { get { return _game.Socket; } set { _game.Socket = value; } } public LoginStage(Main game) : base(game) { _game = game; var font = Graphics.GetImage("Resources", "font"); var color = _game.Swatches.White; _title = Add(new Text(font, color), 0); _title.Value = "RohBot"; _title.Position = (Graphics.Size / 2) - (_title.Size / 2) + new Vector2i(0, 64); _label = Add(new Text(font, color), 0); _input = Add(new Text(font, color), 0); _keyboard = Add(new VirtualKeyboard(font, color), 0); _keyboard.Position = new Vector2i((Graphics.Size.X / 2) - (_keyboard.Width / 2), 16); _keyboard.Pressed += KeyboardPressed; Socket.MessageReceived = message => { var obj = (Dictionary<string, object>)Json.Deserialize(message); var type = (string)obj["Type"]; if (type == "authResponse") { _username = (string)obj["Name"]; var success = (bool)obj["Success"]; ChangeState(success ? LoginState.LoginSuccess : LoginState.LoginFailed); } }; /*_username = "Arcade"; ChangeState(LoginState.EnterPassword); _keyboardStr = "password";*/ ChangeState(LoginState.EnterUsername); OnUpdate(); // workaround for flicker on the first frame } private void KeyboardPressed(char ch) { if (ch == '\b') { if (_keyboardStr.Length == 0) return; _keyboardStr = _keyboardStr.Substring(0, _keyboardStr.Length - 1); return; } if (ch == '\r') { if (string.IsNullOrEmpty(_keyboardStr)) return; switch (_state) { case LoginState.EnterUsername: _username = _keyboardStr; ChangeState(LoginState.EnterPassword); break; case LoginState.EnterPassword: _password = _keyboardStr; Socket.Send(Json.Serialize(new Dictionary<string, object> { { "Type", "auth" }, { "Method", "login" }, { "Username", _username }, { "Password", _password } })); ChangeState(LoginState.LoginSent); break; } _keyboardStr = ""; return; } _keyboardStr += ch; } private void ChangeState(LoginState newState) { _input.IsVisible = false; _keyboard.IsVisible = false; _keyboard.IsActive = false; _keyboardStr = ""; switch (newState) { case LoginState.EnterUsername: _label.Value = "Username:"; _input.IsVisible = true; _keyboard.IsVisible = true; _keyboard.IsActive = true; _keyboardStr = ""; break; case LoginState.EnterPassword: _label.Value = "Password:"; _input.IsVisible = true; _keyboard.IsVisible = true; _keyboard.IsActive = true; _keyboardStr = ""; break; case LoginState.LoginSent: _label.Value = "Logging in..."; break; case LoginState.LoginSuccess: _label.Value = string.Format("Logged in as {0}!", _username); StartCoroutine(LoginSuccessCoroutine); break; case LoginState.LoginFailed: _label.Value = "Login failed!"; StartCoroutine(LoginFailedCoroutine); break; } _state = newState; } protected override void OnUpdate() { base.OnUpdate(); Dispatcher.RunAll(); switch (_state) { case LoginState.EnterUsername: case LoginState.EnterPassword: _input.Value = _keyboardStr; _input.Position = (Graphics.Size / 2) - new Vector2i(_input.Size.X / 2, 0); _label.Position = (Graphics.Size / 2) + new Vector2i(-_label.Size.X, 16); break; case LoginState.LoginSent: case LoginState.LoginSuccess: case LoginState.LoginFailed: _label.Position = (Graphics.Size / 2) - (_label.Size / 2); break; } } protected override void OnEnter() { Debug.Log("LoginStage entered"); Graphics.SetClearColor(_game.Swatches.ClearColor); } private IEnumerator LoginSuccessCoroutine() { yield return Delay(1); _game.SetStage(new ChatStage(_game)); } private IEnumerator LoginFailedCoroutine() { yield return Delay(2); _game.SetStage(new LoginStage(_game)); } } }
#if !NETCOREAPP using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Orleans; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Providers.Streams.AzureQueue; using Orleans.Runtime; using Orleans.TestingHost; using Tester; using Tester.AzureUtils.Streaming; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; using Xunit.Abstractions; using Orleans.Internal; using Tester.AzureUtils; namespace UnitTests.StreamingTests { [TestCategory("Streaming"), TestCategory("Cleanup")] public class StreamLifecycleTests : TestClusterPerTest { public const string AzureQueueStreamProviderName = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME; public const string SmsStreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; protected Guid StreamId; protected string StreamProviderName; protected string StreamNamespace; private readonly ITestOutputHelper output; private IActivateDeactivateWatcherGrain watcher; private const int queueCount = 8; protected override void ConfigureTestCluster(TestClusterBuilder builder) { TestUtils.CheckForAzureStorage(); builder.CreateSiloAsync = AppDomainSiloHandle.Create; builder.AddSiloBuilderConfigurator<MySiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<MyClientBuilderConfigurator>(); } private class MyClientBuilderConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder .AddSimpleMessageStreamProvider(SmsStreamProviderName) .AddAzureQueueStreams(AzureQueueStreamProviderName, ob=>ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConfigureTestDefaults(); options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount); })); } } private class MySiloBuilderConfigurator : ISiloConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder .AddSimpleMessageStreamProvider(SmsStreamProviderName) .AddSimpleMessageStreamProvider("SMSProviderDoNotOptimizeForImmutableData", options => options.OptimizeForImmutableData = false) .AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConfigureTestDefaults(); options.DeleteStateOnClear = true; })) .AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.DeleteStateOnClear = true; options.ConfigureTestDefaults(); })) .AddAzureQueueStreams(AzureQueueStreamProviderName, ob=>ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConfigureTestDefaults(); options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount); })) .AddAzureQueueStreams("AzureQueueProvider2", ob=>ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConfigureTestDefaults(); options.QueueNames = AzureQueueUtilities.GenerateQueueNames($"{dep.Value.ClusterId}2", queueCount); })) .AddMemoryGrainStorage("MemoryStore", options => options.NumStorageGrains = 1); } } public StreamLifecycleTests(ITestOutputHelper output) { this.output = output; } public override async Task InitializeAsync() { await base.InitializeAsync(); this.watcher = this.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0); StreamId = Guid.NewGuid(); StreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; StreamNamespace = StreamTestsConstants.StreamLifecycleTestsNamespace; } public override async Task DisposeAsync() { try { await watcher.Clear().WithTimeout(TimeSpan.FromSeconds(15)); } finally { await base.DisposeAsync(); } if (!string.IsNullOrWhiteSpace(TestDefaultConfiguration.DataConnectionString)) { await AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames(this.HostedCluster.Options.ClusterId, queueCount), new AzureQueueOptions().ConfigureTestDefaults()); await AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames($"{this.HostedCluster.Options.ClusterId}2", queueCount), new AzureQueueOptions().ConfigureTestDefaults()); } } [SkippableFact, TestCategory("Functional")] public async Task StreamCleanup_Deactivate() { await DoStreamCleanupTest_Deactivate(false, false); } [SkippableFact, TestCategory("Functional")] public async Task StreamCleanup_BadDeactivate() { await DoStreamCleanupTest_Deactivate(true, false); } [SkippableFact, TestCategory("Functional")] public async Task StreamCleanup_UseAfter_Deactivate() { await DoStreamCleanupTest_Deactivate(false, true); } [SkippableFact, TestCategory("Functional")] public async Task StreamCleanup_UseAfter_BadDeactivate() { await DoStreamCleanupTest_Deactivate(true, true); } [SkippableFact, TestCategory("Functional")] public async Task Stream_Lifecycle_AddRemoveProducers() { string testName = "Stream_Lifecycle_AddRemoveProducers"; StreamTestUtils.LogStartTest(testName, StreamId, StreamProviderName, logger, HostedCluster); int numProducers = 10; var consumer = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid()); await consumer.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName); var producers = new IStreamLifecycleProducerInternalGrain[numProducers]; for (int i = 1; i <= producers.Length; i++) { var producer = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid()); producers[i - 1] = producer; } int expectedReceived = 0; string when = "round 1"; await IncrementalAddProducers(producers, when); expectedReceived += numProducers; Assert.Equal(expectedReceived, await consumer.GetReceivedCount()); for (int i = producers.Length; i > 0; i--) { var producer = producers[i - 1]; // Force Remove await producer.TestInternalRemoveProducer(StreamId, StreamProviderName); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "producer #" + i + " remove", (i - 1), 1, StreamId, StreamProviderName, StreamNamespace); } when = "round 2"; await IncrementalAddProducers(producers, when); expectedReceived += numProducers; Assert.Equal(expectedReceived, await consumer.GetReceivedCount()); List<Task> promises = new List<Task>(); for (int i = producers.Length; i > 0; i--) { var producer = producers[i - 1]; // Remove when Deactivate promises.Add(producer.DoDeactivateNoClose()); } await Task.WhenAll(promises); await WaitForDeactivation(); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "all producers deactivated", 0, 1, StreamId, StreamProviderName, StreamNamespace); when = "round 3"; await IncrementalAddProducers(producers, when); expectedReceived += numProducers; Assert.Equal(expectedReceived, await consumer.GetReceivedCount()); } private async Task IncrementalAddProducers(IStreamLifecycleProducerGrain[] producers, string when) { for (int i = 1; i <= producers.Length; i++) { var producer = producers[i - 1]; await producer.BecomeProducer(StreamId, StreamNamespace, StreamProviderName); // These Producers test grains always send first message when they register await StreamTestUtils.CheckPubSubCounts( this.InternalClient, output, string.Format("producer #{0} create - {1}", i, when), i, 1, StreamId, StreamProviderName, StreamNamespace); } } // ---------- Test support methods ---------- private async Task DoStreamCleanupTest_Deactivate(bool uncleanShutdown, bool useStreamAfterDeactivate, [CallerMemberName]string testName = null) { StreamTestUtils.LogStartTest(testName, StreamId, StreamProviderName, logger, HostedCluster); var producer1 = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid()); var producer2 = this.GrainFactory.GetGrain<IStreamLifecycleProducerInternalGrain>(Guid.NewGuid()); var consumer1 = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid()); var consumer2 = this.GrainFactory.GetGrain<IStreamLifecycleConsumerInternalGrain>(Guid.NewGuid()); await consumer1.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName); await producer1.BecomeProducer(StreamId, StreamNamespace, StreamProviderName); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after first producer added", 1, 1, StreamId, StreamProviderName, StreamNamespace); Assert.Equal(1, await producer1.GetSendCount()); // "SendCount after first send" var activations = await watcher.GetActivateCalls(); var deactivations = await watcher.GetDeactivateCalls(); Assert.Equal(2, activations.Length); Assert.Empty(deactivations); int expectedNumProducers; if (uncleanShutdown) { expectedNumProducers = 1; // Will not cleanup yet await producer1.DoBadDeactivateNoClose(); } else { expectedNumProducers = 0; // Should immediately cleanup on Deactivate await producer1.DoDeactivateNoClose(); } await WaitForDeactivation(); deactivations = await watcher.GetDeactivateCalls(); Assert.Single(deactivations); // Test grains that did unclean shutdown will not have cleaned up yet, so PubSub counts are unchanged here for them await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after deactivate first producer", expectedNumProducers, 1, StreamId, StreamProviderName, StreamNamespace); // Add another consumer - which forces cleanup of dead producers and PubSub counts should now always be correct await consumer2.BecomeConsumer(StreamId, StreamNamespace, StreamProviderName); // Runtime should have cleaned up after next consumer added await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after add second consumer", 0, 2, StreamId, StreamProviderName, StreamNamespace); if (useStreamAfterDeactivate) { // Add new producer await producer2.BecomeProducer(StreamId, StreamNamespace, StreamProviderName); // These Producer test grains always send first message when they BecomeProducer, so should be registered with PubSub await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after add second producer", 1, 2, StreamId, StreamProviderName, StreamNamespace); Assert.Equal(1, await producer1.GetSendCount()); // "SendCount (Producer#1) after second publisher added"); Assert.Equal(1, await producer2.GetSendCount()); // "SendCount (Producer#2) after second publisher added"); Assert.Equal(2, await consumer1.GetReceivedCount()); // "ReceivedCount (Consumer#1) after second publisher added"); Assert.Equal(1, await consumer2.GetReceivedCount()); // "ReceivedCount (Consumer#2) after second publisher added"); await producer2.SendItem(3); await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, "after second producer send", 1, 2, StreamId, StreamProviderName, StreamNamespace); Assert.Equal(3, await consumer1.GetReceivedCount()); // "ReceivedCount (Consumer#1) after second publisher send"); Assert.Equal(2, await consumer2.GetReceivedCount()); // "ReceivedCount (Consumer#2) after second publisher send"); } StreamTestUtils.LogEndTest(testName, logger); } private async Task WaitForDeactivation() { var delay = TimeSpan.FromSeconds(1); logger.Info("Waiting for {0} to allow time for grain deactivation to occur", delay); await Task.Delay(delay); // Allow time for Deactivate logger.Info("Awake again."); } } } #endif
// // Authorization.cs: // // Authors: Miguel de Icaza // // Copyright 2012 Xamarin 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 MonoMac.ObjCRuntime; using MonoMac.Foundation; using System; using System.Runtime.InteropServices; namespace MonoMac.Security { public enum AuthorizationStatus { Success = 0, InvalidSet = -60001, InvalidRef = -60002, InvalidTag = -60003, InvalidPointer = -60004, Denied = -60005, Canceled = -60006, InteractionNotAllowed = -60007, Internal = -60008, ExternalizeNotAllowed = -60009, InternalizeNotAllowed = -60010, InvalidFlags = -60011, ToolExecuteFailure = -60031, ToolEnvironmentError = -60032, BadAddress = -60033, } [Flags] public enum AuthorizationFlags { Defaults, InteractionAllowed = 1 << 0, ExtendRights = 1 << 1, PartialRights = 1 << 2, DestroyRights = 1 << 3, PreAuthorize = 1 << 4, } // // For ease of use, we let the user pass the AuthorizationParameters, and we // create the structure for them with the proper data // public class AuthorizationParameters { public string PathToSystemPrivilegeTool; public string Prompt; public string IconPath; } public class AuthorizationEnvironment { public string Username; public string Password; public bool AddToSharedCredentialPool; } [StructLayout (LayoutKind.Sequential)] struct AuthorizationItem { public IntPtr name; public IntPtr valueLen; public IntPtr value; public int flags; // zero } unsafe struct AuthorizationItemSet { public int count; public AuthorizationItem *ptrToAuthorization; } public unsafe class Authorization : INativeObject, IDisposable { IntPtr handle; public IntPtr Handle { get { return handle; } } [DllImport (Constants.SecurityLibrary)] extern static int AuthorizationCreate (AuthorizationItemSet *rights, AuthorizationItemSet *environment, AuthorizationFlags flags, out IntPtr auth); [DllImport (Constants.SecurityLibrary)] extern static int AuthorizationExecuteWithPrivileges (IntPtr handle, string pathToTool, AuthorizationFlags flags, string [] args, IntPtr FILEPtr); [DllImport (Constants.SecurityLibrary)] extern static int AuthorizationFree (IntPtr handle, AuthorizationFlags flags); internal Authorization (IntPtr handle) { this.handle = handle; } public int ExecuteWithPrivileges (string pathToTool, AuthorizationFlags flags, string [] args) { return AuthorizationExecuteWithPrivileges (handle, pathToTool, flags, args, IntPtr.Zero); } public void Dispose () { GC.SuppressFinalize (this); Dispose (0, true); } ~Authorization () { Dispose (0, false); } public virtual void Dispose (AuthorizationFlags flags, bool disposing) { if (handle != IntPtr.Zero){ AuthorizationFree (handle, flags); handle = IntPtr.Zero; } } public static Authorization Create (AuthorizationFlags flags) { return Create (null, null, flags); } static void EncodeString (ref AuthorizationItem item, string key, string value) { item.name = Marshal.StringToHGlobalAuto (key); if (value != null){ item.value = Marshal.StringToHGlobalAuto (value); item.valueLen = (IntPtr) value.Length; } } public static Authorization Create (AuthorizationParameters parameters, AuthorizationEnvironment environment, AuthorizationFlags flags) { AuthorizationItemSet pars = new AuthorizationItemSet (); AuthorizationItemSet *ppars = null; AuthorizationItem *pitems = null; AuthorizationItemSet env = new AuthorizationItemSet (); AuthorizationItemSet *penv = null; AuthorizationItem *eitems = null; int code; IntPtr auth; try { unsafe { if (parameters != null){ ppars = &pars; pars.ptrToAuthorization = (AuthorizationItem *) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 3); if (parameters.PathToSystemPrivilegeTool != null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "system.privilege.admin", parameters.PathToSystemPrivilegeTool); if (parameters.Prompt != null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "prompt", parameters.Prompt); if (parameters.IconPath != null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "prompt", parameters.IconPath); } if (environment != null){ penv = &env; env.ptrToAuthorization = (AuthorizationItem *) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 3); if (environment.Username != null) EncodeString (ref env.ptrToAuthorization [env.count++], "username", environment.Username); if (environment.Password != null) EncodeString (ref env.ptrToAuthorization [env.count++], "password", environment.Password); if (environment.AddToSharedCredentialPool) EncodeString (ref env.ptrToAuthorization [env.count++], "shared", null); } code = AuthorizationCreate (ppars, penv, flags, out auth); if (code != 0) return null; return new Authorization (auth); } } finally { if (ppars != null){ for (int i = 0; i < pars.count; i++){ Marshal.FreeHGlobal (pars.ptrToAuthorization [i].name); Marshal.FreeHGlobal (pars.ptrToAuthorization [i].value); } Marshal.FreeHGlobal ((IntPtr)pars.ptrToAuthorization); } if (penv != null){ for (int i = 0; i < env.count; i++){ Marshal.FreeHGlobal (env.ptrToAuthorization [i].name); if (env.ptrToAuthorization [i].value != IntPtr.Zero) Marshal.FreeHGlobal (env.ptrToAuthorization [i].value); } Marshal.FreeHGlobal ((IntPtr)env.ptrToAuthorization); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.Routing; using Microsoft.Msagl.Routing.Visibility; using Microsoft.Msagl.DebugHelpers; using Microsoft.Msagl.Routing.ConstrainedDelaunayTriangulation; namespace Microsoft.Msagl.Routing.Spline.Bundling { /// <summary> /// Adjust current bundle-routing /// </summary> public class SimulatedAnnealing { /// <summary> /// bundle data /// </summary> readonly MetroGraphData metroGraphData; /// <summary> /// Algorithm settings /// </summary> readonly BundlingSettings bundlingSettings; /// calculates rouing cost readonly CostCalculator costCalculator; /// used for fast calculation of intersections readonly IntersectionCache cache; /// <summary> /// fix routing by simulated annealing algorithm /// </summary> internal static bool FixRouting(MetroGraphData metroGraphData, BundlingSettings bundlingSettings) { return FixRouting(metroGraphData, bundlingSettings, null); } internal static bool FixRouting(MetroGraphData metroGraphData, BundlingSettings bundlingSettings, HashSet<Point> changedPoints) { return new SimulatedAnnealing(metroGraphData, bundlingSettings).FixRouting(changedPoints); } SimulatedAnnealing(MetroGraphData metroGraphData, BundlingSettings bundlingSettings) { this.metroGraphData = metroGraphData; this.bundlingSettings = bundlingSettings; costCalculator = new CostCalculator(metroGraphData, bundlingSettings); cache = new IntersectionCache(metroGraphData, bundlingSettings, costCalculator, metroGraphData.Cdt); } const int MaxIterations = 100; const double MaxStep = 50; const double MinStep = 1; const double MinRelativeChange = 0.0005; HashSet<Station> stationsForOptimizations; /// <summary> /// Use constraint edge routing to reduce ink /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Msagl.Routing.Spline.Bundling.GeneralBundling.InkMetric.OutputQ(System.String,Microsoft.Msagl.Routing.Spline.Bundling.GeneralBundling.MetroGraphData,Microsoft.Msagl.Core.Routing.BundlingSettings)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Msagl.Routing.Spline.Bundling.GeneralBundling.InkMetric.OutputQ(System.String,Microsoft.Msagl.Routing.Spline.Bundling.GeneralBundling.MetroGraphData,Microsoft.Msagl.Routing.Spline.Bundling.BundlingSettings)")] bool FixRouting(HashSet<Point> changedPoints) { stationsForOptimizations = GetStationsForOptimizations(changedPoints); cache.InitializeCostCache(); double step = MaxStep; double energy = double.PositiveInfinity; List<Point> x = new List<Point>(metroGraphData.VirtualNodes().Select(v => v.Position)); int iteration = 0; while (iteration++ < MaxIterations) { bool coordinatesChanged = TryMoveNodes(); //TimeMeasurer.DebugOutput(" #iter = " + iteration + " moved: " + cnt + "/" + metroGraphData.VirtualNodes().Count() + " step: " + step); if (iteration <= 1 && !coordinatesChanged) return false; if (!coordinatesChanged) break; double oldEnergy = energy; energy = CostCalculator.Cost(metroGraphData, bundlingSettings); //TimeMeasurer.DebugOutput("energy: " + energy); step = UpdateMaxStep(step, oldEnergy, energy); List<Point> oldX = x; x = new List<Point>(metroGraphData.VirtualNodes().Select(v => v.Position)); if (step < MinStep || Converged(step, oldX, x)) break; } //TimeMeasurer.DebugOutput("SA completed after " + iteration + " iterations"); return true; } HashSet<Station> GetStationsForOptimizations(HashSet<Point> changedPoints) { if (changedPoints == null) { return new HashSet<Station>(metroGraphData.VirtualNodes()); } else { HashSet<Station> result = new HashSet<Station>(); foreach (var p in changedPoints) { if (metroGraphData.PointToStations.ContainsKey(p)) { var s = metroGraphData.PointToStations[p]; if (!s.IsRealNode) result.Add(s); } } return result; } } /// <summary> /// stop SA if relative changes are small /// </summary> bool Converged(double step, List<Point> oldx, List<Point> newx) { //return false; double num = 0, den = 0; for (int i = 0; i < oldx.Count; i++) { num += (oldx[i] - newx[i]).LengthSquared; den += oldx[i].LengthSquared; } double res = Math.Sqrt(num / den); return (res < MinRelativeChange); } int stepsWithProgress = 0; double UpdateMaxStep(double step, double oldEnergy, double newEnergy) { //cooling factor double T = 0.8; if (newEnergy + 1.0 < oldEnergy) { stepsWithProgress++; if (stepsWithProgress >= 5) { stepsWithProgress = 0; step = Math.Min(MaxStep, step / T); } } else { stepsWithProgress = 0; step *= T; } return step; } bool TryMoveNodes() { var coordinatesChanged = false; HashSet<Station> movedStations = new HashSet<Station>(); //foreach (var node in metroGraphData.VirtualNodes()) { foreach (var node in stationsForOptimizations) { if (TryMoveNode(node)) { Debug.Assert(stationsForOptimizations.Contains(node)); coordinatesChanged = true; movedStations.Add(node); foreach (var adj in node.Neighbors) if (!adj.IsRealNode) movedStations.Add(adj); } } stationsForOptimizations = movedStations; return coordinatesChanged; } /// <summary> /// Move node to decrease the cost of the drawing /// Returns true iff position has changed /// </summary> bool TryMoveNode(Station node) { Point direction = BuildDirection(node); if (direction.Length == 0) return false; double stepLength = BuildStepLength(node, direction); if (stepLength < MinStep) { //try random direction direction = Point.RandomPoint(); stepLength = BuildStepLength(node, direction); if (stepLength < MinStep) return false; } Point step = direction * stepLength; Point newPosition = node.Position + step; //can this happen? if (metroGraphData.PointToStations.ContainsKey(newPosition)) return false; metroGraphData.MoveNode(node, newPosition); cache.UpdateCostCache(node); return true; } /// <summary> /// Calculate the direction to improve the ink function /// </summary> Point BuildDirection(Station node) { var forceInk = BuildForceForInk(node); var forcePL = BuildForceForPathLengths(node); var forceR = BuildForceForRadius(node); var forceBundle = BuildForceForBundle(node); var force = forceInk + forcePL + forceR + forceBundle; if (force.Length < 0.1) return new Point(); force = force.Normalize(); return force; } double BuildStepLength(Station node, Point direction) { double stepLength = MinStep; double costGain = CostGain(node, node.Position + direction * stepLength); if (costGain < 0.01) return 0; while (2 * stepLength <= MaxStep) { double newCostGain = CostGain(node, node.Position + direction * stepLength * 2); if (newCostGain <= costGain) break; stepLength *= 2; costGain = newCostGain; } return stepLength; } /// <summary> /// Computes cost delta when moving the node /// the cost will be negative if a new position overlaps obstacles /// </summary> double CostGain(Station node, Point newPosition) { double MInf = -12345678.0; double rGain = costCalculator.RadiusGain(node, newPosition); if (rGain < MInf) return MInf; double bundleGain = costCalculator.BundleGain(node, newPosition); if (bundleGain < MInf) return MInf; double inkGain = costCalculator.InkGain(node, newPosition); double plGain = costCalculator.PathLengthsGain(node, newPosition); return rGain + inkGain + plGain + bundleGain; } /// <summary> /// force to decrease ink /// </summary> Point BuildForceForInk(Station node) { //return new Point(); Point direction = new Point(); foreach (var adj in node.Neighbors) { var p = (adj.Position - node.Position); direction += p / p.Length; } //derivative Point force = direction * bundlingSettings.InkImportance; return force; } /// <summary> /// direction to decrease path lengths /// </summary> Point BuildForceForPathLengths(Station node) { //return new Point(); var direction = new Point(); foreach (var mni in metroGraphData.MetroNodeInfosOfNode(node)) { var metroline = mni.Metroline; Point u = mni.PolyPoint.Next.Point; Point v = mni.PolyPoint.Prev.Point; var p1 = u - node.Position; var p2 = v - node.Position; direction += p1 / (p1.Length * metroline.IdealLength); direction += p2 / (p2.Length * metroline.IdealLength); } //derivative Point force = direction * bundlingSettings.PathLengthImportance; return force; } /// <summary> /// direction to increase radii /// </summary> Point BuildForceForRadius(Station node) { Point direction = new Point(); double idealR = node.cachedIdealRadius; List<Tuple<Polyline, Point>> touchedObstacles; bool res = metroGraphData.looseIntersections.HubAvoidsObstacles(node, node.Position, idealR, out touchedObstacles); Debug.Assert(res); foreach (var d in touchedObstacles) { double dist = (d.Item2 - node.Position).Length; Debug.Assert(dist <= idealR); double lforce = 2.0 * (1.0 - dist / idealR); Point dir = (node.Position - d.Item2).Normalize(); direction += dir * lforce; } //derivative Point force = direction * bundlingSettings.HubRepulsionImportance; return force; } /// <summary> /// direction to push a bundle away from obstacle /// </summary> Point BuildForceForBundle(Station node) { var direction = new Point(); foreach (var adj in node.Neighbors) { double idealWidth = metroGraphData.GetWidth(node, adj, bundlingSettings.EdgeSeparation); List<Tuple<Point, Point>> closestPoints; bool res = metroGraphData.cdtIntersections.BundleAvoidsObstacles(node, adj, node.Position, adj.Position, idealWidth / 2, out closestPoints); if (!res) { #if DEBUG&& TEST_MSAGL HubDebugger.ShowHubs(metroGraphData, bundlingSettings, new LineSegment(node.Position, adj.Position)); #endif } //Debug.Assert(res); //todo : still unsolved foreach (var d in closestPoints) { double dist = (d.Item1 - d.Item2).Length; Debug.Assert(ApproximateComparer.LessOrEqual(dist, idealWidth / 2)); double lforce = 2.0 * (1.0 - dist / (idealWidth / 2)); Point dir = -(d.Item1 - d.Item2).Normalize(); direction += dir * lforce; } } //derivative Point force = direction * bundlingSettings.BundleRepulsionImportance; return force; } } }
using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { private const int MountPointFormatBufferSizeInBytes = 32; /// <summary> /// Internal FileSystem names and magic numbers taken from man(2) statfs /// </summary> /// <remarks> /// These value names MUST be kept in sync with those in GetDriveType below /// </remarks> internal enum UnixFileSystemTypes : long { adfs = 0xadf5, affs = 0xADFF, befs = 0x42465331, bfs = 0x1BADFACE, cifs = 0xFF534D42, coda = 0x73757245, coherent = 0x012FF7B7, cramfs = 0x28cd3d45, devfs = 0x1373, efs = 0x00414A53, ext = 0x137D, ext2_old = 0xEF51, ext2 = 0xEF53, ext3 = 0xEF53, ext4 = 0xEF53, hfs = 0x4244, hpfs = 0xF995E849, hugetlbfs = 0x958458f6, isofs = 0x9660, jffs2 = 0x72b6, jfs = 0x3153464a, minix_old = 0x137F, /* orig. minix */ minix = 0x138F, /* 30 char minix */ minix2 = 0x2468, /* minix V2 */ minix2v2 = 0x2478, /* minix V2, 30 char names */ msdos = 0x4d44, ncpfs = 0x564c, nfs = 0x6969, ntfs = 0x5346544e, openprom = 0x9fa1, proc = 0x9fa0, qnx4 = 0x002f, reiserfs = 0x52654973, romfs = 0x7275, smb = 0x517B, sysv2 = 0x012FF7B6, sysv4 = 0x012FF7B5, tmpfs = 0x01021994, udf = 0x15013346, ufs = 0x00011954, usbdevice = 0x9fa2, vxfs = 0xa501FCF5, xenix = 0x012FF7B4, xfs = 0x58465342, xiafs = 0x012FD16D, } [StructLayout(LayoutKind.Sequential)] internal struct MountPointInformation { internal long AvailableFreeSpace; internal long TotalFreeSpace; internal long TotalSize; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate void MountPointFound(byte* name); [DllImport(Libraries.SystemNative, SetLastError = true)] private static extern int GetAllMountPoints(MountPointFound mpf); [DllImport(Libraries.SystemNative, SetLastError = true)] internal static extern int GetSpaceInfoForMountPoint([MarshalAs(UnmanagedType.LPStr)]string name, out MountPointInformation mpi); [DllImport(Libraries.SystemNative, SetLastError = true)] private unsafe static extern int GetFormatInfoForMountPoint( [MarshalAs(UnmanagedType.LPStr)]string name, byte* formatNameBuffer, int bufferLength, long* formatType); internal static int GetFormatInfoForMountPoint(string name, out string format) { DriveType temp; return GetFormatInfoForMountPoint(name, out format, out temp); } internal static int GetFormatInfoForMountPoint(string name, out DriveType type) { string temp; return GetFormatInfoForMountPoint(name, out temp, out type); } private static int GetFormatInfoForMountPoint(string name, out string format, out DriveType type) { unsafe { byte* formatBuffer = stackalloc byte[MountPointFormatBufferSizeInBytes]; // format names should be small long numericFormat; int result = GetFormatInfoForMountPoint(name, formatBuffer, MountPointFormatBufferSizeInBytes, &numericFormat); if (result == 0) { // Check if we have a numeric answer or string format = numericFormat != -1 ? Enum.GetName(typeof(UnixFileSystemTypes), numericFormat) : Marshal.PtrToStringAnsi((IntPtr)formatBuffer); type = GetDriveType(format); } else { format = string.Empty; type = DriveType.Unknown; } return result; } } internal static List<string> GetAllMountPoints() { List<string> lst = new List<string>(); unsafe { int result = GetAllMountPoints((byte* name) => { lst.Add(Marshal.PtrToStringAnsi((IntPtr)name)); }); } return lst; } /// <summary>Categorizes a file system name into a drive type.</summary> /// <param name="fileSystemName">The name to categorize.</param> /// <returns>The recognized drive type.</returns> private static DriveType GetDriveType(string fileSystemName) { // This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems", // and "wiki.debian.org/FileSystem". It can be extended over time as we // find additional file systems that should be recognized as a particular drive type. switch (fileSystemName) { case "iso": case "isofs": case "iso9660": case "fuseiso": case "fuseiso9660": case "umview-mod-umfuseiso9660": return DriveType.CDRom; case "adfs": case "affs": case "befs": case "bfs": case "btrfs": case "ecryptfs": case "efs": case "ext": case "ext2": case "ext2_old": case "ext3": case "ext4": case "ext4dev": case "fat": case "fuseblk": case "fuseext2": case "fusefat": case "hfs": case "hfsplus": case "hpfs": case "jbd": case "jbd2": case "jfs": case "jffs": case "jffs2": case "minix": case "minix_old": case "minix2": case "minix2v2": case "msdos": case "ocfs2": case "omfs": case "openprom": case "ntfs": case "qnx4": case "reiserfs": case "squashfs": case "swap": case "sysv": case "ubifs": case "udf": case "ufs": case "umsdos": case "umview-mod-umfuseext2": case "xenix": case "xfs": case "xiafs": case "xmount": case "zfs-fuse": return DriveType.Fixed; case "9p": case "autofs": case "autofs4": case "beaglefs": case "cifs": case "coda": case "coherent": case "curlftpfs": case "davfs2": case "dlm": case "flickrfs": case "fusedav": case "fusesmb": case "gfs2": case "glusterfs-client": case "gmailfs": case "kafs": case "ltspfs": case "ncpfs": case "nfs": case "nfs4": case "obexfs": case "s3ql": case "smb": case "smbfs": case "sshfs": case "sysfs": case "sysv2": case "sysv4": case "vxfs": case "wikipediafs": return DriveType.Network; case "anon_inodefs": case "aptfs": case "avfs": case "bdev": case "binfmt_misc": case "cgroup": case "configfs": case "cramfs": case "cryptkeeper": case "cpuset": case "debugfs": case "devfs": case "devpts": case "devtmpfs": case "encfs": case "fuse": case "fuse.gvfsd-fuse": case "fusectl": case "hugetlbfs": case "libpam-encfs": case "ibpam-mount": case "mtpfs": case "mythtvfs": case "mqueue": case "pipefs": case "plptools": case "proc": case "pstore": case "pytagsfs": case "ramfs": case "rofs": case "romfs": case "rootfs": case "securityfs": case "sockfs": case "tmpfs": return DriveType.Ram; case "gphotofs": case "usbfs": case "usbdevice": case "vfat": return DriveType.Removable; case "aufs": // marking all unions as unknown case "funionfs": case "unionfs-fuse": case "mhddfs": default: return DriveType.Unknown; } } } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel email : [email protected] based on : id3v2tag.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ using System.Collections; using System; namespace TagLib.Id3v2 { public class Tag : TagLib.Tag { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private long tag_offset; private Header header; private ExtendedHeader extended_header; private Footer footer; private ArrayList frame_list; private static ByteVector language = "eng"; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public Tag () : base () { tag_offset = -1; header = new Header (); extended_header = null; footer = null; frame_list = new ArrayList (); } public Tag (File file, long tag_offset) : this () { this.tag_offset = tag_offset; Read (file); } public Frame [] GetFrames () { return (Frame []) frame_list.ToArray (typeof (Frame)); } public Frame [] GetFrames (ByteVector id) { ArrayList l = new ArrayList (); foreach (Frame f in frame_list) if (f.FrameId == id) l.Add (f); return (Frame []) l.ToArray (typeof (Frame)); } public void AddFrame (Frame frame) { frame_list.Add (frame); } public void RemoveFrame (Frame frame) { if (frame_list.Contains (frame)) frame_list.Remove (frame); } public void RemoveFrames (ByteVector id) { for (int i = frame_list.Count - 1; i >= 0; i --) { Frame f = (Frame) frame_list [i]; if (f.FrameId == id) RemoveFrame (f); } } public ByteVector Render () { // We need to render the "tag data" first so that we have to correct size to // render in the tag's header. The "tag data" -- everything that is included // in ID3v2::Header::tagSize() -- includes the extended header, frames and // padding, but does not include the tag's header or footer. ByteVector tag_data = new ByteVector (); // TODO: Render the extended header. header.ExtendedHeader = false; // Loop through the frames rendering them and adding them to the tagData. foreach (Frame frame in frame_list) if (!frame.Header.TagAlterPreservation) tag_data.Add (frame.Render ()); // Compute the amount of padding, and append that to tagData. uint padding_size = 0; uint original_size = header.TagSize; if (!header.FooterPresent) { if (tag_data.Count < original_size) padding_size = (uint) (original_size - tag_data.Count); else padding_size = 1024; tag_data.Add (new ByteVector ((int) padding_size)); } // Set the tag size. header.TagSize = (uint) tag_data.Count; tag_data.Insert (0, header.Render ()); if (header.FooterPresent) { footer = new Footer (header); tag_data.Add (footer.Render ()); } return tag_data; } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// public override string Title { get { foreach (TextIdentificationFrame f in GetFrames ("TIT2")) return f.ToString (); return null; } set { SetTextFrame ("TIT2", value); } } public override string [] AlbumArtists { get { foreach (TextIdentificationFrame f in GetFrames ("TPE1")) return f.FieldList.ToArray (); return new string [] {}; } set { SetTextFrame ("TPE1", new StringList (value)); } } public override string [] Performers { get { foreach (TextIdentificationFrame f in GetFrames ("TPE2")) return f.FieldList.ToArray (); return new string [] {}; } set { SetTextFrame ("TPE2", new StringList (value)); } } public override string [] Composers { get { foreach (TextIdentificationFrame f in GetFrames ("TCOM")) return f.FieldList.ToArray (); return new string [] {}; } set { SetTextFrame ("TCOM", new StringList (value)); } } public override string Album { get { foreach (TextIdentificationFrame f in GetFrames ("TALB")) return f.ToString (); return null; } set { SetTextFrame ("TALB", value); } } public override string Comment { get { // This is weird, so bear with me. The best thing we can have is // something straightforward and in our own language. If it has a // description, then it is probably used for something other than // an actual comment. If that doesn't work, we'd still rather have // something in our language than something in another. After that // all we have left are things in other languages, so we'd rather // have one with actual content, so we try to get one with no // description first. Frame [] frames = GetFrames ("COMM"); foreach (CommentsFrame f in frames) if (f.Description == "" && f.Language == Language) return f.ToString (); foreach (CommentsFrame f in frames) if (f.Language == Language) return f.ToString (); foreach (CommentsFrame f in frames) if (f.Description == "") return f.ToString (); foreach (CommentsFrame f in frames) return f.ToString (); return null; } set { if (value == null || value == "") { RemoveFrames ("COMM"); return; } // See above. Frame [] frames = GetFrames ("COMM"); foreach (CommentsFrame f in frames) if (f.Description == "" && f.Language == Language) { f.SetText (value); return; } foreach (CommentsFrame f in frames) if (f.Language == Language) { f.SetText (value); return; } foreach (CommentsFrame f in frames) if (f.Description == "") { f.SetText (value); return; } foreach (CommentsFrame f in frames) { f.SetText (value); return; } // There were absolutely no comment frames. Let's add one in our // language. CommentsFrame frame = new CommentsFrame (FrameFactory.DefaultTextEncoding); frame.Language = Language; frame.SetText (value); AddFrame (frame); } } public override string [] Genres { get { ArrayList l = new ArrayList (); Frame [] frames = GetFrames ("TCON"); TextIdentificationFrame frame; if (frames.Length != 0 && (frame = (TextIdentificationFrame) frames [0]) != null) { StringList fields = frame.FieldList; foreach (string s in fields) { if (s == null) continue; bool is_number = true; foreach (char c in s) if (c < '0' || c > '9') is_number = false; if(is_number) { try { l.Add (Id3v1.GenreList.Genre (Byte.Parse (s))); continue; } catch {} } int closing = s.IndexOf (')'); if (closing > 0 && s.Substring (0, 1) == "(") { if(closing == s.Length - 1) { try { l.Add (Id3v1.GenreList.Genre (Byte.Parse (s.Substring (1, closing - 1)))); } catch { l.Add (s); } } else l.Add (s.Substring (closing + 1)); } else l.Add (s); } } return (string []) l.ToArray (typeof (string)); } set { for (int i = 0; i < value.Length; i ++) { int index = Id3v1.GenreList.GenreIndex (value [i]); if (index != 255) value [i] = index.ToString (); } SetTextFrame ("TCON", new StringList (value)); } } public override uint Year { get { foreach (TextIdentificationFrame f in GetFrames ("TDRC")) { try { return UInt32.Parse (f.ToString ().Substring (0, 4)); } catch {} } return 0; } set { SetTextFrame ("TDRC", value.ToString ()); } } public override uint Track { get { try { return UInt32.Parse (GetFrames ("TRCK") [0].ToString ().Split (new char [] {'/'}) [0]); } catch {return 0;} } set { uint count = TrackCount; if (count != 0) SetTextFrame ("TRCK", value + "/" + count); else SetTextFrame ("TRCK", value.ToString ()); } } public override uint TrackCount { get { try { return UInt32.Parse (GetFrames ("TRCK") [0].ToString ().Split (new char [] {'/'}) [1]); } catch {return 0;} } set { SetTextFrame ("TRCK", Track + "/" + value); } } public override uint Disc { get { try { return UInt32.Parse (GetFrames ("TPOS") [0].ToString ().Split (new char [] {'/'}) [0]); } catch {return 0;} } set { uint count = DiscCount; if (count != 0) SetTextFrame ("TPOS", value + "/" + count); else SetTextFrame ("TPOS", value.ToString ()); } } public override uint DiscCount { get { try { return UInt32.Parse (GetFrames ("TPOS") [0].ToString ().Split (new char [] {'/'}) [1]); } catch {return 0;} } set { SetTextFrame ("TPOS", Disc + "/" + value); } } public override IPicture [] Pictures { get { Frame [] raw_frames = GetFrames("APIC"); if(raw_frames == null || raw_frames.Length == 0) { return base.Pictures; } AttachedPictureFrame [] frames = new AttachedPictureFrame[raw_frames.Length]; for(int i = 0; i < frames.Length; i++) { frames[i] = (AttachedPictureFrame)raw_frames[i]; } return frames; } set { if(value == null || value.Length < 1) { return; } RemoveFrames("APIC"); foreach(IPicture picture in value) { AddFrame(new AttachedPictureFrame(picture)); } } } public override bool IsEmpty {get {return frame_list.Count == 0;}} public Header Header {get {return header;}} public ExtendedHeader ExtendedHeader {get {return extended_header;}} public Footer Footer {get {return footer;}} ////////////////////////////////////////////////////////////////////////// // public static properties ////////////////////////////////////////////////////////////////////////// public static ByteVector Language { get {return language;} set {language = (value == null || value.Count < 3) ? "XXX" : value.Mid (0,3);} } ////////////////////////////////////////////////////////////////////////// // protected methods ////////////////////////////////////////////////////////////////////////// protected void Read (TagLib.File file) { if (file == null) return; try {file.Mode = File.AccessMode.Read;} catch {return;} file.Seek (tag_offset); header.SetData (file.ReadBlock ((int) Header.Size)); // if the tag size is 0, then this is an invalid tag (tags must contain // at least one frame) if(header.TagSize == 0) return; Parse (file.ReadBlock ((int) header.TagSize)); } protected void Parse (ByteVector data) { int frame_data_position = 0; int frame_data_length = data.Count; // check for extended header if (header.ExtendedHeader) { if (ExtendedHeader == null) extended_header = new ExtendedHeader (); ExtendedHeader.SetData (data); if(ExtendedHeader.Size <= data.Count) { frame_data_position += (int) ExtendedHeader.Size; frame_data_length -= (int) ExtendedHeader.Size; } } // check for footer -- we don't actually need to parse it, as it *must* // contain the same data as the header, but we do need to account for its // size. if(header.FooterPresent && Footer.Size <= frame_data_length) frame_data_length -= (int) Footer.Size; // parse frames // Make sure that there is at least enough room in the remaining frame data for // a frame header. while (frame_data_position < frame_data_length - FrameHeader.Size (header.MajorVersion)) { // If the next data is position is 0, assume that we've hit the padding // portion of the frame data. if(data [frame_data_position] == 0) { if (header.FooterPresent) Debugger.Debug ("Padding *and* a footer found. This is not allowed by the spec."); return; } Frame frame = FrameFactory.CreateFrame (data, frame_data_position, header.MajorVersion); if(frame == null) return; // Checks to make sure that frame parsed correctly. if(frame.Size < 0) return; frame_data_position += (int) (frame.Size + FrameHeader.Size (header.MajorVersion)); // Only add frames with content so we don't send out just we got in. if (frame.Size > 0) AddFrame (frame); } } public void SetTextFrame (ByteVector id, string value) { if (value == null || value == "") { RemoveFrames (id); return; } SetTextFrame (id, new StringList (value)); } public void SetTextFrame (ByteVector id, StringList value) { if (value == null || value.Count == 0) { RemoveFrames (id); return; } Frame [] frames = GetFrames (id); if (frames.Length != 0) { bool first = true; foreach (TextIdentificationFrame frame in frames) { // There should only be one of each text frame, per the specification. if (first) frame.SetText (value); else RemoveFrame (frame); first = false; } } else { TextIdentificationFrame f = new TextIdentificationFrame (id, FrameFactory.DefaultTextEncoding); AddFrame (f); f.SetText (value); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysPerfil class. /// </summary> [Serializable] public partial class SysPerfilCollection : ActiveList<SysPerfil, SysPerfilCollection> { public SysPerfilCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysPerfilCollection</returns> public SysPerfilCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysPerfil 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 Sys_Perfil table. /// </summary> [Serializable] public partial class SysPerfil : ActiveRecord<SysPerfil>, IActiveRecord { #region .ctors and Default Settings public SysPerfil() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysPerfil(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysPerfil(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysPerfil(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("Sys_Perfil", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdPerfil = new TableSchema.TableColumn(schema); colvarIdPerfil.ColumnName = "idPerfil"; colvarIdPerfil.DataType = DbType.Int32; colvarIdPerfil.MaxLength = 0; colvarIdPerfil.AutoIncrement = true; colvarIdPerfil.IsNullable = false; colvarIdPerfil.IsPrimaryKey = true; colvarIdPerfil.IsForeignKey = false; colvarIdPerfil.IsReadOnly = false; colvarIdPerfil.DefaultSetting = @""; colvarIdPerfil.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPerfil); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @"('')"; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarActivo = new TableSchema.TableColumn(schema); colvarActivo.ColumnName = "activo"; colvarActivo.DataType = DbType.Boolean; colvarActivo.MaxLength = 0; colvarActivo.AutoIncrement = false; colvarActivo.IsNullable = false; colvarActivo.IsPrimaryKey = false; colvarActivo.IsForeignKey = false; colvarActivo.IsReadOnly = false; colvarActivo.DefaultSetting = @"((1))"; colvarActivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarActivo); TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema); colvarIdUsuario.ColumnName = "idUsuario"; colvarIdUsuario.DataType = DbType.Int32; colvarIdUsuario.MaxLength = 0; colvarIdUsuario.AutoIncrement = false; colvarIdUsuario.IsNullable = false; colvarIdUsuario.IsPrimaryKey = false; colvarIdUsuario.IsForeignKey = false; colvarIdUsuario.IsReadOnly = false; colvarIdUsuario.DefaultSetting = @"((0))"; colvarIdUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuario); TableSchema.TableColumn colvarFechaActualizacion = new TableSchema.TableColumn(schema); colvarFechaActualizacion.ColumnName = "fechaActualizacion"; colvarFechaActualizacion.DataType = DbType.DateTime; colvarFechaActualizacion.MaxLength = 0; colvarFechaActualizacion.AutoIncrement = false; colvarFechaActualizacion.IsNullable = false; colvarFechaActualizacion.IsPrimaryKey = false; colvarFechaActualizacion.IsForeignKey = false; colvarFechaActualizacion.IsReadOnly = false; colvarFechaActualizacion.DefaultSetting = @"(((1)/(1))/(1900))"; colvarFechaActualizacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaActualizacion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_Perfil",schema); } } #endregion #region Props [XmlAttribute("IdPerfil")] [Bindable(true)] public int IdPerfil { get { return GetColumnValue<int>(Columns.IdPerfil); } set { SetColumnValue(Columns.IdPerfil, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Activo")] [Bindable(true)] public bool Activo { get { return GetColumnValue<bool>(Columns.Activo); } set { SetColumnValue(Columns.Activo, value); } } [XmlAttribute("IdUsuario")] [Bindable(true)] public int IdUsuario { get { return GetColumnValue<int>(Columns.IdUsuario); } set { SetColumnValue(Columns.IdUsuario, value); } } [XmlAttribute("FechaActualizacion")] [Bindable(true)] public DateTime FechaActualizacion { get { return GetColumnValue<DateTime>(Columns.FechaActualizacion); } set { SetColumnValue(Columns.FechaActualizacion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.SysPermisoCollection colSysPermisoRecords; public DalSic.SysPermisoCollection SysPermisoRecords { get { if(colSysPermisoRecords == null) { colSysPermisoRecords = new DalSic.SysPermisoCollection().Where(SysPermiso.Columns.IdPerfil, IdPerfil).Load(); colSysPermisoRecords.ListChanged += new ListChangedEventHandler(colSysPermisoRecords_ListChanged); } return colSysPermisoRecords; } set { colSysPermisoRecords = value; colSysPermisoRecords.ListChanged += new ListChangedEventHandler(colSysPermisoRecords_ListChanged); } } void colSysPermisoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysPermisoRecords[e.NewIndex].IdPerfil = IdPerfil; } } private DalSic.SysUsuarioCollection colSysUsuarioRecords; public DalSic.SysUsuarioCollection SysUsuarioRecords { get { if(colSysUsuarioRecords == null) { colSysUsuarioRecords = new DalSic.SysUsuarioCollection().Where(SysUsuario.Columns.IdPerfil, IdPerfil).Load(); colSysUsuarioRecords.ListChanged += new ListChangedEventHandler(colSysUsuarioRecords_ListChanged); } return colSysUsuarioRecords; } set { colSysUsuarioRecords = value; colSysUsuarioRecords.ListChanged += new ListChangedEventHandler(colSysUsuarioRecords_ListChanged); } } void colSysUsuarioRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysUsuarioRecords[e.NewIndex].IdPerfil = IdPerfil; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEfector,string varNombre,bool varActivo,int varIdUsuario,DateTime varFechaActualizacion) { SysPerfil item = new SysPerfil(); item.IdEfector = varIdEfector; item.Nombre = varNombre; item.Activo = varActivo; item.IdUsuario = varIdUsuario; item.FechaActualizacion = varFechaActualizacion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdPerfil,int varIdEfector,string varNombre,bool varActivo,int varIdUsuario,DateTime varFechaActualizacion) { SysPerfil item = new SysPerfil(); item.IdPerfil = varIdPerfil; item.IdEfector = varIdEfector; item.Nombre = varNombre; item.Activo = varActivo; item.IdUsuario = varIdUsuario; item.FechaActualizacion = varFechaActualizacion; 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 IdPerfilColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn ActivoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn IdUsuarioColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn FechaActualizacionColumn { get { return Schema.Columns[5]; } } #endregion #region Columns Struct public struct Columns { public static string IdPerfil = @"idPerfil"; public static string IdEfector = @"idEfector"; public static string Nombre = @"nombre"; public static string Activo = @"activo"; public static string IdUsuario = @"idUsuario"; public static string FechaActualizacion = @"fechaActualizacion"; } #endregion #region Update PK Collections public void SetPKValues() { if (colSysPermisoRecords != null) { foreach (DalSic.SysPermiso item in colSysPermisoRecords) { if (item.IdPerfil != IdPerfil) { item.IdPerfil = IdPerfil; } } } if (colSysUsuarioRecords != null) { foreach (DalSic.SysUsuario item in colSysUsuarioRecords) { if (item.IdPerfil != IdPerfil) { item.IdPerfil = IdPerfil; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colSysPermisoRecords != null) { colSysPermisoRecords.SaveAll(); } if (colSysUsuarioRecords != null) { colSysUsuarioRecords.SaveAll(); } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SubnetsOperations operations. /// </summary> internal partial class SubnetsOperations : IServiceOperations<NetworkManagementClient>, ISubnetsOperations { /// <summary> /// Initializes a new instance of the SubnetsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SubnetsOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified subnet by virtual network and resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a subnet in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create or update subnet operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Subnet> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all subnets in a virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a subnet in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create or update subnet operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (subnetParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("subnetParameters", subnetParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(subnetParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(subnetParameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all subnets in a virtual network. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using NUnit.Framework; namespace Softengi.DmnEngine.Tests.Feel { [TestFixture] public class NumericUnaryComparisonsTests : FeelTester { [TestCase(20, true)] [TestCase(10.1, true)] [TestCase(10, false)] public void Test_GreaterThan(decimal value, bool expectation) { ExpectFeel(">10", value, expectation); } [TestCase(20, false)] [TestCase(10.1, false)] [TestCase(10, true)] public void Test_not_GreaterThan(decimal value, bool expectation) { ExpectFeel("not(>10)", value, expectation); } [TestCase(20, true)] [TestCase(10, true)] [TestCase(9.999, false)] public void Test_GreaterThanOrEqual(decimal value, bool expectation) { ExpectFeel(">=10", value, expectation); } [TestCase(20, false)] [TestCase(10, false)] [TestCase(9.999, true)] public void Test_not_GreaterThanOrEqual(decimal value, bool expectation) { ExpectFeel("not(>=10)", value, expectation); } [TestCase(20, false)] [TestCase(10.1, false)] [TestCase(10, false)] [TestCase(9.999, true)] [TestCase(-20, true)] public void Test_LessThan(decimal value, bool expectation) { ExpectFeel("<10", value, expectation); } [TestCase(20, true)] [TestCase(10.1, true)] [TestCase(10, true)] [TestCase(9.999, false)] [TestCase(-20, false)] public void Test_not_LessThan(decimal value, bool expectation) { ExpectFeel("not(<10)", value, expectation); } [TestCase(20, false)] [TestCase(10.1, false)] [TestCase(10, true)] [TestCase(9.999, true)] [TestCase(-20, true)] public void Test_LessThanOrEqual(decimal value, bool expectation) { ExpectFeel("<=10", value, expectation); } [TestCase(20, true)] [TestCase(10.1, true)] [TestCase(10, false)] [TestCase(9.999, false)] [TestCase(-20, false)] public void Test_not_LessThanOrEqual(decimal value, bool expectation) { ExpectFeel("not(<=10)", value, expectation); } [TestCase(10.1, false)] [TestCase(10, true)] [TestCase(9.999, false)] [TestCase(-10, false)] public void Test_Equal(decimal value, bool expectation) { ExpectFeel("10", value, expectation); } [TestCase(10.1, true)] [TestCase(10, false)] [TestCase(9.999, true)] [TestCase(-10, true)] public void Test_not_Equal(decimal value, bool expectation) { ExpectFeel("not(10)", value, expectation); } [TestCase("10", 10, true)] [TestCase("-10", -10, true)] [TestCase("10.", 10, true)] [TestCase("-10.", -10, true)] [TestCase("10.1000", 10.1, true)] [TestCase("-10.1000", -10.1, true)] [TestCase(".1", .1, true)] [TestCase("-.1", -.1, true)] [TestCase(".100000", .1, true)] [TestCase("-.100000", -.1, true)] [TestCase("000.100000", .1, true)] [TestCase("-000.100000", -.1, true)] public void Test_Formats(string sfeel, decimal value, bool expectation) { ExpectFeel(sfeel, value, expectation); } [TestCase(0, true)] [TestCase(1, true)] [TestCase(2, false)] [TestCase(10, false)] [TestCase(10.01, true)] [TestCase(-10, false)] [TestCase(-10.01, true)] public void Test_CompareList(decimal value, bool expectation) { ExpectFeel(">10,<-10,0,1", value, expectation); } [TestCase(0, false)] [TestCase(1, false)] [TestCase(2, true)] [TestCase(10, true)] [TestCase(10.01, false)] [TestCase(-10, true)] [TestCase(-10.01, false)] public void Test_not_CompareList(decimal value, bool expectation) { ExpectFeel("not(>10,<-10,0,1)", value, expectation); } [TestCase(-5.01, false)] [TestCase(-5, true)] [TestCase(0, true)] [TestCase(5, true)] [TestCase(5.01, false)] public void Test_Range_Open_Open(decimal value, bool expectation) { ExpectFeel("[-5..5]", value, expectation); } [TestCase(-5.001, false)] [TestCase(-5, true)] [TestCase(0.5, true)] [TestCase(0.51, false)] public void Test_Range_vs_DecimalPoint(decimal value, bool expectation) { ExpectFeel("[-5...5]", value, expectation); } [TestCase(-5.501, false)] [TestCase(-5.5, true)] [TestCase(-1.1, true)] [TestCase(-1.009, false)] public void Test_Range_NegativeEnd(decimal value, bool expectation) { ExpectFeel("[-5.5..-1.1]", value, expectation); } [Test] public void Test_Spaces() { ExpectFeel(" [ - 5.5 .. - 1.1 ] ", -5.501m, false); } [TestCase(-5.01, false)] [TestCase(-5, true)] [TestCase(0, true)] [TestCase(5, false)] [TestCase(5.01, false)] [TestCase(-5.01, false)] [TestCase(-5, true)] [TestCase(0, true)] [TestCase(5, false)] [TestCase(5.01, false)] public void Test_Range_Open_Close(decimal value, bool expectation) { ExpectFeel("[-5..5)", value, expectation); } [TestCase(-5.01, false)] [TestCase(-5, false)] [TestCase(0, true)] [TestCase(5, true)] [TestCase(5.01, false)] [TestCase(-5.01, false)] [TestCase(-5, false)] [TestCase(0, true)] [TestCase(5, true)] [TestCase(5.01, false)] public void Test_Range_Close_Open(decimal value, bool expectation) { ExpectFeel("(-5..5]", value, expectation); } [TestCase(-5.01, false)] [TestCase(-5, false)] [TestCase(0, true)] [TestCase(5, false)] [TestCase(5.01, false)] public void Test_Range_Close_Close(decimal value, bool expectation) { ExpectFeel("(-5..5)", value, expectation); } [TestCase(-5.001, true)] [TestCase(-5, false)] [TestCase(0.5, false)] [TestCase(0.51, true)] public void Test_not_Range(decimal value, bool expectation) { ExpectFeel("not([-5...5])", value, expectation); } [TestCase(-5.01, false)] [TestCase(-5, true)] [TestCase(-4, true)] [TestCase(.99, false)] [TestCase(1, true)] [TestCase(2, true)] [TestCase(2.01, false)] public void Test_Range_List(decimal value, bool expectation) { ExpectFeel("[-5..-4],[1..2]", value, expectation); } [TestCase(-5.01, true)] [TestCase(-5, false)] [TestCase(-4, false)] [TestCase(.99, true)] [TestCase(1, false)] [TestCase(2, false)] [TestCase(2.01, true)] public void Test_not_Range_List(decimal value, bool expectation) { ExpectFeel("not([-5..-4],[1..2])", value, expectation); } [TestCase(-10, true)] [TestCase(-9.99, false)] [TestCase(-5.01, false)] [TestCase(-5, true)] [TestCase(-4, true)] [TestCase(0, true)] [TestCase(.99, false)] [TestCase(1, true)] [TestCase(2, true)] [TestCase(2.01, false)] [TestCase(10, false)] [TestCase(10.001, true)] public void Test_combined_Range(decimal value, bool expectation) { ExpectFeel("<=-10,[-5..-4],0,[1..2],>10", value, expectation); } [TestCase(-10, false)] [TestCase(-9.99, true)] [TestCase(-5.01, true)] [TestCase(-5, false)] [TestCase(-4, false)] [TestCase(0, false)] [TestCase(.99, true)] [TestCase(1, false)] [TestCase(2, false)] [TestCase(2.01, true)] [TestCase(10, true)] [TestCase(10.001, false)] public void Test_not_combined_Range(decimal value, bool expectation) { ExpectFeel("not(<=-10,[-5..-4],0,[1..2],>10)", value, expectation); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using iSukces.UnitedValues; namespace UnitGenerator { public class HeuristicOperatorGenerator { private HeuristicOperatorGenerator(OperatorHints.CreateOperatorCodeEventArgs args, ClrTypesResolver resolver) { _args = args; _resolver = resolver; } public static void TryCreate(OperatorHints.CreateOperatorCodeEventArgs args, ClrTypesResolver resolver) { var instance = new HeuristicOperatorGenerator(args, resolver); try { instance.TryCreateInternal(); } catch { args.Result.SetComment(); args.Result.Comment += " Exception !!!"; args.SetHandled(); } } private string AddVariable(string code, string varName) { if (varName is null) varName = "tmp" + (++_varNumber).CsEncode(); _args.Result.AddVariable(varName, code); return varName; } private ICodeSource Construct(XUnitTypeName unit) { if (!_resolver.TryGetValue(unit.GetTypename(), out var type1)) throw new NotImplementedException(); ValueOfSomeTypeExpression[] sources; var constr = type1.GetConstructors() .Where(a => { var pa = a.GetParameters(); foreach (var info in pa) if (!info.ParameterType.Implements<IUnit>()) return false; return true; }) .OrderByDescending(a => a.GetParameters().Length) .ToArray(); var typesDict = TypeFinder.Make(_sink); if (constr.Length == 0) { sources = typesDict.GetTypeSources(type1); if (sources.Any()) { var src = sources[0]; return new ExpressionCodeSource(src.Expression, src.Root == ValueOfSomeTypeExpressionRoot.Left); } return null; } var ccc = constr[0]; var list = typesDict.FindParameters(ccc, t=>Construct(new XUnitTypeName(t.Name)), out var hasLeft); // var hasLeft = list.Any(q => q.Root == ValueOfSomeTypeExpressionRoot.Left); if (!hasLeft) { sources = typesDict.GetTypeSources(type1); if (sources.Any()) { var src = sources[0]; return new ExpressionCodeSource(src.Expression, src.Root == ValueOfSomeTypeExpressionRoot.Left); } throw new NotImplementedException(); } return MethodCallCodeSource.MakeFromConstructor(unit, list, true); } private void Scan(ValueOfSomeTypeExpressionRoot root, XUnitTypeName x, Kind2 kind, ExpressionPath path = null) { if (!_resolver.TryGetValue(x.GetTypename(), out var type)) throw new NotImplementedException(); var info1 = new ValueOfSomeTypeExpression(root, type, new TreeExpression(path, null, kind), kind); _sink.Add(info1); if (kind != Kind2.Property) return; foreach (var propInfo in type.GetProperties()) { var attribute = propInfo.GetCustomAttribute<RelatedUnitSourceAttribute>(); if (attribute != null && attribute.Usage == RelatedUnitSourceUsage.DoNotUse) continue; var pt = propInfo.PropertyType; if (!pt.Implements<IUnit>()) continue; Scan(root, new XUnitTypeName(propInfo.PropertyType.Name), kind, path + propInfo.Name); } foreach (var methodInfo in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)) { var at = methodInfo.GetCustomAttribute<RelatedUnitSourceAttribute>(); if (at is null || (at.Usage & RelatedUnitSourceUsage.ProvidesRelatedUnit) == 0) continue; var returnType = methodInfo.ReturnType; if (!returnType.Implements<IUnit>()) throw new Exception("Should return IUnit"); if (methodInfo.GetParameters().Length != 0) throw new Exception("Should be parameterles"); Scan(root, new XUnitTypeName(returnType.Name), Kind2.Method, path + $"{methodInfo.Name}"); } } private void TryCreateInternal() { if (_args.Input.Is<PlanarDensity, Length, LinearDensity>("*")) Debug.Write(""); var cc = _args.Input; var lu = cc.LeftMethodArgumentName + ".Unit"; var ru = cc.RightMethodArgumentName + ".Unit"; Scan(ValueOfSomeTypeExpressionRoot.Left, cc.Left.Unit, Kind2.Property, ExpressionPath.FromSplit(lu)); Scan(ValueOfSomeTypeExpressionRoot.Right, cc.Right.Unit, Kind2.Property, ExpressionPath.FromSplit(ru)); _conversionMethodScanner = ConversionMethodScanner.Scan(_resolver.Assembly); var reductor = new ExpressionsReductor(n => { string varName = null; if (n == lu || n == ru) varName = n.Replace(".", ""); return AddVariable(n, varName); }); var convertType = Construct(cc.Right.Unit); if (convertType.Code == ru) convertType = null; else reductor.AddAny(convertType); // convertType.AddToDeleteMe(reductor); ICodeSource result = Construct(cc.Result.Unit); Func<string> addExtraValueMultiplication = null; ICodeSource G1() { if (!_resolver.TryGetValue(cc.Result.Unit.TypeName, out var type1)) throw new NotImplementedException(); if (_conversionMethodScanner.Dictionary.TryGetValue(type1, out var list)) { var typesDict = TypeFinder.Make(_sink); foreach (var i in list) { var aaa = typesDict.FindParameters(i, null, out var hl); return MethodCallCodeSource.Make(i, aaa, hl); } } return null; } if (result is null) { result = G1(); if (result != null) { addExtraValueMultiplication = () => { return result.Code + "." + nameof(IUnitDefinition.Multiplication); }; } } if (result is null) { } reductor.AddAny(result); //result.AddToDeleteMe(reductor); reductor.ReduceExpressions(); if (addExtraValueMultiplication != null) { reductor.ForceReduce(new ExpressionPath(result)); } // ============================= if (result?.Code == "specificHeatCapacity.Unit.DenominatorUnit") Debug.WriteLine(""); switch (convertType) { case null: break; case MethodCallCodeSource _: _args.Result.ConvertRight(AddVariable(convertType.Code, "targetRightUnit")); break; default: _args.Result.ConvertRight(convertType.Code); break; } if (result is MethodCallCodeSource) _args.Result.ResultUnit = AddVariable(result.Code, "resultUnit"); else _args.Result.ResultUnit = result.Code; if (addExtraValueMultiplication != null) _args.Result.ResultMultiplication = addExtraValueMultiplication(); } private int _varNumber; private readonly OperatorHints.CreateOperatorCodeEventArgs _args; private readonly ClrTypesResolver _resolver; private readonly List<ValueOfSomeTypeExpression> _sink = new List<ValueOfSomeTypeExpression>(); private ConversionMethodScanner _conversionMethodScanner; } public enum ValueOfSomeTypeExpressionRoot { Left, Right } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.UIElement3D.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows { abstract public partial class UIElement3D : System.Windows.Media.Media3D.Visual3D, IInputElement { #region Methods and constructors public void AddHandler(RoutedEvent routedEvent, Delegate handler) { } public void AddHandler(RoutedEvent routedEvent, Delegate handler, bool handledEventsToo) { } public void AddToEventRoute(EventRoute route, RoutedEventArgs e) { } public bool CaptureMouse() { return default(bool); } public bool CaptureStylus() { return default(bool); } public bool CaptureTouch(System.Windows.Input.TouchDevice touchDevice) { return default(bool); } public bool Focus() { return default(bool); } protected internal DependencyObject GetUIParentCore() { return default(DependencyObject); } public void InvalidateModel() { } public virtual new bool MoveFocus(System.Windows.Input.TraversalRequest request) { return default(bool); } protected virtual new void OnAccessKey(System.Windows.Input.AccessKeyEventArgs e) { } protected virtual new System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected internal virtual new void OnDragEnter(DragEventArgs e) { } protected internal virtual new void OnDragLeave(DragEventArgs e) { } protected internal virtual new void OnDragOver(DragEventArgs e) { } protected internal virtual new void OnDrop(DragEventArgs e) { } protected internal virtual new void OnGiveFeedback(GiveFeedbackEventArgs e) { } protected virtual new void OnGotFocus(RoutedEventArgs e) { } protected internal virtual new void OnGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { } protected internal virtual new void OnGotMouseCapture(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnGotStylusCapture(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnGotTouchCapture(System.Windows.Input.TouchEventArgs e) { } protected virtual new void OnIsKeyboardFocusedChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsMouseCapturedChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsMouseCaptureWithinChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsMouseDirectlyOverChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsStylusCapturedChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsStylusCaptureWithinChanged(DependencyPropertyChangedEventArgs e) { } protected virtual new void OnIsStylusDirectlyOverChanged(DependencyPropertyChangedEventArgs e) { } protected internal virtual new void OnKeyDown(System.Windows.Input.KeyEventArgs e) { } protected internal virtual new void OnKeyUp(System.Windows.Input.KeyEventArgs e) { } protected virtual new void OnLostFocus(RoutedEventArgs e) { } protected internal virtual new void OnLostKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { } protected internal virtual new void OnLostMouseCapture(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnLostStylusCapture(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnLostTouchCapture(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnMouseDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseEnter(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnMouseLeave(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseMove(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseRightButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnMouseWheel(System.Windows.Input.MouseWheelEventArgs e) { } protected internal virtual new void OnPreviewDragEnter(DragEventArgs e) { } protected internal virtual new void OnPreviewDragLeave(DragEventArgs e) { } protected internal virtual new void OnPreviewDragOver(DragEventArgs e) { } protected internal virtual new void OnPreviewDrop(DragEventArgs e) { } protected internal virtual new void OnPreviewGiveFeedback(GiveFeedbackEventArgs e) { } protected internal virtual new void OnPreviewGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { } protected internal virtual new void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e) { } protected internal virtual new void OnPreviewKeyUp(System.Windows.Input.KeyEventArgs e) { } protected internal virtual new void OnPreviewLostKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { } protected internal virtual new void OnPreviewMouseDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseMove(System.Windows.Input.MouseEventArgs e) { } protected internal virtual new void OnPreviewMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseRightButtonUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseUp(System.Windows.Input.MouseButtonEventArgs e) { } protected internal virtual new void OnPreviewMouseWheel(System.Windows.Input.MouseWheelEventArgs e) { } protected internal virtual new void OnPreviewQueryContinueDrag(QueryContinueDragEventArgs e) { } protected internal virtual new void OnPreviewStylusButtonDown(System.Windows.Input.StylusButtonEventArgs e) { } protected internal virtual new void OnPreviewStylusButtonUp(System.Windows.Input.StylusButtonEventArgs e) { } protected internal virtual new void OnPreviewStylusDown(System.Windows.Input.StylusDownEventArgs e) { } protected internal virtual new void OnPreviewStylusInAirMove(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewStylusInRange(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewStylusMove(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewStylusOutOfRange(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewStylusSystemGesture(System.Windows.Input.StylusSystemGestureEventArgs e) { } protected internal virtual new void OnPreviewStylusUp(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { } protected internal virtual new void OnPreviewTouchDown(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnPreviewTouchMove(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnPreviewTouchUp(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnQueryContinueDrag(QueryContinueDragEventArgs e) { } protected internal virtual new void OnQueryCursor(System.Windows.Input.QueryCursorEventArgs e) { } protected internal virtual new void OnStylusButtonDown(System.Windows.Input.StylusButtonEventArgs e) { } protected internal virtual new void OnStylusButtonUp(System.Windows.Input.StylusButtonEventArgs e) { } protected internal virtual new void OnStylusDown(System.Windows.Input.StylusDownEventArgs e) { } protected internal virtual new void OnStylusEnter(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusInAirMove(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusInRange(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusLeave(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusMove(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusOutOfRange(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnStylusSystemGesture(System.Windows.Input.StylusSystemGestureEventArgs e) { } protected internal virtual new void OnStylusUp(System.Windows.Input.StylusEventArgs e) { } protected internal virtual new void OnTextInput(System.Windows.Input.TextCompositionEventArgs e) { } protected internal virtual new void OnTouchDown(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnTouchEnter(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnTouchLeave(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnTouchMove(System.Windows.Input.TouchEventArgs e) { } protected internal virtual new void OnTouchUp(System.Windows.Input.TouchEventArgs e) { } protected virtual new void OnUpdateModel() { } protected internal override void OnVisualParentChanged(DependencyObject oldParent) { } public virtual new DependencyObject PredictFocus(System.Windows.Input.FocusNavigationDirection direction) { return default(DependencyObject); } public void RaiseEvent(RoutedEventArgs e) { } public void ReleaseAllTouchCaptures() { } public void ReleaseMouseCapture() { } public void ReleaseStylusCapture() { } public bool ReleaseTouchCapture(System.Windows.Input.TouchDevice touchDevice) { return default(bool); } public void RemoveHandler(RoutedEvent routedEvent, Delegate handler) { } public bool ShouldSerializeCommandBindings() { return default(bool); } public bool ShouldSerializeInputBindings() { return default(bool); } protected UIElement3D() { } #endregion #region Properties and indexers public bool AllowDrop { get { return default(bool); } set { } } public bool AreAnyTouchesCaptured { get { return default(bool); } } public bool AreAnyTouchesCapturedWithin { get { return default(bool); } } public bool AreAnyTouchesDirectlyOver { get { return default(bool); } } public bool AreAnyTouchesOver { get { return default(bool); } } public System.Windows.Input.CommandBindingCollection CommandBindings { get { return default(System.Windows.Input.CommandBindingCollection); } } public bool Focusable { get { return default(bool); } set { } } public System.Windows.Input.InputBindingCollection InputBindings { get { return default(System.Windows.Input.InputBindingCollection); } } public bool IsEnabled { get { return default(bool); } set { } } protected virtual new bool IsEnabledCore { get { return default(bool); } } public bool IsFocused { get { return default(bool); } } public bool IsHitTestVisible { get { return default(bool); } set { } } public bool IsInputMethodEnabled { get { return default(bool); } } public bool IsKeyboardFocused { get { return default(bool); } } public bool IsKeyboardFocusWithin { get { return default(bool); } } public bool IsMouseCaptured { get { return default(bool); } } public bool IsMouseCaptureWithin { get { return default(bool); } } public bool IsMouseDirectlyOver { get { return default(bool); } } public bool IsMouseOver { get { return default(bool); } } public bool IsStylusCaptured { get { return default(bool); } } public bool IsStylusCaptureWithin { get { return default(bool); } } public bool IsStylusDirectlyOver { get { return default(bool); } } public bool IsStylusOver { get { return default(bool); } } public bool IsVisible { get { return default(bool); } } public IEnumerable<System.Windows.Input.TouchDevice> TouchesCaptured { get { return default(IEnumerable<System.Windows.Input.TouchDevice>); } } public IEnumerable<System.Windows.Input.TouchDevice> TouchesCapturedWithin { get { return default(IEnumerable<System.Windows.Input.TouchDevice>); } } public IEnumerable<System.Windows.Input.TouchDevice> TouchesDirectlyOver { get { return default(IEnumerable<System.Windows.Input.TouchDevice>); } } public IEnumerable<System.Windows.Input.TouchDevice> TouchesOver { get { return default(IEnumerable<System.Windows.Input.TouchDevice>); } } public Visibility Visibility { get { return default(Visibility); } set { } } #endregion #region Events public event DragEventHandler DragEnter { add { } remove { } } public event DragEventHandler DragLeave { add { } remove { } } public event DragEventHandler DragOver { add { } remove { } } public event DragEventHandler Drop { add { } remove { } } public event DependencyPropertyChangedEventHandler FocusableChanged { add { } remove { } } public event GiveFeedbackEventHandler GiveFeedback { add { } remove { } } public event RoutedEventHandler GotFocus { add { } remove { } } public event System.Windows.Input.KeyboardFocusChangedEventHandler GotKeyboardFocus { add { } remove { } } public event System.Windows.Input.MouseEventHandler GotMouseCapture { add { } remove { } } public event System.Windows.Input.StylusEventHandler GotStylusCapture { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> GotTouchCapture { add { } remove { } } public event DependencyPropertyChangedEventHandler IsEnabledChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsHitTestVisibleChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsKeyboardFocusedChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsKeyboardFocusWithinChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsMouseCapturedChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsMouseCaptureWithinChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsMouseDirectlyOverChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsStylusCapturedChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsStylusCaptureWithinChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsStylusDirectlyOverChanged { add { } remove { } } public event DependencyPropertyChangedEventHandler IsVisibleChanged { add { } remove { } } public event System.Windows.Input.KeyEventHandler KeyDown { add { } remove { } } public event System.Windows.Input.KeyEventHandler KeyUp { add { } remove { } } public event RoutedEventHandler LostFocus { add { } remove { } } public event System.Windows.Input.KeyboardFocusChangedEventHandler LostKeyboardFocus { add { } remove { } } public event System.Windows.Input.MouseEventHandler LostMouseCapture { add { } remove { } } public event System.Windows.Input.StylusEventHandler LostStylusCapture { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> LostTouchCapture { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseDown { add { } remove { } } public event System.Windows.Input.MouseEventHandler MouseEnter { add { } remove { } } public event System.Windows.Input.MouseEventHandler MouseLeave { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseLeftButtonDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseLeftButtonUp { add { } remove { } } public event System.Windows.Input.MouseEventHandler MouseMove { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseRightButtonDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseRightButtonUp { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler MouseUp { add { } remove { } } public event System.Windows.Input.MouseWheelEventHandler MouseWheel { add { } remove { } } public event DragEventHandler PreviewDragEnter { add { } remove { } } public event DragEventHandler PreviewDragLeave { add { } remove { } } public event DragEventHandler PreviewDragOver { add { } remove { } } public event DragEventHandler PreviewDrop { add { } remove { } } public event GiveFeedbackEventHandler PreviewGiveFeedback { add { } remove { } } public event System.Windows.Input.KeyboardFocusChangedEventHandler PreviewGotKeyboardFocus { add { } remove { } } public event System.Windows.Input.KeyEventHandler PreviewKeyDown { add { } remove { } } public event System.Windows.Input.KeyEventHandler PreviewKeyUp { add { } remove { } } public event System.Windows.Input.KeyboardFocusChangedEventHandler PreviewLostKeyboardFocus { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseLeftButtonDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseLeftButtonUp { add { } remove { } } public event System.Windows.Input.MouseEventHandler PreviewMouseMove { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseRightButtonDown { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseRightButtonUp { add { } remove { } } public event System.Windows.Input.MouseButtonEventHandler PreviewMouseUp { add { } remove { } } public event System.Windows.Input.MouseWheelEventHandler PreviewMouseWheel { add { } remove { } } public event QueryContinueDragEventHandler PreviewQueryContinueDrag { add { } remove { } } public event System.Windows.Input.StylusButtonEventHandler PreviewStylusButtonDown { add { } remove { } } public event System.Windows.Input.StylusButtonEventHandler PreviewStylusButtonUp { add { } remove { } } public event System.Windows.Input.StylusDownEventHandler PreviewStylusDown { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusInAirMove { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusInRange { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusMove { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusOutOfRange { add { } remove { } } public event System.Windows.Input.StylusSystemGestureEventHandler PreviewStylusSystemGesture { add { } remove { } } public event System.Windows.Input.StylusEventHandler PreviewStylusUp { add { } remove { } } public event System.Windows.Input.TextCompositionEventHandler PreviewTextInput { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> PreviewTouchDown { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> PreviewTouchMove { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> PreviewTouchUp { add { } remove { } } public event QueryContinueDragEventHandler QueryContinueDrag { add { } remove { } } public event System.Windows.Input.QueryCursorEventHandler QueryCursor { add { } remove { } } public event System.Windows.Input.StylusButtonEventHandler StylusButtonDown { add { } remove { } } public event System.Windows.Input.StylusButtonEventHandler StylusButtonUp { add { } remove { } } public event System.Windows.Input.StylusDownEventHandler StylusDown { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusEnter { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusInAirMove { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusInRange { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusLeave { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusMove { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusOutOfRange { add { } remove { } } public event System.Windows.Input.StylusSystemGestureEventHandler StylusSystemGesture { add { } remove { } } public event System.Windows.Input.StylusEventHandler StylusUp { add { } remove { } } public event System.Windows.Input.TextCompositionEventHandler TextInput { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchDown { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchEnter { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchLeave { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchMove { add { } remove { } } public event EventHandler<System.Windows.Input.TouchEventArgs> TouchUp { add { } remove { } } #endregion #region Fields public readonly static DependencyProperty AllowDropProperty; public readonly static DependencyProperty AreAnyTouchesCapturedProperty; public readonly static DependencyProperty AreAnyTouchesCapturedWithinProperty; public readonly static DependencyProperty AreAnyTouchesDirectlyOverProperty; public readonly static DependencyProperty AreAnyTouchesOverProperty; public readonly static RoutedEvent DragEnterEvent; public readonly static RoutedEvent DragLeaveEvent; public readonly static RoutedEvent DragOverEvent; public readonly static RoutedEvent DropEvent; public readonly static DependencyProperty FocusableProperty; public readonly static RoutedEvent GiveFeedbackEvent; public readonly static RoutedEvent GotFocusEvent; public readonly static RoutedEvent GotKeyboardFocusEvent; public readonly static RoutedEvent GotMouseCaptureEvent; public readonly static RoutedEvent GotStylusCaptureEvent; public readonly static RoutedEvent GotTouchCaptureEvent; public readonly static DependencyProperty IsEnabledProperty; public readonly static DependencyProperty IsFocusedProperty; public readonly static DependencyProperty IsHitTestVisibleProperty; public readonly static DependencyProperty IsKeyboardFocusedProperty; public readonly static DependencyProperty IsKeyboardFocusWithinProperty; public readonly static DependencyProperty IsMouseCapturedProperty; public readonly static DependencyProperty IsMouseCaptureWithinProperty; public readonly static DependencyProperty IsMouseDirectlyOverProperty; public readonly static DependencyProperty IsMouseOverProperty; public readonly static DependencyProperty IsStylusCapturedProperty; public readonly static DependencyProperty IsStylusCaptureWithinProperty; public readonly static DependencyProperty IsStylusDirectlyOverProperty; public readonly static DependencyProperty IsStylusOverProperty; public readonly static DependencyProperty IsVisibleProperty; public readonly static RoutedEvent KeyDownEvent; public readonly static RoutedEvent KeyUpEvent; public readonly static RoutedEvent LostFocusEvent; public readonly static RoutedEvent LostKeyboardFocusEvent; public readonly static RoutedEvent LostMouseCaptureEvent; public readonly static RoutedEvent LostStylusCaptureEvent; public readonly static RoutedEvent LostTouchCaptureEvent; public readonly static RoutedEvent MouseDownEvent; public readonly static RoutedEvent MouseEnterEvent; public readonly static RoutedEvent MouseLeaveEvent; public readonly static RoutedEvent MouseLeftButtonDownEvent; public readonly static RoutedEvent MouseLeftButtonUpEvent; public readonly static RoutedEvent MouseMoveEvent; public readonly static RoutedEvent MouseRightButtonDownEvent; public readonly static RoutedEvent MouseRightButtonUpEvent; public readonly static RoutedEvent MouseUpEvent; public readonly static RoutedEvent MouseWheelEvent; public readonly static RoutedEvent PreviewDragEnterEvent; public readonly static RoutedEvent PreviewDragLeaveEvent; public readonly static RoutedEvent PreviewDragOverEvent; public readonly static RoutedEvent PreviewDropEvent; public readonly static RoutedEvent PreviewGiveFeedbackEvent; public readonly static RoutedEvent PreviewGotKeyboardFocusEvent; public readonly static RoutedEvent PreviewKeyDownEvent; public readonly static RoutedEvent PreviewKeyUpEvent; public readonly static RoutedEvent PreviewLostKeyboardFocusEvent; public readonly static RoutedEvent PreviewMouseDownEvent; public readonly static RoutedEvent PreviewMouseLeftButtonDownEvent; public readonly static RoutedEvent PreviewMouseLeftButtonUpEvent; public readonly static RoutedEvent PreviewMouseMoveEvent; public readonly static RoutedEvent PreviewMouseRightButtonDownEvent; public readonly static RoutedEvent PreviewMouseRightButtonUpEvent; public readonly static RoutedEvent PreviewMouseUpEvent; public readonly static RoutedEvent PreviewMouseWheelEvent; public readonly static RoutedEvent PreviewQueryContinueDragEvent; public readonly static RoutedEvent PreviewStylusButtonDownEvent; public readonly static RoutedEvent PreviewStylusButtonUpEvent; public readonly static RoutedEvent PreviewStylusDownEvent; public readonly static RoutedEvent PreviewStylusInAirMoveEvent; public readonly static RoutedEvent PreviewStylusInRangeEvent; public readonly static RoutedEvent PreviewStylusMoveEvent; public readonly static RoutedEvent PreviewStylusOutOfRangeEvent; public readonly static RoutedEvent PreviewStylusSystemGestureEvent; public readonly static RoutedEvent PreviewStylusUpEvent; public readonly static RoutedEvent PreviewTextInputEvent; public readonly static RoutedEvent PreviewTouchDownEvent; public readonly static RoutedEvent PreviewTouchMoveEvent; public readonly static RoutedEvent PreviewTouchUpEvent; public readonly static RoutedEvent QueryContinueDragEvent; public readonly static RoutedEvent QueryCursorEvent; public readonly static RoutedEvent StylusButtonDownEvent; public readonly static RoutedEvent StylusButtonUpEvent; public readonly static RoutedEvent StylusDownEvent; public readonly static RoutedEvent StylusEnterEvent; public readonly static RoutedEvent StylusInAirMoveEvent; public readonly static RoutedEvent StylusInRangeEvent; public readonly static RoutedEvent StylusLeaveEvent; public readonly static RoutedEvent StylusMoveEvent; public readonly static RoutedEvent StylusOutOfRangeEvent; public readonly static RoutedEvent StylusSystemGestureEvent; public readonly static RoutedEvent StylusUpEvent; public readonly static RoutedEvent TextInputEvent; public readonly static RoutedEvent TouchDownEvent; public readonly static RoutedEvent TouchEnterEvent; public readonly static RoutedEvent TouchLeaveEvent; public readonly static RoutedEvent TouchMoveEvent; public readonly static RoutedEvent TouchUpEvent; public readonly static DependencyProperty VisibilityProperty; #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.Reflection; using System.Threading; using System.Xml; namespace System.Runtime.Serialization.Json { internal class JsonCollectionDataContract : JsonDataContract { private JsonCollectionDataContractCriticalHelper _helper; public JsonCollectionDataContract(CollectionDataContract traditionalDataContract) : base(new JsonCollectionDataContractCriticalHelper(traditionalDataContract)) { _helper = base.Helper as JsonCollectionDataContractCriticalHelper; } internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate { get { if (_helper.JsonFormatReaderDelegate == null) { lock (this) { if (_helper.JsonFormatReaderDelegate == null) { JsonFormatCollectionReaderDelegate tempDelegate; if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { tempDelegate = new ReflectionJsonCollectionReader().ReflectionReadCollection; } #if uapaot else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract)?.CollectionReaderDelegate; tempDelegate = tempDelegate ?? new ReflectionJsonCollectionReader().ReflectionReadCollection; if (tempDelegate == null) throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString())); } #endif else { #if uapaot tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).CollectionReaderDelegate; #else tempDelegate = new JsonFormatReaderGenerator().GenerateCollectionReader(TraditionalCollectionDataContract); #endif } Interlocked.MemoryBarrier(); _helper.JsonFormatReaderDelegate = tempDelegate; } } } return _helper.JsonFormatReaderDelegate; } } internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate { get { if (_helper.JsonFormatGetOnlyReaderDelegate == null) { lock (this) { if (_helper.JsonFormatGetOnlyReaderDelegate == null) { CollectionKind kind = this.TraditionalCollectionDataContract.Kind; if (this.TraditionalDataContract.UnderlyingType.IsInterface && (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)) { throw new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(this.TraditionalDataContract.UnderlyingType))); } JsonFormatGetOnlyCollectionReaderDelegate tempDelegate; if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { tempDelegate = new ReflectionJsonCollectionReader().ReflectionReadGetOnlyCollection; } #if uapaot else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract)?.GetOnlyCollectionReaderDelegate; tempDelegate = tempDelegate ?? new ReflectionJsonCollectionReader().ReflectionReadGetOnlyCollection; if (tempDelegate == null) throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString())); } #endif else { #if uapaot tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).GetOnlyCollectionReaderDelegate; #else tempDelegate = new JsonFormatReaderGenerator().GenerateGetOnlyCollectionReader(TraditionalCollectionDataContract); #endif } Interlocked.MemoryBarrier(); _helper.JsonFormatGetOnlyReaderDelegate = tempDelegate; } } } return _helper.JsonFormatGetOnlyReaderDelegate; } } internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate { get { if (_helper.JsonFormatWriterDelegate == null) { lock (this) { if (_helper.JsonFormatWriterDelegate == null) { JsonFormatCollectionWriterDelegate tempDelegate; if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { tempDelegate = new ReflectionJsonFormatWriter().ReflectionWriteCollection; } #if uapaot else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract)?.CollectionWriterDelegate; tempDelegate = tempDelegate ?? new ReflectionJsonFormatWriter().ReflectionWriteCollection; if (tempDelegate == null) throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString())); } #endif else { #if uapaot tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).CollectionWriterDelegate; #else tempDelegate = new JsonFormatWriterGenerator().GenerateCollectionWriter(TraditionalCollectionDataContract); #endif } Interlocked.MemoryBarrier(); _helper.JsonFormatWriterDelegate = tempDelegate; } } } return _helper.JsonFormatWriterDelegate; } } private CollectionDataContract TraditionalCollectionDataContract => _helper.TraditionalCollectionDataContract; public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { jsonReader.Read(); object o = null; if (context.IsGetOnlyCollection) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; JsonFormatGetOnlyReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract); } else { o = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract); } jsonReader.ReadEndElement(); return o; } public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract); } private class JsonCollectionDataContractCriticalHelper : JsonDataContractCriticalHelper { private JsonFormatCollectionReaderDelegate _jsonFormatReaderDelegate; private JsonFormatGetOnlyCollectionReaderDelegate _jsonFormatGetOnlyReaderDelegate; private JsonFormatCollectionWriterDelegate _jsonFormatWriterDelegate; private CollectionDataContract _traditionalCollectionDataContract; public JsonCollectionDataContractCriticalHelper(CollectionDataContract traditionalDataContract) : base(traditionalDataContract) { _traditionalCollectionDataContract = traditionalDataContract; } internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate { get { return _jsonFormatReaderDelegate; } set { _jsonFormatReaderDelegate = value; } } internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate { get { return _jsonFormatGetOnlyReaderDelegate; } set { _jsonFormatGetOnlyReaderDelegate = value; } } internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate { get { return _jsonFormatWriterDelegate; } set { _jsonFormatWriterDelegate = value; } } internal CollectionDataContract TraditionalCollectionDataContract { get { return _traditionalCollectionDataContract; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using NDesk.Options; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Util; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("rcheckin")] [RequiresValidGitRepository] public class Rcheckin : GitTfsCommand { private readonly TextWriter _stdout; private readonly CheckinOptions _checkinOptions; private readonly CommitSpecificCheckinOptionsFactory _checkinOptionsFactory; private readonly TfsWriter _writer; private readonly Globals _globals; private readonly AuthorsFile _authors; private bool AutoRebase { get; set; } private bool ForceCheckin { get; set; } public Rcheckin(TextWriter stdout, CheckinOptions checkinOptions, TfsWriter writer, Globals globals, AuthorsFile authors) { _stdout = stdout; _checkinOptions = checkinOptions; _checkinOptionsFactory = new CommitSpecificCheckinOptionsFactory(_stdout, globals, authors); _writer = writer; _globals = globals; _authors = authors; } public OptionSet OptionSet { get { return new OptionSet { {"a|autorebase", "Continue and rebase if new TFS changesets found", v => AutoRebase = v != null}, {"ignore-merge", "Force check in ignoring parent tfs branches in merge commits", v => ForceCheckin = v != null}, }.Merge(_checkinOptions.OptionSet); } } // uses rebase and works only with HEAD public int Run() { _globals.WarnOnGitVersion(_stdout); if (_globals.Repository.IsBare) throw new GitTfsException("error: you should specify the local branch to checkin for a bare repository."); return _writer.Write("HEAD", PerformRCheckin); } // uses rebase and works only with HEAD in a none bare repository public int Run(string localBranch) { _globals.WarnOnGitVersion(_stdout); if (!_globals.Repository.IsBare) throw new GitTfsException("error: This syntax with one parameter is only allowed in bare repository."); _authors.Parse(null, _globals.GitDir); return _writer.Write(GitRepository.ShortToLocalName(localBranch), PerformRCheckin); } private int PerformRCheckin(TfsChangesetInfo parentChangeset, string refToCheckin) { if (_globals.Repository.IsBare) AutoRebase = false; if (_globals.Repository.WorkingCopyHasUnstagedOrUncommitedChanges) { throw new GitTfsException("error: You have local changes; rebase-workflow checkin only possible with clean working directory.") .WithRecommendation("Try 'git stash' to stash your local changes and checkin again."); } // get latest changes from TFS to minimize possibility of late conflict _stdout.WriteLine("Fetching changes from TFS to minimize possibility of late conflict..."); parentChangeset.Remote.Fetch(); if (parentChangeset.ChangesetId != parentChangeset.Remote.MaxChangesetId) { if (AutoRebase) { _globals.Repository.CommandNoisy("rebase", "--preserve-merges", parentChangeset.Remote.RemoteRef); parentChangeset = _globals.Repository.GetTfsCommit(parentChangeset.Remote.MaxCommitHash); } else { if (_globals.Repository.IsBare) _globals.Repository.UpdateRef(refToCheckin, parentChangeset.Remote.MaxCommitHash); throw new GitTfsException("error: New TFS changesets were found.") .WithRecommendation("Try to rebase HEAD onto latest TFS checkin and repeat rcheckin or alternatively checkins"); } } IEnumerable<GitCommit> commitsToCheckin = _globals.Repository.FindParentCommits(refToCheckin, parentChangeset.Remote.MaxCommitHash); Trace.WriteLine("Commit to checkin count:" + commitsToCheckin.Count()); if (!commitsToCheckin.Any()) throw new GitTfsException("error: latest TFS commit should be parent of commits being checked in"); SetupMetadataExport(parentChangeset.Remote); return _PerformRCheckinQuick(parentChangeset, refToCheckin, commitsToCheckin); } private void SetupMetadataExport(IGitTfsRemote remote) { var exportInitializer = new ExportMetadatasInitializer(_globals); var shouldExport = _globals.Repository.GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true"; exportInitializer.InitializeRemote(remote, shouldExport); } private int _PerformRCheckinQuick(TfsChangesetInfo parentChangeset, string refToCheckin, IEnumerable<GitCommit> commitsToCheckin) { var tfsRemote = parentChangeset.Remote; string currentParent = parentChangeset.Remote.MaxCommitHash; int newChangesetId = 0; foreach (var commit in commitsToCheckin) { var message = BuildCommitMessage(commit, !_checkinOptions.NoGenerateCheckinComment, currentParent); string target = commit.Sha; var parents = commit.Parents.Where(c => c.Sha != currentParent).ToArray(); string tfsRepositoryPathOfMergedBranch = FindTfsRepositoryPathOfMergedBranch(tfsRemote, parents, target); var commitSpecificCheckinOptions = _checkinOptionsFactory.BuildCommitSpecificCheckinOptions(_checkinOptions, message, commit); _stdout.WriteLine("Starting checkin of {0} '{1}'", target.Substring(0, 8), commitSpecificCheckinOptions.CheckinComment); try { newChangesetId = tfsRemote.Checkin(target, currentParent, parentChangeset, commitSpecificCheckinOptions, tfsRepositoryPathOfMergedBranch); var fetchResult = tfsRemote.FetchWithMerge(newChangesetId, false, parents.Select(c=>c.Sha).ToArray()); if (fetchResult.NewChangesetCount != 1) { var lastCommit = _globals.Repository.FindCommitHashByChangesetId(newChangesetId); RebaseOnto(lastCommit, target); if (AutoRebase) tfsRemote.Repository.CommandNoisy("rebase", "--preserve-merges", tfsRemote.RemoteRef); else throw new GitTfsException("error: New TFS changesets were found. Rcheckin was not finished."); } currentParent = target; parentChangeset = new TfsChangesetInfo {ChangesetId = newChangesetId, GitCommit = tfsRemote.MaxCommitHash, Remote = tfsRemote}; _stdout.WriteLine("Done with {0}.", target); } catch (Exception) { if (newChangesetId != 0) { var lastCommit = _globals.Repository.FindCommitHashByChangesetId(newChangesetId); RebaseOnto(lastCommit, currentParent); } throw; } } if (_globals.Repository.IsBare) _globals.Repository.UpdateRef(refToCheckin, tfsRemote.MaxCommitHash); else _globals.Repository.ResetHard(tfsRemote.MaxCommitHash); _stdout.WriteLine("No more to rcheckin."); Trace.WriteLine("Cleaning..."); tfsRemote.CleanupWorkspaceDirectory(); return GitTfsExitCodes.OK; } public string BuildCommitMessage(GitCommit commit, bool generateCheckinComment, string latest) { return generateCheckinComment ? _globals.Repository.GetCommitMessage(commit.Sha, latest) : _globals.Repository.GetCommit(commit.Sha).Message; } private string FindTfsRepositoryPathOfMergedBranch(IGitTfsRemote remoteToCheckin, GitCommit[] gitParents, string target) { if (gitParents.Length != 0) { _stdout.WriteLine("Working on the merge commit: " + target); if (gitParents.Length > 1) _stdout.WriteLine("warning: only 1 parent is supported by TFS for a merge changeset. The other parents won't be materialized in the TFS merge!"); foreach (var gitParent in gitParents) { var tfsCommit = _globals.Repository.GetTfsCommit(gitParent); if (tfsCommit != null) return tfsCommit.Remote.TfsRepositoryPath; var lastCheckinCommit = _globals.Repository.GetLastParentTfsCommits(gitParent.Sha).FirstOrDefault(); if (lastCheckinCommit != null) { if(!ForceCheckin && lastCheckinCommit.Remote.Id != remoteToCheckin.Id) throw new GitTfsException("error: the merged branch '" + lastCheckinCommit.Remote.Id + "' is a TFS tracked branch ("+lastCheckinCommit.Remote.TfsRepositoryPath + ") with some commits not checked in.\nIn this case, the local merge won't be materialized as a merge in tfs...") .WithRecommendation("check in all the commits of the tfs merged branch in TFS before trying to check in a merge commit", "use --ignore-merge option to ignore merged TFS branch and check in commit as a normal changeset (not a merge)."); } else { _stdout.WriteLine("warning: the parent " + gitParent + " does not belong to a TFS tracked branch (not checked in TFS) and will be ignored!"); } } } return null; } public void RebaseOnto(string newBaseCommit, string oldBaseCommit) { _globals.Repository.CommandNoisy("rebase", "--preserve-merges", "--onto", newBaseCommit, oldBaseCommit); } } }
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. 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. * */ #endregion using System; using System.Globalization; using System.Reflection; using Quartz.Util; namespace Quartz.Impl { /// <summary> /// Conveys the detail properties of a given job instance. /// </summary> /// <remarks> /// Quartz does not store an actual instance of a <see cref="IJob" /> type, but /// instead allows you to define an instance of one, through the use of a <see cref="IJobDetail" />. /// <para> /// <see cref="IJob" />s have a name and group associated with them, which /// should uniquely identify them within a single <see cref="IScheduler" />. /// </para> /// <para> /// <see cref="ITrigger" /> s are the 'mechanism' by which <see cref="IJob" /> s /// are scheduled. Many <see cref="ITrigger" /> s can point to the same <see cref="IJob" />, /// but a single <see cref="ITrigger" /> can only point to one <see cref="IJob" />. /// </para> /// </remarks> /// <seealso cref="IJob" /> /// <seealso cref="DisallowConcurrentExecutionAttribute"/> /// <seealso cref="PersistJobDataAfterExecutionAttribute"/> /// <seealso cref="JobDataMap"/> /// <seealso cref="ITrigger"/> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class JobDetailImpl : IJobDetail { private string name = null!; private string group = SchedulerConstants.DefaultGroup; private string? description; private JobDataMap jobDataMap = null!; private Type jobType = null!; [NonSerialized] // we have the key in string fields private JobKey key = null!; /// <summary> /// Create a <see cref="IJobDetail" /> with no specified name or group, and /// the default settings of all the other properties. /// <para> /// Note that the <see cref="Name" />,<see cref="Group" /> and /// <see cref="JobType" /> properties must be set before the job can be /// placed into a <see cref="IScheduler" />. /// </para> /// </summary> public JobDetailImpl() { // do nothing... } /// <summary> /// Create a <see cref="IJobDetail" /> with the given name, default group, and /// the default settings of all the other properties. /// If <see langword="null" />, SchedulerConstants.DefaultGroup will be used. /// </summary> /// <exception cref="ArgumentException"> /// If name is null or empty, or the group is an empty string. /// </exception> public JobDetailImpl(string name, Type jobType) : this(name, SchedulerConstants.DefaultGroup, jobType) { } /// <summary> /// Create a <see cref="IJobDetail" /> with the given name, and group, and /// the default settings of all the other properties. /// If <see langword="null" />, SchedulerConstants.DefaultGroup will be used. /// </summary> /// <exception cref="ArgumentException"> /// If name is null or empty, or the group is an empty string. /// </exception> public JobDetailImpl(string name, string group, Type jobType) { Name = name; Group = group; JobType = jobType; } /// <summary> /// Create a <see cref="IJobDetail" /> with the given name, and group, and /// the given settings of all the other properties. /// </summary> /// <param name="name">The name.</param> /// <param name="group">if <see langword="null" />, SchedulerConstants.DefaultGroup will be used.</param> /// <param name="jobType">Type of the job.</param> /// <param name="isDurable">if set to <c>true</c>, job will be durable.</param> /// <param name="requestsRecovery">if set to <c>true</c>, job will request recovery.</param> /// <exception cref="ArgumentException"> /// ArgumentException if name is null or empty, or the group is an empty string. /// </exception> public JobDetailImpl(string name, string group, Type jobType, bool isDurable, bool requestsRecovery) { Name = name; Group = group; JobType = jobType; Durable = isDurable; RequestsRecovery = requestsRecovery; } /// <summary> /// Get or sets the name of this <see cref="IJob" />. /// </summary> /// <exception cref="ArgumentException"> /// if name is null or empty. /// </exception> public string Name { get => name; set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Job name cannot be empty."); } name = value; } } /// <summary> /// Get or sets the group of this <see cref="IJob" />. /// If <see langword="null" />, <see cref="SchedulerConstants.DefaultGroup" /> will be used. /// </summary> /// <exception cref="ArgumentException"> /// If the group is an empty string. /// </exception> public string Group { get => group; set { if (value != null && value.Trim().Length == 0) { throw new ArgumentException("Group name cannot be empty."); } if (value == null) { value = SchedulerConstants.DefaultGroup; } group = value; } } /// <summary> /// Returns the 'full name' of the <see cref="ITrigger" /> in the format /// "group.name". /// </summary> public string FullName => group + "." + name; /// <summary> /// Gets the key. /// </summary> /// <value>The key.</value> public JobKey Key { get { if (key == null) { if (Name == null) { return null!; } key = new JobKey(Name, Group); } return key; } set { if (value is null) { throw new ArgumentNullException(nameof(value)); } Name = value.Name; Group = value.Group; key = value; } } /// <summary> /// Get or set the description given to the <see cref="IJob" /> instance by its /// creator (if any). /// </summary> /// <remarks> /// May be useful for remembering/displaying the purpose of the job, though the /// description has no meaning to Quartz. /// </remarks> public string? Description { get => description; set => description = value; } /// <summary> /// Get or sets the instance of <see cref="IJob" /> that will be executed. /// </summary> /// <exception cref="ArgumentException"> /// if jobType is null or the class is not a <see cref="IJob" />. /// </exception> public virtual Type JobType { get => jobType; set { if (value == null) { throw new ArgumentException("Job class cannot be null."); } if (!typeof(IJob).GetTypeInfo().IsAssignableFrom(value.GetTypeInfo())) { throw new ArgumentException("Job class must implement the Job interface."); } jobType = value; } } /// <summary> /// Get or set the <see cref="JobDataMap" /> that is associated with the <see cref="IJob" />. /// </summary> public virtual JobDataMap JobDataMap { get { if (jobDataMap == null) { jobDataMap = new JobDataMap(); } return jobDataMap; } set => jobDataMap = value; } /// <summary> /// Set whether or not the <see cref="IScheduler" /> should re-Execute /// the <see cref="IJob" /> if a 'recovery' or 'fail-over' situation is /// encountered. /// <para> /// If not explicitly set, the default value is <see langword="false" />. /// </para> /// </summary> /// <seealso cref="IJobExecutionContext.Recovering" /> public bool RequestsRecovery { set; get; } /// <summary> /// Whether or not the <see cref="IJob" /> should remain stored after it is /// orphaned (no <see cref="ITrigger" />s point to it). /// <para> /// If not explicitly set, the default value is <see langword="false" />. /// </para> /// </summary> /// <returns> /// <see langword="true" /> if the Job should remain persisted after /// being orphaned. /// </returns> public bool Durable { get; set; } /// <summary> /// Whether the associated Job class carries the <see cref="PersistJobDataAfterExecution" /> attribute. /// </summary> public virtual bool PersistJobDataAfterExecution => ObjectUtils.IsAttributePresent(jobType, typeof(PersistJobDataAfterExecutionAttribute)); /// <summary> /// Whether the associated Job class carries the <see cref="DisallowConcurrentExecutionAttribute" /> attribute. /// </summary> public virtual bool ConcurrentExecutionDisallowed => ObjectUtils.IsAttributePresent(jobType, typeof(DisallowConcurrentExecutionAttribute)); /// <summary> /// Validates whether the properties of the <see cref="IJobDetail" /> are /// valid for submission into a <see cref="IScheduler" />. /// </summary> public virtual void Validate() { if (name == null) { throw new SchedulerException("Job's name cannot be null"); } if (group == null) { throw new SchedulerException("Job's group cannot be null"); } if (jobType == null) { throw new SchedulerException("Job's class cannot be null"); } } /// <summary> /// Return a simple string representation of this object. /// </summary> public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "JobDetail '{0}': jobType: '{1} persistJobDataAfterExecution: {2} concurrentExecutionDisallowed: {3} isDurable: {4} requestsRecovers: {5}", FullName, JobType?.FullName, PersistJobDataAfterExecution, ConcurrentExecutionDisallowed, Durable, RequestsRecovery); } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> public virtual IJobDetail Clone() { JobDetailImpl copy; try { copy = (JobDetailImpl) MemberwiseClone(); if (jobDataMap != null) { copy.jobDataMap = (JobDataMap) jobDataMap.Clone(); } } catch (Exception) { throw new Exception("Not Cloneable."); } return copy; } /// <summary> /// Determines whether the specified detail is equal to this instance. /// </summary> /// <param name="detail">The detail to examine.</param> /// <returns> /// <c>true</c> if the specified detail is equal; otherwise, <c>false</c>. /// </returns> protected virtual bool IsEqual(JobDetailImpl detail) { //doesn't consider job's saved data, //durability etc return detail != null && detail.Name == Name && detail.Group == Group && detail.JobType == JobType; } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// <see langword="true"/> if the specified <see cref="T:System.Object"/> is equal to the /// current <see cref="T:System.Object"/>; otherwise, <see langword="false"/>. /// </returns> public override bool Equals(object? obj) { if (!(obj is JobDetailImpl jd)) { return false; } return IsEqual(jd); } /// <summary> /// Checks equality between given job detail and this instance. /// </summary> /// <param name="detail">The detail to compare this instance with.</param> /// <returns></returns> public virtual bool Equals(JobDetailImpl detail) { return IsEqual(detail); } /// <summary> /// Serves as a hash function for a particular type, suitable /// for use in hashing algorithms and data structures like a hash table. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return FullName.GetHashCode(); } public virtual JobBuilder GetJobBuilder() { JobBuilder b = JobBuilder.Create() .OfType(JobType) .RequestRecovery(RequestsRecovery) .StoreDurably(Durable) .UsingJobData(JobDataMap) .WithDescription(description) .WithIdentity(Key); return b; } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Composing; using Umbraco.Cms.Core.Configuration; using Umbraco.Cms.Core.Configuration.Grid; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Diagnostics; using Umbraco.Cms.Core.Dictionary; using Umbraco.Cms.Core.Editors; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Features; using Umbraco.Cms.Core.Handlers; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Install; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Logging; using Umbraco.Cms.Core.Mail; using Umbraco.Cms.Core.Manifest; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Core.PublishedCache.Internal; using Umbraco.Cms.Core.Routing; using Umbraco.Cms.Core.Runtime; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Sync; using Umbraco.Cms.Core.Telemetry; using Umbraco.Cms.Core.Templates; using Umbraco.Cms.Core.Web; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Extensions; namespace Umbraco.Cms.Core.DependencyInjection { public class UmbracoBuilder : IUmbracoBuilder { private readonly Dictionary<Type, ICollectionBuilder> _builders = new Dictionary<Type, ICollectionBuilder>(); public IServiceCollection Services { get; } public IConfiguration Config { get; } public TypeLoader TypeLoader { get; } /// <inheritdoc /> public ILoggerFactory BuilderLoggerFactory { get; } /// <inheritdoc /> public IHostingEnvironment BuilderHostingEnvironment { get; } public IProfiler Profiler { get; } public AppCaches AppCaches { get; } /// <summary> /// Initializes a new instance of the <see cref="UmbracoBuilder"/> class primarily for testing. /// </summary> public UmbracoBuilder(IServiceCollection services, IConfiguration config, TypeLoader typeLoader) : this(services, config, typeLoader, NullLoggerFactory.Instance, new NoopProfiler(), AppCaches.Disabled, null) { } /// <summary> /// Initializes a new instance of the <see cref="UmbracoBuilder"/> class. /// </summary> public UmbracoBuilder( IServiceCollection services, IConfiguration config, TypeLoader typeLoader, ILoggerFactory loggerFactory, IProfiler profiler, AppCaches appCaches, IHostingEnvironment hostingEnvironment) { Services = services; Config = config; BuilderLoggerFactory = loggerFactory; BuilderHostingEnvironment = hostingEnvironment; Profiler = profiler; AppCaches = appCaches; TypeLoader = typeLoader; AddCoreServices(); } /// <summary> /// Gets a collection builder (and registers the collection). /// </summary> /// <typeparam name="TBuilder">The type of the collection builder.</typeparam> /// <returns>The collection builder.</returns> public TBuilder WithCollectionBuilder<TBuilder>() where TBuilder : ICollectionBuilder, new() { Type typeOfBuilder = typeof(TBuilder); if (_builders.TryGetValue(typeOfBuilder, out ICollectionBuilder o)) { return (TBuilder)o; } var builder = new TBuilder(); _builders[typeOfBuilder] = builder; return builder; } public void Build() { foreach (ICollectionBuilder builder in _builders.Values) { builder.RegisterWith(Services); } _builders.Clear(); } private void AddCoreServices() { Services.AddSingleton(AppCaches); Services.AddSingleton(Profiler); // Register as singleton to allow injection everywhere. Services.AddSingleton<ServiceFactory>(p => p.GetService); Services.AddSingleton<IEventAggregator, EventAggregator>(); Services.AddLazySupport(); // Adds no-op registrations as many core services require these dependencies but these // dependencies cannot be fulfilled in the Core project Services.AddUnique<IMarchal, NoopMarchal>(); Services.AddUnique<IApplicationShutdownRegistry, NoopApplicationShutdownRegistry>(); Services.AddUnique<IMainDom, MainDom>(); Services.AddUnique<IMainDomLock, MainDomSemaphoreLock>(); Services.AddUnique<IIOHelper>(factory => { IHostingEnvironment hostingEnvironment = factory.GetRequiredService<IHostingEnvironment>(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return new IOHelperLinux(hostingEnvironment); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return new IOHelperOSX(hostingEnvironment); } return new IOHelperWindows(hostingEnvironment); }); Services.AddUnique(factory => factory.GetRequiredService<AppCaches>().RuntimeCache); Services.AddUnique(factory => factory.GetRequiredService<AppCaches>().RequestCache); Services.AddUnique<IProfilingLogger, ProfilingLogger>(); Services.AddUnique<IUmbracoVersion, UmbracoVersion>(); Services.AddUnique<IEntryAssemblyMetadata, EntryAssemblyMetadata>(); this.AddAllCoreCollectionBuilders(); this.AddNotificationHandler<UmbracoApplicationStartingNotification, EssentialDirectoryCreator>(); Services.AddSingleton<UmbracoRequestPaths>(); Services.AddSingleton<InstallStatusTracker>(); // by default, register a noop factory Services.AddUnique<IPublishedModelFactory, NoopPublishedModelFactory>(); Services.AddUnique<ICultureDictionaryFactory, DefaultCultureDictionaryFactory>(); Services.AddSingleton(f => f.GetRequiredService<ICultureDictionaryFactory>().CreateDictionary()); Services.AddSingleton<UriUtility>(); Services.AddUnique<IDashboardService, DashboardService>(); Services.AddUnique<IUserDataService, UserDataService>(); // will be injected in controllers when needed to invoke rest endpoints on Our Services.AddUnique<IInstallationService, InstallationService>(); Services.AddUnique<IUpgradeService, UpgradeService>(); // Grid config is not a real config file as we know them Services.AddUnique<IGridConfig, GridConfig>(); Services.AddUnique<IPublishedUrlProvider, UrlProvider>(); Services.AddUnique<ISiteDomainMapper, SiteDomainMapper>(); Services.AddSingleton<HtmlLocalLinkParser>(); Services.AddSingleton<HtmlImageSourceParser>(); Services.AddSingleton<HtmlUrlParser>(); // register properties fallback Services.AddUnique<IPublishedValueFallback, PublishedValueFallback>(); Services.AddSingleton<UmbracoFeatures>(); // register published router Services.AddUnique<IPublishedRouter, PublishedRouter>(); Services.AddUnique<IEventMessagesFactory, DefaultEventMessagesFactory>(); Services.AddUnique<IEventMessagesAccessor, HybridEventMessagesAccessor>(); Services.AddUnique<ITreeService, TreeService>(); Services.AddUnique<ISectionService, SectionService>(); Services.AddUnique<ISmsSender, NotImplementedSmsSender>(); Services.AddUnique<IEmailSender, NotImplementedEmailSender>(); Services.AddUnique<IDataValueEditorFactory, DataValueEditorFactory>(); // register distributed cache Services.AddUnique(f => new DistributedCache(f.GetRequiredService<IServerMessenger>(), f.GetRequiredService<CacheRefresherCollection>())); Services.AddUnique<ICacheRefresherNotificationFactory, CacheRefresherNotificationFactory>(); // register the http context and umbraco context accessors // we *should* use the HttpContextUmbracoContextAccessor, however there are cases when // we have no http context, eg when booting Umbraco or in background threads, so instead // let's use an hybrid accessor that can fall back to a ThreadStatic context. Services.AddUnique<IUmbracoContextAccessor, HybridUmbracoContextAccessor>(); Services.AddSingleton<LegacyPasswordSecurity>(); Services.AddSingleton<UserEditorAuthorizationHelper>(); Services.AddSingleton<ContentPermissions>(); Services.AddSingleton<MediaPermissions>(); Services.AddSingleton<PropertyEditorCollection>(); Services.AddSingleton<ParameterEditorCollection>(); // register a server registrar, by default it's the db registrar Services.AddUnique<IServerRoleAccessor>(f => { GlobalSettings globalSettings = f.GetRequiredService<IOptions<GlobalSettings>>().Value; var singleServer = globalSettings.DisableElectionForSingleServer; return singleServer ? (IServerRoleAccessor)new SingleServerRoleAccessor() : new ElectedServerRoleAccessor(f.GetRequiredService<IServerRegistrationService>()); }); // For Umbraco to work it must have the default IPublishedModelFactory // which may be replaced by models builder but the default is required to make plain old IPublishedContent // instances. Services.AddSingleton<IPublishedModelFactory>(factory => factory.CreateDefaultPublishedModelFactory()); Services .AddNotificationHandler<MemberGroupSavedNotification, PublicAccessHandler>() .AddNotificationHandler<MemberGroupDeletedNotification, PublicAccessHandler>(); Services.AddSingleton<ISyncBootStateAccessor, NonRuntimeLevelBootStateAccessor>(); // register a basic/noop published snapshot service to be replaced Services.AddSingleton<IPublishedSnapshotService, InternalPublishedSnapshotService>(); // Register ValueEditorCache used for validation Services.AddSingleton<IValueEditorCache, ValueEditorCache>(); // Register telemetry service used to gather data about installed packages Services.AddUnique<ISiteIdentifierService, SiteIdentifierService>(); Services.AddUnique<ITelemetryService, TelemetryService>(); // Register a noop IHtmlSanitizer to be replaced Services.AddUnique<IHtmlSanitizer, NoopHtmlSanitizer>(); } } }
using System; using System.Diagnostics.CodeAnalysis; using ToolKit.DirectoryServices; using ToolKit.DirectoryServices.ActiveDirectory; using ToolKit.DirectoryServices.ServiceInterfaces; using Xunit; namespace UnitTests.DirectoryServices.ActiveDirectory { [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Test Suites do not need XML Documentation.")] [SuppressMessage("ReSharper", "StringLiteralTypo", Justification = "Contains Many Acroymns")] [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Contains Many Acroymns")] public class ActiveDirectoryCommonFiltersTest { [Fact] public void Computers() { // Arrange const string expected = "(objectCategory=computer)"; // Act var filter = ActiveDirectoryCommonFilters.Computers; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Computers_DomainControllers() { // Arrange const string expected = "(&(objectCategory=computer)" + "(userAccountControl:1.2.840.113556.1.4.803:=8192))"; // Act var filter = ActiveDirectoryCommonFilters.DomainControllers; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Computers_Name_Containing() { // Arrange const string expected = "(&(objectCategory=computer)(name=*ex*))"; // Act var filter = ActiveDirectoryCommonFilters.ComputersNameContaining("ex"); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Computers_With_Operating_System() { // Arrange const string expected = "(&(objectCategory=computer)(operatingSystem=*vista*))"; // Act var filter = ActiveDirectoryCommonFilters.ComputersWithOS("vista"); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Computers_With_Operating_System_And_Service_Pack() { // Arrange const string expected = "(&(&(objectCategory=computer)" + "(operatingSystem=*server*))" + "(operatingSystemServicePack=*1*))"; // Act var filter = ActiveDirectoryCommonFilters.ComputersWithOsAndSp("server", 1); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Constructor_Should_ThrowInvalidOperationException_When_ProvideNullValue() { // Arrange const ADS_USER_FLAG invalid = (ADS_USER_FLAG)99; // Act and Assert Assert.Throws<InvalidOperationException>( () => _ = ActiveDirectoryCommonFilters.UserAccessControl(invalid)); } [Fact] public void Contacts() { // Arrange const string expected = "(&(objectCategory=person)(objectClass=contact))"; // Act var filter = ActiveDirectoryCommonFilters.Contacts; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Contacts_In_Group() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=contact))" + "(memberOf=CN=TEST,OU=Groups,OU=HDQRK,DC=COMPANY,DC=COM))"; // Act var filter = ActiveDirectoryCommonFilters.ContactsInGroup( DistinguishedName.Parse( "CN=TEST,OU=Groups,OU=HDQRK,DC=COMPANY,DC=COM")); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Group_With_Fuzzy_Search() { // Arrange const string expected = "(&(objectCategory=group)(sAMAccountName=*domain*))"; // Act var filter = ActiveDirectoryCommonFilters.Group("domain", true); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Group_With_Strict_Search() { // Arrange const string expected = "(&(objectCategory=group)(sAMAccountName=domain))"; // Act var filter = ActiveDirectoryCommonFilters.Group("domain"); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Groups() { // Arrange const string expected = "(objectCategory=group)"; // Act var filter = ActiveDirectoryCommonFilters.Groups; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Groups_Domain_Local() { // Arrange const string expected = "(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=2147483652))"; // Act var filter = ActiveDirectoryCommonFilters.DomainLocalGroups; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Groups_Global() { // Arrange const string expected = "(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=2147483650))"; // Act var filter = ActiveDirectoryCommonFilters.GlobalGroups; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Groups_Universal() { // Arrange const string expected = "(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=2147483656))"; // Act var filter = ActiveDirectoryCommonFilters.UniversalGroups; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Groups_With_Email_Address() { // Arrange const string expected = "(&(objectCategory=group)(mail=*))"; // Act var filter = ActiveDirectoryCommonFilters.GroupsWithEmail; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Groups_With_No_Members() { // Arrange const string expected = "(&(objectCategory=group)(!member=*))"; // Act var filter = ActiveDirectoryCommonFilters.EmptyGroups; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void SAM_ALIAS_OBJECT() { // Arrange const string expected = "(sAMAcountType=536870912)"; // Act var filter = ActiveDirectoryCommonFilters.SAM_ALIAS_OBJECT; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void SAM_GROUP_OBJECT() { // Arrange const string expected = "(sAMAcountType=268435456)"; // Act var filter = ActiveDirectoryCommonFilters.SAM_GROUP_OBJECT; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void SAM_MACHINE_ACCOUNT() { // Arrange const string expected = "(sAMAcountType=805306369)"; // Act var filter = ActiveDirectoryCommonFilters.SAM_MACHINE_ACCOUNT; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void SAM_NON_SECURITY_ALIAS_OBJECT() { // Arrange const string expected = "(sAMAcountType=536870913)"; // Act var filter = ActiveDirectoryCommonFilters.SAM_NON_SECURITY_ALIAS_OBJECT; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void SAM_NON_SECURITY_GROUP_OBJECT() { // Arrange const string expected = "(sAMAcountType=268435457)"; // Act var filter = ActiveDirectoryCommonFilters.SAM_NON_SECURITY_GROUP_OBJECT; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void SAM_NORMAL_USER_ACCOUNT() { // Arrange const string expected = "(sAMAcountType=805306368)"; // Act var filter = ActiveDirectoryCommonFilters.SAM_NORMAL_USER_ACCOUNT; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void SAM_TRUST_ACCOUNT() { // Arrange const string expected = "(sAMAcountType=805306370)"; // Act var filter = ActiveDirectoryCommonFilters.SAM_TRUST_ACCOUNT; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void SAM_USER_OBJECT() { // Arrange const string expected = "(sAMAcountType=805306368)"; // Act var filter = ActiveDirectoryCommonFilters.SAM_USER_OBJECT; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_ACCOUNTDISABLE() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=2)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.ACCOUNTDISABLE); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_DONT_EXPIRE_PASSWORD() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=65536)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.DONT_EXPIRE_PASSWD); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_DONT_REQ_PREAUTH() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=4194304)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.DONT_REQUIRE_PREAUTH); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_ENCRYPTED_TEXT_PWD_ALLOWED() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=128)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.ENCRYPTED_TEXT_PASSWORD_ALLOWED); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_HOMEDIR_REQUIRED() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=8)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.HOMEDIR_REQUIRED); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_INTERDOMAIN_TRUST_ACCOUNT() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=2048)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.INTERDOMAIN_TRUST_ACCOUNT); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_LOCKOUT() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=16)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.LOCKOUT); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_MNS_LOGON_ACCOUNT() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=131072)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.MNS_LOGON_ACCOUNT); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_NORMAL_ACCOUNT() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=512)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.NORMAL_ACCOUNT); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_NOT_DELEGATED() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=1048576)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.NOT_DELEGATED); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_PASSWD_CANT_CHANGE() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=64)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.PASSWD_CANT_CHANGE); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_PASSWD_NOTREQD() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=32)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.PASSWD_NOTREQD); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_PASSWORD_EXPIRED() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=8388608)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.PASSWORD_EXPIRED); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_SCRIPT() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=1)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.SCRIPT); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_SERVER_TRUST_ACCOUNT() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=8192)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.SERVER_TRUST_ACCOUNT); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_SMARTCARD_REQUIRED() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=262144)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.SMARTCARD_REQUIRED); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_TEMP_DUPLICATE_ACCOUNT() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=256)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.TEMP_DUPLICATE_ACCOUNT); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_TRUSTED_FOR_DELEGATION() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=524288)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.TRUSTED_FOR_DELEGATION); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_TRUSTED_TO_AUTH_FOR_DELEGATION() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=16777216)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_USE_DES_KEY_ONLY() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=2097152)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.USE_DES_KEY_ONLY); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void UAC_WORKSTATION_TRUST_ACCOUNT() { // Arrange const string expected = "(userAccountControl:1.2.840.113556.1.4.803:=4096)"; // Act var filter = ActiveDirectoryCommonFilters.UserAccessControl( ADS_USER_FLAG.WORKSTATION_TRUST_ACCOUNT); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users() { // Arrange const string expected = "(&(objectCategory=person)(objectClass=user))"; // Act var filter = ActiveDirectoryCommonFilters.Users; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Administrative_Users() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=*-adm))"; // Act var filter = ActiveDirectoryCommonFilters.AdministrativeUsers; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_And_Contacts_Who_Are_Members_Of_A_Group() { // Arrange const string expected = "(&(objectCategory=person)" + "(|(objectClass=contact)(objectClass=user))" + "(memberOf=CN=TEST,OU=Groups,OU=HDQRK,DC=COMPANY,DC=COM))"; // Act var filter = ActiveDirectoryCommonFilters.UsersContactsInGroup( DistinguishedName.Parse( "CN=TEST,OU=Groups,OU=HDQRK,DC=COMPANY,DC=COM")); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Created_After_Date() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))" + "(whenCreated>=20090501000000.0Z))"; var theDate = new DateTime(2009, 5, 1); // Act var filter = ActiveDirectoryCommonFilters.UsersCreatedAfterDate(theDate); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Created_Before_Date() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))" + "(whenCreated<=20090501000000.0Z))"; var theDate = new DateTime(2009, 5, 1); // Act var filter = ActiveDirectoryCommonFilters.UsersCreatedBeforeDate(theDate); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Created_Between_Dates() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))" + "(&(whenCreated>=20090501000000.0Z)(whenCreated<=20090501000000.0Z)))"; var firstDate = new DateTime(2009, 5, 1); var secondDate = new DateTime(2009, 5, 1); // Act var filter = ActiveDirectoryCommonFilters.UsersCreatedBetweenDates(firstDate, secondDate); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Normal_Account() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))" + "(!sAMAccountName=*-adm)(!sAMAccountName=*svc))"; // Act var filter = ActiveDirectoryCommonFilters.NormalAccounts; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Service_Accounts() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=*svc))"; // Act var filter = ActiveDirectoryCommonFilters.ServiceAccounts; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Who_Are_Disabled() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))" + "(userAccountControl:1.2.840.113556.1.4.803:=2))"; // Act var filter = LdapFilter.And( ActiveDirectoryCommonFilters.Users, ActiveDirectoryCommonFilters.UserAccessControl(ADS_USER_FLAG.ACCOUNTDISABLE)); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Who_Are_Locked_Out() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))" + "(userAccountControl:1.2.840.113556.1.4.803:=16))"; // Act var filter = LdapFilter.And( ActiveDirectoryCommonFilters.Users, ActiveDirectoryCommonFilters.UserAccessControl(ADS_USER_FLAG.LOCKOUT)); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Who_Are_Not_Disabled_And_Must_Change_Password() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))" + "(pwdLastSet=0)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"; // Act var filter = ActiveDirectoryCommonFilters.UsersNotDisabledMustChangePassword; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_Whose_Passwords_Do_Not_Expire() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))" + "(userAccountControl:1.2.840.113556.1.4.803:=65536))"; // Act var filter = LdapFilter.And( ActiveDirectoryCommonFilters.Users, ActiveDirectoryCommonFilters.UserAccessControl(ADS_USER_FLAG.DONT_EXPIRE_PASSWD)); // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_With_Email_Address() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))(mail=*))"; // Act var filter = ActiveDirectoryCommonFilters.UsersWithEmail; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_With_No_Email_Address() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))(!mail=*))"; // Act var filter = ActiveDirectoryCommonFilters.UsersWithoutEmail; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_With_No_Logon_Script() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))(!scriptPath=*))"; // Act var filter = ActiveDirectoryCommonFilters.UsersWithoutLogonScript; // Assert Assert.Equal(expected, filter.ToString()); } [Fact] public void Users_With_No_Profile_Path() { // Arrange const string expected = "(&(&(objectCategory=person)(objectClass=user))(!profilePath=*))"; // Act var filter = ActiveDirectoryCommonFilters.UsersWithoutProfilePath; // Assert Assert.Equal(expected, filter.ToString()); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace OCR.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2AllSync.Models { using Fixtures.PetstoreV2AllSync; using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; public partial class Pet { /// <summary> /// Initializes a new instance of the Pet class. /// </summary> public Pet() { CustomInit(); } /// <summary> /// Initializes a new instance of the Pet class. /// </summary> /// <param name="status">pet status in the store. Possible values /// include: 'available', 'pending', 'sold'</param> public Pet(string name, IList<string> photoUrls, long? id = default(long?), Category category = default(Category), IList<Tag> tags = default(IList<Tag>), byte[] sByteProperty = default(byte[]), System.DateTime? birthday = default(System.DateTime?), IDictionary<string, Category> dictionary = default(IDictionary<string, Category>), string status = default(string)) { Id = id; Category = category; Name = name; PhotoUrls = photoUrls; Tags = tags; SByteProperty = sByteProperty; Birthday = birthday; Dictionary = dictionary; Status = status; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "id")] public long? Id { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "category")] public Category Category { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "photoUrls")] public IList<string> PhotoUrls { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "tags")] public IList<Tag> Tags { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sByte")] public byte[] SByteProperty { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "birthday")] public System.DateTime? Birthday { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "dictionary")] public IDictionary<string, Category> Dictionary { get; set; } /// <summary> /// Gets or sets pet status in the store. Possible values include: /// 'available', 'pending', 'sold' /// </summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Name"); } if (PhotoUrls == null) { throw new ValidationException(ValidationRules.CannotBeNull, "PhotoUrls"); } } /// <summary> /// Serializes the object to an XML node /// </summary> internal XElement XmlSerialize(XElement result) { if( null != Id ) { result.Add(new XElement("id", Id) ); } if( null != Category ) { result.Add(Category.XmlSerialize(new XElement( "category" ))); } if( null != Name ) { result.Add(new XElement("name", Name) ); } if( null != PhotoUrls ) { var seq = new XElement("photoUrl"); foreach( var value in PhotoUrls ){ seq.Add(new XElement( "photoUrl", value ) ); } result.Add(seq); } if( null != Tags ) { var seq = new XElement("tag"); foreach( var value in Tags ){ seq.Add(value.XmlSerialize( new XElement( "tag") ) ); } result.Add(seq); } if( null != SByteProperty ) { result.Add(new XElement("sByte", SByteProperty) ); } if( null != Birthday ) { result.Add(new XElement("birthday", Birthday) ); } if( null != Dictionary ) { var dict = new XElement("dictionary"); foreach( var key in Dictionary.Keys ) { dict.Add(Dictionary[key].XmlSerialize(new XElement(key) ) ); } result.Add(dict); } if( null != Status ) { result.Add(new XElement("status", Status) ); } return result; } /// <summary> /// Deserializes an XML node to an instance of Pet /// </summary> internal static Pet XmlDeserialize(string payload) { // deserialize to xml and use the overload to do the work return XmlDeserialize( XElement.Parse( payload ) ); } internal static Pet XmlDeserialize(XElement payload) { var result = new Pet(); var deserializeId = XmlSerialization.ToDeserializer(e => (long?)e); long? resultId; if (deserializeId(payload, "id", out resultId)) { result.Id = resultId; } var deserializeCategory = XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e)); Category resultCategory; if (deserializeCategory(payload, "category", out resultCategory)) { result.Category = resultCategory; } var deserializeName = XmlSerialization.ToDeserializer(e => (string)e); string resultName; if (deserializeName(payload, "name", out resultName)) { result.Name = resultName; } var deserializePhotoUrls = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => (string)e), "photoUrl"); IList<string> resultPhotoUrls; if (deserializePhotoUrls(payload, "photoUrl", out resultPhotoUrls)) { result.PhotoUrls = resultPhotoUrls; } var deserializeTags = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => Tag.XmlDeserialize(e)), "tag"); IList<Tag> resultTags; if (deserializeTags(payload, "tag", out resultTags)) { result.Tags = resultTags; } var deserializeSByteProperty = XmlSerialization.ToDeserializer(e => System.Convert.FromBase64String(e.Value)); byte[] resultSByteProperty; if (deserializeSByteProperty(payload, "sByte", out resultSByteProperty)) { result.SByteProperty = resultSByteProperty; } var deserializeBirthday = XmlSerialization.ToDeserializer(e => (System.DateTime?)e); System.DateTime? resultBirthday; if (deserializeBirthday(payload, "birthday", out resultBirthday)) { result.Birthday = resultBirthday; } var deserializeDictionary = XmlSerialization.CreateDictionaryXmlDeserializer(XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e))); IDictionary<string, Category> resultDictionary; if (deserializeDictionary(payload, "dictionary", out resultDictionary)) { result.Dictionary = resultDictionary; } var deserializeStatus = XmlSerialization.ToDeserializer(e => (string)e); string resultStatus; if (deserializeStatus(payload, "status", out resultStatus)) { result.Status = resultStatus; } return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class WarningHeaderValueTest { [Fact] public void Ctor_3ParamsOverload_AllFieldsInitializedCorrectly() { WarningHeaderValue warning = new WarningHeaderValue(111, ".host", "\"Revalidation failed\""); Assert.Equal(111, warning.Code); Assert.Equal(".host", warning.Agent); Assert.Equal("\"Revalidation failed\"", warning.Text); Assert.Null(warning.Date); warning = new WarningHeaderValue(112, "[::1]", "\"Disconnected operation\""); Assert.Equal(112, warning.Code); Assert.Equal("[::1]", warning.Agent); Assert.Equal("\"Disconnected operation\"", warning.Text); Assert.Null(warning.Date); Assert.Throws<ArgumentOutOfRangeException>(() => { new WarningHeaderValue(-1, "host", "\"\""); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new WarningHeaderValue(1000, "host", "\"\""); }); Assert.Throws<ArgumentException>(() => { new WarningHeaderValue(100, null, "\"\""); }); Assert.Throws<ArgumentException>(() => { new WarningHeaderValue(100, "", "\"\""); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "x y", "\"\""); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "x ", "\"\""); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, " x", "\"\""); }); Assert.Throws<ArgumentException>(() => { new WarningHeaderValue(100, null, "\"\""); }); Assert.Throws<ArgumentException>(() => { new WarningHeaderValue(100, "", "\"\""); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "h", "x"); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "h", "\"x"); }); } [Fact] public void Ctor_4ParamsOverload_AllFieldsInitializedCorrectly() { WarningHeaderValue warning = new WarningHeaderValue(111, "host", "\"Revalidation failed\"", new DateTimeOffset(2010, 7, 19, 17, 9, 15, TimeSpan.Zero)); Assert.Equal(111, warning.Code); Assert.Equal("host", warning.Agent); Assert.Equal("\"Revalidation failed\"", warning.Text); Assert.Equal(new DateTimeOffset(2010, 7, 19, 17, 9, 15, TimeSpan.Zero), warning.Date); Assert.Throws<ArgumentOutOfRangeException>(() => { new WarningHeaderValue(-1, "host", "\"\""); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new WarningHeaderValue(1000, "host", "\"\""); }); Assert.Throws<ArgumentException>(() => { new WarningHeaderValue(100, null, "\"\""); }); Assert.Throws<ArgumentException>(() => { new WarningHeaderValue(100, "", "\"\""); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "[::1]:80(x)", "\"\""); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "host::80", "\"\""); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "192.168.0.1=", "\"\""); }); Assert.Throws<ArgumentException>(() => { new WarningHeaderValue(100, null, "\"\""); }); Assert.Throws<ArgumentException>(() => { new WarningHeaderValue(100, "", "\"\""); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "h", "(x)"); }); Assert.Throws<FormatException>(() => { new WarningHeaderValue(100, "h", "\"x\"y"); }); } [Fact] public void ToString_UseDifferentRanges_AllSerializedCorrectly() { WarningHeaderValue warning = new WarningHeaderValue(113, "host:80", "\"Heuristic expiration\""); Assert.Equal("113 host:80 \"Heuristic expiration\"", warning.ToString()); warning = new WarningHeaderValue(199, "[::1]", "\"Miscellaneous warning\"", new DateTimeOffset(2010, 7, 19, 18, 31, 27, TimeSpan.Zero)); Assert.Equal("199 [::1] \"Miscellaneous warning\" \"Mon, 19 Jul 2010 18:31:27 GMT\"", warning.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes() { WarningHeaderValue warning1 = new WarningHeaderValue(214, "host", "\"Transformation applied\""); WarningHeaderValue warning2 = new WarningHeaderValue(214, "HOST", "\"Transformation applied\""); WarningHeaderValue warning3 = new WarningHeaderValue(215, "host", "\"Transformation applied\""); WarningHeaderValue warning4 = new WarningHeaderValue(214, "other", "\"Transformation applied\""); WarningHeaderValue warning5 = new WarningHeaderValue(214, "host", "\"TRANSFORMATION APPLIED\""); WarningHeaderValue warning6 = new WarningHeaderValue(214, "host", "\"Transformation applied\"", new DateTimeOffset(2010, 7, 19, 18, 31, 27, TimeSpan.Zero)); WarningHeaderValue warning7 = new WarningHeaderValue(214, "host", "\"Transformation applied\"", new DateTimeOffset(2011, 7, 19, 18, 31, 27, TimeSpan.Zero)); WarningHeaderValue warning8 = new WarningHeaderValue(214, "host", "\"Transformation applied\"", new DateTimeOffset(2010, 7, 19, 18, 31, 27, TimeSpan.Zero)); Assert.Equal(warning1.GetHashCode(), warning2.GetHashCode()); Assert.NotEqual(warning1.GetHashCode(), warning3.GetHashCode()); Assert.NotEqual(warning1.GetHashCode(), warning4.GetHashCode()); Assert.NotEqual(warning1.GetHashCode(), warning6.GetHashCode()); Assert.NotEqual(warning1.GetHashCode(), warning7.GetHashCode()); Assert.NotEqual(warning6.GetHashCode(), warning7.GetHashCode()); Assert.Equal(warning6.GetHashCode(), warning8.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { WarningHeaderValue warning1 = new WarningHeaderValue(214, "host", "\"Transformation applied\""); WarningHeaderValue warning2 = new WarningHeaderValue(214, "HOST", "\"Transformation applied\""); WarningHeaderValue warning3 = new WarningHeaderValue(215, "host", "\"Transformation applied\""); WarningHeaderValue warning4 = new WarningHeaderValue(214, "other", "\"Transformation applied\""); WarningHeaderValue warning5 = new WarningHeaderValue(214, "host", "\"TRANSFORMATION APPLIED\""); WarningHeaderValue warning6 = new WarningHeaderValue(214, "host", "\"Transformation applied\"", new DateTimeOffset(2010, 7, 19, 18, 31, 27, TimeSpan.Zero)); WarningHeaderValue warning7 = new WarningHeaderValue(214, "host", "\"Transformation applied\"", new DateTimeOffset(2011, 7, 19, 18, 31, 27, TimeSpan.Zero)); WarningHeaderValue warning8 = new WarningHeaderValue(214, "host", "\"Transformation applied\"", new DateTimeOffset(2010, 7, 19, 18, 31, 27, TimeSpan.Zero)); Assert.False(warning1.Equals(null), "214 host \"t.a.\" vs. <null>"); Assert.True(warning1.Equals(warning2), "214 host \"t.a.\" vs. 214 HOST \"t.a.\""); Assert.False(warning1.Equals(warning3), "214 host \"t.a.\" vs. 215 host \"t.a.\""); Assert.False(warning1.Equals(warning4), "214 host \"t.a.\" vs. 214 other \"t.a.\""); Assert.False(warning1.Equals(warning6), "214 host \"t.a.\" vs. 214 host \"T.A.\""); Assert.False(warning1.Equals(warning7), "214 host \"t.a.\" vs. 214 host \"t.a.\" \"D\""); Assert.False(warning7.Equals(warning1), "214 host \"t.a.\" \"D\" vs. 214 host \"t.a.\""); Assert.False(warning6.Equals(warning7), "214 host \"t.a.\" \"D\" vs. 214 host \"t.a.\" \"other D\""); Assert.True(warning6.Equals(warning8), "214 host \"t.a.\" \"D\" vs. 214 host \"t.a.\" \"D\""); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { WarningHeaderValue source = new WarningHeaderValue(299, "host", "\"Miscellaneous persistent warning\""); WarningHeaderValue clone = (WarningHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Code, clone.Code); Assert.Equal(source.Agent, clone.Agent); Assert.Equal(source.Text, clone.Text); Assert.Equal(source.Date, clone.Date); source = new WarningHeaderValue(110, "host", "\"Response is stale\"", new DateTimeOffset(2010, 7, 31, 15, 37, 05, TimeSpan.Zero)); clone = (WarningHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Code, clone.Code); Assert.Equal(source.Agent, clone.Agent); Assert.Equal(source.Text, clone.Text); Assert.Equal(source.Date, clone.Date); } [Fact] public void GetWarningLength_DifferentValidScenarios_AllReturnNonZero() { CheckGetWarningLength(" 199 .host \r\n \"Miscellaneous warning\" ", 1, 38, new WarningHeaderValue(199, ".host", "\"Miscellaneous warning\"")); CheckGetWarningLength("987 [FE18:AB64::156]:80 \"\" \"Tue, 20 Jul 2010 01:02:03 GMT\"", 0, 58, new WarningHeaderValue(987, "[FE18:AB64::156]:80", "\"\"", new DateTimeOffset(2010, 7, 20, 1, 2, 3, TimeSpan.Zero))); // The parser reads until it reaches an invalid/unexpected character. If until then it was able to create // a valid WarningHeaderValue, it will return the length of the parsed string. Therefore a string like // the following is considered valid (until '[') CheckGetWarningLength("1 h \"t\"[", 0, 7, new WarningHeaderValue(1, "h", "\"t\"")); CheckGetWarningLength("1 h \"t\" \"Tue, 20 Jul 2010 01:02:03 GMT\"[", 0, 39, new WarningHeaderValue(1, "h", "\"t\"", new DateTimeOffset(2010, 7, 20, 1, 2, 3, TimeSpan.Zero))); CheckGetWarningLength(null, 0, 0, null); CheckGetWarningLength(string.Empty, 0, 0, null); CheckGetWarningLength(" ", 0, 0, null); } [Fact] public void GetWarningLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidWarningViaLength(" 123 host", 0); // no leading whitespaces allowed // No delimiter between two values CheckInvalidWarningViaLength("123host \"t\"", 0); CheckInvalidWarningViaLength("123 host\"t\"", 0); CheckInvalidWarningViaLength("123 host \"t\"\"Tue, 20 Jul 2010 01:02:03 GMT\"", 0); CheckInvalidWarningViaLength("123 http://host \"t\"", 0); CheckInvalidWarningViaLength("1=host \"t\"", 0); CheckInvalidWarningViaLength("1.1 host \"invalid_quoted_string", 0); CheckInvalidWarningViaLength("=", 0); CheckInvalidWarningViaLength("121 host=\"t\"", 0); CheckInvalidWarningViaLength("121 host= \"t\"", 0); CheckInvalidWarningViaLength("121 host =\"t\"", 0); CheckInvalidWarningViaLength("121 host = \"t\"", 0); CheckInvalidWarningViaLength("121 host =", 0); CheckInvalidWarningViaLength("121 = \"t\"", 0); CheckInvalidWarningViaLength("123", 0); CheckInvalidWarningViaLength("123 host", 0); CheckInvalidWarningViaLength(" ", 0); CheckInvalidWarningViaLength("123 example.com[ \"t\"", 0); CheckInvalidWarningViaLength("123 / \"t\"", 0); CheckInvalidWarningViaLength("123 host::80 \"t\"", 0); CheckInvalidWarningViaLength("123 host/\"t\"", 0); CheckInvalidWarningViaLength("123 host \"t\" \"Tue, 20 Jul 2010 01:02:03 GMT", 0); CheckInvalidWarningViaLength("123 host \"t\" \"Tue, 200 Jul 2010 01:02:03 GMT\"", 0); CheckInvalidWarningViaLength("123 host \"t\" \"\"", 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse(" 123 host \"text\"", new WarningHeaderValue(123, "host", "\"text\"")); CheckValidParse(" 50 192.168.0.1 \"text \" \"Tue, 20 Jul 2010 01:02:03 GMT\" ", new WarningHeaderValue(50, "192.168.0.1", "\"text \"", new DateTimeOffset(2010, 7, 20, 1, 2, 3, TimeSpan.Zero))); CheckValidParse(" 123 h \"t\"", new WarningHeaderValue(123, "h", "\"t\"")); CheckValidParse("1 h \"t\"", new WarningHeaderValue(1, "h", "\"t\"")); CheckValidParse("1 h \"t\" \"Tue, 20 Jul 2010 01:02:03 GMT\"", new WarningHeaderValue(1, "h", "\"t\"", new DateTimeOffset(2010, 7, 20, 1, 2, 3, TimeSpan.Zero))); CheckValidParse("1 \u4F1A \"t\" ", new WarningHeaderValue(1, "\u4F1A", "\"t\"")); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("1.1 host \"text\""); CheckInvalidParse("11 host text"); CheckInvalidParse("11 host \"text\" Tue, 20 Jul 2010 01:02:03 GMT"); CheckInvalidParse("11 host \"text\" 123 next \"text\""); CheckInvalidParse("\u4F1A"); CheckInvalidParse("123 \u4F1A"); CheckInvalidParse("111 [::1]:80\r(comment) \"text\""); CheckInvalidParse("111 [::1]:80\n(comment) \"text\""); CheckInvalidParse("X , , 123 host \"text\", ,next"); CheckInvalidParse("X 50 192.168.0.1 \"text \" \"Tue, 20 Jul 2010 01:02:03 GMT\" , ,next"); CheckInvalidParse(" ,123 h \"t\","); CheckInvalidParse("1 \u4F1A \"t\" ,,"); CheckInvalidParse(null); CheckInvalidParse(string.Empty); CheckInvalidParse(" "); CheckInvalidParse(" ,,"); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse(" 123 host \"text\"", new WarningHeaderValue(123, "host", "\"text\"")); CheckValidTryParse(" 50 192.168.0.1 \"text \" \"Tue, 20 Jul 2010 01:02:03 GMT\" ", new WarningHeaderValue(50, "192.168.0.1", "\"text \"", new DateTimeOffset(2010, 7, 20, 1, 2, 3, TimeSpan.Zero))); CheckValidTryParse(" 123 h \"t\"", new WarningHeaderValue(123, "h", "\"t\"")); CheckValidTryParse("1 h \"t\"", new WarningHeaderValue(1, "h", "\"t\"")); CheckValidTryParse("1 h \"t\" \"Tue, 20 Jul 2010 01:02:03 GMT\"", new WarningHeaderValue(1, "h", "\"t\"", new DateTimeOffset(2010, 7, 20, 1, 2, 3, TimeSpan.Zero))); CheckValidTryParse("1 \u4F1A \"t\" ", new WarningHeaderValue(1, "\u4F1A", "\"t\"")); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("1.1 host \"text\""); CheckInvalidTryParse("11 host text"); CheckInvalidTryParse("11 host \"text\" Tue, 20 Jul 2010 01:02:03 GMT"); CheckInvalidTryParse("11 host \"text\" 123 next \"text\""); CheckInvalidTryParse("\u4F1A"); CheckInvalidTryParse("123 \u4F1A"); CheckInvalidTryParse("111 [::1]:80\r(comment) \"text\""); CheckInvalidTryParse("111 [::1]:80\n(comment) \"text\""); CheckInvalidTryParse("X , , 123 host \"text\", ,next"); CheckInvalidTryParse("X 50 192.168.0.1 \"text \" \"Tue, 20 Jul 2010 01:02:03 GMT\" , ,next"); CheckInvalidTryParse(" ,123 h \"t\","); CheckInvalidTryParse("1 \u4F1A \"t\" ,,"); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); CheckInvalidTryParse(" "); CheckInvalidTryParse(" ,,"); } #region Helper methods private void CheckValidParse(string input, WarningHeaderValue expectedResult) { WarningHeaderValue result = WarningHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { WarningHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, WarningHeaderValue expectedResult) { WarningHeaderValue result = null; Assert.True(WarningHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { WarningHeaderValue result = null; Assert.False(WarningHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CheckGetWarningLength(string input, int startIndex, int expectedLength, WarningHeaderValue expectedResult) { object result = null; Assert.Equal(expectedLength, WarningHeaderValue.GetWarningLength(input, startIndex, out result)); Assert.Equal(expectedResult, result); } private static void CheckInvalidWarningViaLength(string input, int startIndex) { object result = null; Assert.Equal(0, WarningHeaderValue.GetWarningLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Apex Trigger ///<para>SObject Name: ApexTrigger</para> ///<para>Custom Object: False</para> ///</summary> public class SfApexTrigger : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "ApexTrigger"; } } ///<summary> /// Trigger ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Namespace Prefix /// <para>Name: NamespacePrefix</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "namespacePrefix")] [Updateable(false), Createable(false)] public string NamespacePrefix { get; set; } ///<summary> /// Name /// <para>Name: Name</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } ///<summary> /// Custom Object Definition ID /// <para>Name: TableEnumOrId</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "tableEnumOrId")] public string TableEnumOrId { get; set; } ///<summary> /// BeforeInsert /// <para>Name: UsageBeforeInsert</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "usageBeforeInsert")] public bool? UsageBeforeInsert { get; set; } ///<summary> /// AfterInsert /// <para>Name: UsageAfterInsert</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "usageAfterInsert")] public bool? UsageAfterInsert { get; set; } ///<summary> /// BeforeUpdate /// <para>Name: UsageBeforeUpdate</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "usageBeforeUpdate")] public bool? UsageBeforeUpdate { get; set; } ///<summary> /// AfterUpdate /// <para>Name: UsageAfterUpdate</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "usageAfterUpdate")] public bool? UsageAfterUpdate { get; set; } ///<summary> /// BeforeDelete /// <para>Name: UsageBeforeDelete</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "usageBeforeDelete")] public bool? UsageBeforeDelete { get; set; } ///<summary> /// AfterDelete /// <para>Name: UsageAfterDelete</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "usageAfterDelete")] public bool? UsageAfterDelete { get; set; } ///<summary> /// IsBulk /// <para>Name: UsageIsBulk</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "usageIsBulk")] public bool? UsageIsBulk { get; set; } ///<summary> /// AfterUndelete /// <para>Name: UsageAfterUndelete</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "usageAfterUndelete")] public bool? UsageAfterUndelete { get; set; } ///<summary> /// Api Version /// <para>Name: ApiVersion</para> /// <para>SF Type: double</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "apiVersion")] public double? ApiVersion { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } ///<summary> /// Is Valid /// <para>Name: IsValid</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isValid")] public bool? IsValid { get; set; } ///<summary> /// Body CRC /// <para>Name: BodyCrc</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "bodyCrc")] public double? BodyCrc { get; set; } ///<summary> /// Body /// <para>Name: Body</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "body")] public string Body { get; set; } ///<summary> /// Size Without Comments /// <para>Name: LengthWithoutComments</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lengthWithoutComments")] public int? LengthWithoutComments { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using FlatRedBall.Content.Polygon; using FlatRedBall.Math; using FileManager = FlatRedBall.IO.FileManager; using FlatRedBall.Math.Geometry; using Microsoft.Xna.Framework; namespace FlatRedBall.Content.Math.Geometry { public class ShapeCollectionSave { #region Fields public List<AxisAlignedRectangleSave> AxisAlignedRectangleSaves = new List<AxisAlignedRectangleSave>(); public List<AxisAlignedCubeSave> AxisAlignedCubeSaves = new List<AxisAlignedCubeSave>(); public List<PolygonSave> PolygonSaves = new List<PolygonSave>(); public List<CircleSave> CircleSaves = new List<CircleSave>(); public List<SphereSave> SphereSaves = new List<SphereSave>(); string mFileName; #endregion #region Properties [XmlIgnore] public string FileName { get { return mFileName; } set { mFileName = value; } } #endregion #region Methods public void AddAxisAlignedRectangleList(PositionedObjectList<FlatRedBall.Math.Geometry.AxisAlignedRectangle> axisAlignedRectanglesToAdd) { foreach (FlatRedBall.Math.Geometry.AxisAlignedRectangle rectangle in axisAlignedRectanglesToAdd) { AxisAlignedRectangleSave rectangleSave = AxisAlignedRectangleSave.FromAxisAlignedRectangle(rectangle); AxisAlignedRectangleSaves.Add(rectangleSave); } } public void AddCircleList(PositionedObjectList<Circle> circlesToAdd) { foreach (Circle circle in circlesToAdd) { CircleSave circleSave = CircleSave.FromCircle(circle); CircleSaves.Add(circleSave); } } public void AddSphereList(PositionedObjectList<Sphere> spheresToAdd) { foreach (Sphere sphere in spheresToAdd) { SphereSave sphereSave = SphereSave.FromSphere(sphere); SphereSaves.Add(sphereSave); } } public void AddPolygonList(PositionedObjectList<FlatRedBall.Math.Geometry.Polygon> polygonsToAdd) { foreach (FlatRedBall.Math.Geometry.Polygon polygon in polygonsToAdd) { PolygonSave polygonSave = PolygonSave.FromPolygon(polygon); PolygonSaves.Add(polygonSave); } } public void AddAxisAlignedCubeList(PositionedObjectList<FlatRedBall.Math.Geometry.AxisAlignedCube> axisAlignedCubesToAdd) { foreach (FlatRedBall.Math.Geometry.AxisAlignedCube cube in axisAlignedCubesToAdd) { AxisAlignedCubeSave cubeSave = AxisAlignedCubeSave.FromAxisAlignedCube(cube); AxisAlignedCubeSaves.Add(cubeSave); } } /// <summary> /// Deserializes a file into a new ShapeCollectionSave and returns it. /// </summary> /// <param name="fileName">The absolute or relative file name. If the file name is relative, then the FileManager's RelativeDirectory will be used.</param> /// <returns>The newly-created ShapeCollectionSave.</returns> public static ShapeCollectionSave FromFile(string fileName) { ShapeCollectionSave shapeSaveCollection = FileManager.XmlDeserialize<ShapeCollectionSave>(fileName); shapeSaveCollection.mFileName = fileName; return shapeSaveCollection; } public static ShapeCollectionSave FromShapeCollection(ShapeCollection shapeCollection) { ShapeCollectionSave toReturn = new ShapeCollectionSave(); toReturn.AddAxisAlignedRectangleList(shapeCollection.AxisAlignedRectangles); toReturn.AddAxisAlignedCubeList(shapeCollection.AxisAlignedCubes); toReturn.AddCircleList(shapeCollection.Circles); toReturn.AddSphereList(shapeCollection.Spheres); toReturn.AddPolygonList(shapeCollection.Polygons); if (shapeCollection.Lines.Count != 0) { throw new NotImplementedException("Lines in ShapeCollectionSaves are not implemented yet. Complain on the FRB forums"); } if (shapeCollection.Capsule2Ds.Count != 0) { throw new NotImplementedException("Capsule2Ds in ShapeCollectionSaves are not implemented yet. Complain on the FRB forums"); } return toReturn; } public void Save(string fileName) { FileManager.XmlSerialize(this, fileName); } public PositionedObjectList<Circle> ToCircleList() { PositionedObjectList<Circle> listToReturn = new PositionedObjectList<Circle>(); foreach (CircleSave circleSave in CircleSaves) { Circle circle = circleSave.ToCircle(); listToReturn.Add(circle); } return listToReturn; } public PositionedObjectList<Sphere> ToSphereList() { PositionedObjectList<Sphere> listToReturn = new PositionedObjectList<Sphere>(); foreach (SphereSave sphereSave in SphereSaves) { Sphere sphere = sphereSave.ToSphere(); listToReturn.Add(sphere); } return listToReturn; } public PositionedObjectList<FlatRedBall.Math.Geometry.AxisAlignedRectangle> ToAxisAlignedRectangleList() { PositionedObjectList<FlatRedBall.Math.Geometry.AxisAlignedRectangle> listToReturn = new PositionedObjectList<FlatRedBall.Math.Geometry.AxisAlignedRectangle>(); foreach (AxisAlignedRectangleSave rectangleSave in AxisAlignedRectangleSaves) { FlatRedBall.Math.Geometry.AxisAlignedRectangle rectangle = rectangleSave.ToAxisAlignedRectangle(); listToReturn.Add(rectangle); } return listToReturn; } public PositionedObjectList<FlatRedBall.Math.Geometry.AxisAlignedCube> ToAxisAlignedCubeList() { PositionedObjectList<FlatRedBall.Math.Geometry.AxisAlignedCube> listToReturn = new PositionedObjectList<FlatRedBall.Math.Geometry.AxisAlignedCube>(); foreach (AxisAlignedCubeSave cubeSave in AxisAlignedCubeSaves) { FlatRedBall.Math.Geometry.AxisAlignedCube cube = cubeSave.ToAxisAlignedCube(); listToReturn.Add(cube); } return listToReturn; } public PositionedObjectList<FlatRedBall.Math.Geometry.Polygon> ToPolygonList() { PositionedObjectList<FlatRedBall.Math.Geometry.Polygon> listToReturn = new PositionedObjectList<FlatRedBall.Math.Geometry.Polygon>(); foreach (PolygonSave polygonSave in PolygonSaves) { FlatRedBall.Math.Geometry.Polygon polygon = polygonSave.ToPolygon(); listToReturn.Add(polygon); } return listToReturn; } public ShapeCollection ToShapeCollection() { ShapeCollection newShapeCollection = new ShapeCollection(); SetShapeCollection(newShapeCollection); return newShapeCollection; } public void SetShapeCollection(ShapeCollection newShapeCollection) { newShapeCollection.AxisAlignedRectangles.AddRange(ToAxisAlignedRectangleList()); newShapeCollection.AxisAlignedCubes.AddRange(ToAxisAlignedCubeList()); newShapeCollection.Circles.AddRange(ToCircleList()); newShapeCollection.Spheres.AddRange(ToSphereList()); newShapeCollection.Polygons.AddRange(ToPolygonList()); // Handle lines when we add them to the save class if (!string.IsNullOrEmpty(mFileName) && FileManager.IsRelative(mFileName)) { mFileName = FileManager.MakeAbsolute(mFileName); } newShapeCollection.Name = mFileName; } public void Shift(Vector3 shiftAmount) { foreach (AxisAlignedRectangleSave shape in AxisAlignedRectangleSaves) { shape.X += shiftAmount.X; shape.Y += shiftAmount.Y; shape.Z += shiftAmount.Z; } foreach (AxisAlignedCubeSave shape in AxisAlignedCubeSaves) { shape.X += shiftAmount.X; shape.Y += shiftAmount.Y; shape.Z += shiftAmount.Z; } foreach (PolygonSave shape in PolygonSaves) { shape.X += shiftAmount.X; shape.Y += shiftAmount.Y; shape.Z += shiftAmount.Z; } foreach (CircleSave shape in CircleSaves) { shape.X += shiftAmount.X; shape.Y += shiftAmount.Y; shape.Z += shiftAmount.Z; } foreach (SphereSave shape in SphereSaves) { shape.X += shiftAmount.X; shape.Y += shiftAmount.Y; shape.Z += shiftAmount.Z; } } #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using EnvDTE; using NuGet.VisualStudio; namespace NuGet.PowerShell.Commands { /// <summary> /// This command creates new package file. /// </summary> [Cmdlet(VerbsCommon.New, "Package")] public class NewPackageCommand : NuGetBaseCommand { private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { Constants.PackageExtension, Constants.ManifestExtension }, StringComparer.OrdinalIgnoreCase); public NewPackageCommand() : this(ServiceLocator.GetInstance<ISolutionManager>(), ServiceLocator.GetInstance<IVsPackageManagerFactory>(), ServiceLocator.GetInstance<IHttpClientEvents>()) { } public NewPackageCommand(ISolutionManager solutionManager, IVsPackageManagerFactory packageManagerFactory, IHttpClientEvents httpClientEvents) : base(solutionManager, packageManagerFactory, httpClientEvents) { } [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string ProjectName { get; set; } [Parameter(Position = 1)] [ValidateNotNullOrEmpty] public string SpecFileName { get; set; } [Parameter(Position = 2)] [ValidateNotNullOrEmpty] public string TargetFile { get; set; } /// <summary> /// If present, New-Package will not overwrite TargetFile. /// </summary> [Parameter] public SwitchParameter NoClobber { get; set; } protected override void ProcessRecordCore() { if (!SolutionManager.IsSolutionOpen) { ErrorHandler.ThrowSolutionNotOpenTerminatingError(); } string projectName = ProjectName; // no project specified - choose default if (String.IsNullOrEmpty(projectName)) { projectName = SolutionManager.DefaultProjectName; } // no default project? empty solution or no compatible projects found if (String.IsNullOrEmpty(projectName)) { ErrorHandler.ThrowNoCompatibleProjectsTerminatingError(); } var projectIns = SolutionManager.GetProject(projectName); if (projectIns == null) { ErrorHandler.WriteProjectNotFoundError(projectName, terminating: true); } string specFilePath = GetSpecFilePath(projectIns); var builder = new NuGet.PackageBuilder(specFilePath); string outputFilePath = GetTargetFilePath(projectIns, builder); // Remove .nuspec and .nupkg files from output package RemoveExludedFiles(builder); WriteLine(String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_CreatingPackage, outputFilePath)); using (Stream stream = File.Create(outputFilePath)) { builder.Save(stream); } WriteLine(Resources.Cmdlet_PackageCreated); } private string GetSpecFilePath(Project projectIns) { string specFilePath = null; ProjectItem specFile = null; try { specFile = FindSpecFile(projectIns, SpecFileName).SingleOrDefault(); } catch (InvalidOperationException) { // SingleOrDefault will throw if more than one spec files were found // terminating ErrorHandler.HandleException( new InvalidOperationException(Resources.Cmdlet_TooManySpecFiles), terminating: true, errorId: NuGetErrorId.TooManySpecFiles, category: ErrorCategory.InvalidOperation); } if (specFile == null) { // terminating ErrorHandler.HandleException( new ItemNotFoundException(Resources.Cmdlet_NuspecFileNotFound), terminating: true, errorId: NuGetErrorId.NuspecFileNotFound, category: ErrorCategory.ObjectNotFound, target: SpecFileName); } else { specFilePath = specFile.FileNames[0]; } return specFilePath; } private string GetTargetFilePath(Project projectIns, PackageBuilder builder) { // Get the output file path string outputFilePath = GetPackageFilePath(TargetFile, projectIns.FullName, builder.Id, builder.Version); bool fileExists = File.Exists(outputFilePath); // prevent overwrite if -NoClobber specified if (fileExists && NoClobber.IsPresent) { // terminating ErrorHandler.HandleException( new UnauthorizedAccessException(String.Format( CultureInfo.CurrentCulture, Resources.Cmdlet_FileExistsNoClobber, TargetFile)), terminating: true, errorId: NuGetErrorId.FileExistsNoClobber, category: ErrorCategory.PermissionDenied, target: TargetFile); } return outputFilePath; } internal static string GetPackageFilePath(string outputFile, string projectPath, string id, SemanticVersion version) { if (String.IsNullOrEmpty(outputFile)) { outputFile = String.Join(".", id, version, Constants.PackageExtension.TrimStart('.')); } if (!Path.IsPathRooted(outputFile)) { // if the path is a relative, prepend the project path to it string folder = Path.GetDirectoryName(projectPath); outputFile = Path.Combine(folder, outputFile); } return outputFile; } internal static void RemoveExludedFiles(PackageBuilder builder) { // Remove the output file or the package spec might try to include it (which is default behavior) builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path))); } private static IEnumerable<ProjectItem> FindSpecFile(EnvDTE.Project projectIns, string specFile) { if (!String.IsNullOrEmpty(specFile)) { ProjectItem projectItem; projectIns.ProjectItems.TryGetFile(specFile, out projectItem); yield return projectItem; } else { // Verify if the project has exactly one file with the .nuspec extension. // If found, use it as the manifest file for package creation. int count = 0; foreach (ProjectItem item in projectIns.ProjectItems) { if (item.Name.EndsWith(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase)) { yield return item; count++; if (count > 1) { yield break; } } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Nmap.Internal { internal sealed class MapCompiler { #region Fields private readonly ConverterCollection converters; private readonly ObjectFactory objectFactory; private readonly IDictionary<PropertyInfo, Func<object, object>> getters; private readonly IDictionary<PropertyInfo, Action<object, object>> setters; private readonly IDictionary<Type, Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>> rootCompilers; private readonly IDictionary<PropertyInfo, Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>> nodeCompilers; #endregion #region Constructors public MapCompiler(ConverterCollection converters, ObjectFactory objectFactory) { this.converters = converters; this.objectFactory = objectFactory; getters = new Dictionary<PropertyInfo, Func<object, object>>(); setters = new Dictionary<PropertyInfo, Action<object, object>>(); rootCompilers = new Dictionary<Type, Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>>(); nodeCompilers = new Dictionary<PropertyInfo, Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>>(); rootCompilers.Add(typeof(TypeMap), new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(TypeMap)); rootCompilers.Add(typeof(ReversiveTypeMap), new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(ReversiveTypeMap)); nodeCompilers.Add(ReflectionHelper.GetMemberInfo<TypeMap, Action<object, object, TypeMappingContext>>((TypeMap o) => o.Mapper) as PropertyInfo, new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(MapWithMapper)); nodeCompilers.Add(ReflectionHelper.GetMemberInfo<TypeMap, ICollection<PropertyMap>>((TypeMap o) => o.PropertyMaps) as PropertyInfo, new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(TypeMapWithPropertyMaps)); nodeCompilers.Add(ReflectionHelper.GetMemberInfo<PropertyMap, Action<object, object, TypeMappingContext>>((PropertyMap o) => o.Mapper) as PropertyInfo, new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(MapWithMapper)); nodeCompilers.Add(ReflectionHelper.GetMemberInfo<PropertyMap, ICollection<TypeMap>>((PropertyMap o) => o.InheritanceMaps) as PropertyInfo, new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(PropertyMapWithInheritanceMaps)); nodeCompilers.Add(ReflectionHelper.GetMemberInfo<ReversiveTypeMap, Action<object, object, TypeMappingContext>>((ReversiveTypeMap o) => o.Mapper) as PropertyInfo, new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(ReversiveTypeMapWithMapper)); nodeCompilers.Add(ReflectionHelper.GetMemberInfo<ReversiveTypeMap, ICollection<ReversivePropertyMap>>((ReversiveTypeMap o) => o.PropertyMaps) as PropertyInfo, new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(ReversiveTypeMapWithPropertyMaps)); nodeCompilers.Add(ReflectionHelper.GetMemberInfo<ReversivePropertyMap, Action<object, object, TypeMappingContext>>((ReversivePropertyMap o) => o.Mapper) as PropertyInfo, new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(ReversivePropertyMapWithMapper)); nodeCompilers.Add(ReflectionHelper.GetMemberInfo<ReversivePropertyMap, ICollection<ReversiveTypeMap>>((ReversivePropertyMap o) => o.InheritanceMaps) as PropertyInfo, new Func<MapCompiler.CompilationContext, MapCompiler.CompilationResult>(ReversivePropertyMapWithInheritanceMaps)); } #endregion #region Public Methods public MapCompiler.CompilationResult Compile(TypeMapBase map, string contextualName) { if (!rootCompilers.ContainsKey(map.GetType())) { Error.MapValidationException_TypeMapIsNotSupported(map); } var arg = new MapCompiler.CompilationContext { Map = map, CurrentNode = map, ParentNode = null, ContextualName = contextualName }; return rootCompilers[map.GetType()](arg); } #endregion #region Private Methods private MapCompiler.CompilationResult TypeMap(MapCompiler.CompilationContext context) { var compilationResult = FirstNode(context); if (context.Map.Mapper != null) { return compilationResult; } else { TypeMap typeMap = context.Map as TypeMap; var list = new List<Action<object, object, TypeMappingContext>>(); var properties = typeMap.SourceType.GetProperties(BindingFlags.Instance | BindingFlags.Public); for (int i = 0; i < properties.Length; i++) { var sourcePropertyInfo = properties[i]; if (ReflectionHelper.IsSimple(sourcePropertyInfo.PropertyType) || ReflectionHelper.IsSimpleEnumerable(sourcePropertyInfo.PropertyType)) { if (!typeMap.PropertyMaps.Any((PropertyMap pm) => pm.SourcePropertyInfo == sourcePropertyInfo)) { PropertyInfo propertyInfo = FindDestintationProperty(typeMap.DestinationType, sourcePropertyInfo, context.ContextualName); if (!(propertyInfo == null)) { var getter = GetGetter(typeMap.SourceType, sourcePropertyInfo); var setter = GetSetter(typeMap.DestinationType, propertyInfo); if (ReflectionHelper.IsSimple(sourcePropertyInfo.PropertyType) && ReflectionHelper.IsSimple(propertyInfo.PropertyType)) { list.Add(Mappers.GetSimplePropertiesMapper( sourcePropertyInfo, propertyInfo, converters, getter, setter)); } else { if (ReflectionHelper.IsSimpleEnumerable(sourcePropertyInfo.PropertyType) && ReflectionHelper.IsSimpleEnumerable(propertyInfo.PropertyType)) { list.Add(Mappers.GetSimpleEnumerablePropertiesMapper( sourcePropertyInfo, propertyInfo, objectFactory, converters, getter, setter)); } } } } } } compilationResult = compilationResult ?? new MapCompiler.CompilationResult(); var mapper = compilationResult.Mapper; compilationResult.Mapper = Mappers.GetMapperWithSimplePropertyMappers(mapper, list); return compilationResult; } } private MapCompiler.CompilationResult MapWithMapper(MapCompiler.CompilationContext context) { var mapper = context.CurrentNode as Action<object, object, TypeMappingContext>; return new MapCompiler.CompilationResult { Mapper = mapper }; } private MapCompiler.CompilationResult TypeMapWithPropertyMaps(MapCompiler.CompilationContext context) { var enumerable = context.CurrentNode as IEnumerable<PropertyMapBase>; if (enumerable.Count<PropertyMapBase>() == 0) { return null; } else { var list = new List<Action<object, object, TypeMappingContext>>(); foreach (PropertyMapBase current in enumerable) { var compilationResult = FirstNode(new MapCompiler.CompilationContext { Map = context.Map, ContextualName = context.ContextualName, ParentNode = enumerable, CurrentNode = current }); list.Add(compilationResult.Mapper); } return new MapCompiler.CompilationResult { Mapper = Mappers.GetMapperWithPropertyMappers(list) }; } } private MapCompiler.CompilationResult PropertyMapWithInheritanceMaps(MapCompiler.CompilationContext context) { var enumerable = context.CurrentNode as IEnumerable<TypeMapBase>; if (enumerable == null || enumerable.Count<TypeMapBase>() == 0) { return null; } else { var propertyMapBase = context.ParentNode as PropertyMapBase; var mapperCollection = new MapperCollection(); string text = context.ContextualName; if (propertyMapBase.DestinationPropertyInfo == null) { text += propertyMapBase.SourcePropertyInfo.Name; } foreach (TypeMapBase current in enumerable) { mapperCollection.Add(current.SourceType, current.DestinationType, Compile(current, text).Mapper); } var compilationResult = new MapCompiler.CompilationResult(); var getter = GetGetter(context.Map.SourceType, propertyMapBase.SourcePropertyInfo); if (propertyMapBase.DestinationPropertyInfo == null) { compilationResult.Mapper = Mappers.GetMapperToRootType(getter, mapperCollection); return compilationResult; } else { var setter = GetSetter(context.Map.DestinationType, propertyMapBase.DestinationPropertyInfo); if (ReflectionHelper.IsComplex(propertyMapBase.SourcePropertyInfo.PropertyType) && ReflectionHelper.IsComplex(propertyMapBase.DestinationPropertyInfo.PropertyType)) { compilationResult.Mapper = Mappers.GetComplexPropertiesMapper(getter, setter, mapperCollection, objectFactory); return compilationResult; } else { if (ReflectionHelper.IsComplexEnumerable(propertyMapBase.SourcePropertyInfo.PropertyType) && ReflectionHelper.IsComplexEnumerable(propertyMapBase.DestinationPropertyInfo.PropertyType)) { compilationResult.Mapper = Mappers.GetComplexEnumerablePropertiesMapper(propertyMapBase .DestinationPropertyInfo.PropertyType, getter, setter, objectFactory, mapperCollection); return compilationResult; } return null; } } } } private MapCompiler.CompilationResult ReversiveTypeMap(MapCompiler.CompilationContext context) { var compilationResult = FirstNode(context); var reversiveTypeMap = context.Map as ReversiveTypeMap; if (reversiveTypeMap.Mapper != null && reversiveTypeMap.UnMapper != null) { return compilationResult; } else { var mappers = new List<Action<object, object, TypeMappingContext>>(); var unmappers = new List<Action<object, object, TypeMappingContext>>(); var properties = reversiveTypeMap.SourceType.GetProperties(BindingFlags.Instance | BindingFlags.Public); for (int i = 0; i < properties.Length; i++) { var sourcePropertyInfo = properties[i]; if (ReflectionHelper.IsSimple(sourcePropertyInfo.PropertyType) || ReflectionHelper.IsSimpleEnumerable(sourcePropertyInfo.PropertyType)) { if (!reversiveTypeMap.PropertyMaps.Any((ReversivePropertyMap pm) => pm.SourcePropertyInfo == sourcePropertyInfo)) { var propertyInfo = FindDestintationProperty(reversiveTypeMap.DestinationType, sourcePropertyInfo, context.ContextualName); if (!(propertyInfo == null)) { var sourceGetter = GetGetter(reversiveTypeMap.SourceType, sourcePropertyInfo); var sourceSetter = GetSetter(reversiveTypeMap.SourceType, sourcePropertyInfo); var destinationGetter = GetGetter(reversiveTypeMap.DestinationType, propertyInfo); var destinationSetter = GetSetter(reversiveTypeMap.DestinationType, propertyInfo); if (ReflectionHelper.IsSimple(sourcePropertyInfo.PropertyType) && ReflectionHelper.IsSimple(propertyInfo.PropertyType)) { mappers.Add(Mappers.GetSimplePropertiesMapper(sourcePropertyInfo, propertyInfo, converters, sourceGetter, destinationSetter)); unmappers.Add(Mappers.GetSimplePropertiesMapper(propertyInfo, sourcePropertyInfo, converters, destinationGetter, sourceSetter)); } else { if (ReflectionHelper.IsSimpleEnumerable(sourcePropertyInfo.PropertyType) && ReflectionHelper.IsSimpleEnumerable(propertyInfo.PropertyType)) { mappers.Add(Mappers.GetSimpleEnumerablePropertiesMapper(sourcePropertyInfo, propertyInfo, objectFactory, converters, sourceGetter, destinationSetter)); unmappers.Add(Mappers.GetSimpleEnumerablePropertiesMapper(propertyInfo, sourcePropertyInfo, objectFactory, converters, destinationGetter, sourceSetter)); } } } } } } compilationResult = (compilationResult ?? new MapCompiler.CompilationResult()); var mapper = compilationResult.Mapper; var unMapper = compilationResult.UnMapper; compilationResult.Mapper = Mappers.GetMapperWithSimplePropertyMappers(mapper, mappers); compilationResult.UnMapper = Mappers.GetMapperWithSimplePropertyMappers(unMapper, unmappers); return compilationResult; } } private MapCompiler.CompilationResult ReversiveTypeMapWithMapper(MapCompiler.CompilationContext context) { var compilationResult = MapWithMapper(context); compilationResult.UnMapper = ((ReversiveTypeMap)context.ParentNode).UnMapper; return compilationResult; } private MapCompiler.CompilationResult ReversiveTypeMapWithPropertyMaps(MapCompiler.CompilationContext context) { var enumerable = context.CurrentNode as IEnumerable<PropertyMapBase>; if (enumerable.Count<PropertyMapBase>() == 0) { return null; } else { var mappers = new List<Action<object, object, TypeMappingContext>>(); var unmappers = new List<Action<object, object, TypeMappingContext>>(); foreach (PropertyMapBase current in enumerable) { MapCompiler.CompilationResult compilationResult = FirstNode(new MapCompiler.CompilationContext { Map = context.Map, ContextualName = context.ContextualName, ParentNode = enumerable, CurrentNode = current }); mappers.Add(compilationResult.Mapper); unmappers.Add(compilationResult.UnMapper); } return new MapCompiler.CompilationResult { Mapper = Mappers.GetMapperWithPropertyMappers(mappers), UnMapper = Mappers.GetMapperWithPropertyMappers(unmappers) }; } } private MapCompiler.CompilationResult ReversivePropertyMapWithMapper(MapCompiler.CompilationContext context) { var compilationResult = MapWithMapper(context); compilationResult.UnMapper = ((ReversivePropertyMap)context.ParentNode).UnMapper; return compilationResult; } private MapCompiler.CompilationResult ReversivePropertyMapWithInheritanceMaps(MapCompiler.CompilationContext context) { var enumerable = context.CurrentNode as IEnumerable<TypeMapBase>; if (enumerable == null || enumerable.Count<TypeMapBase>() == 0) { return null; } else { var propertyMapBase = context.ParentNode as PropertyMapBase; var mapperCollection = new MapperCollection(); var unmapperCollection = new MapperCollection(); string text = context.ContextualName; if (propertyMapBase.DestinationPropertyInfo == null) { text += propertyMapBase.SourcePropertyInfo.Name; } foreach (TypeMapBase current in enumerable) { var compilationResult = Compile(current, text); mapperCollection.Add(current.SourceType, current.DestinationType, compilationResult.Mapper); unmapperCollection.Add(current.DestinationType, current.SourceType, compilationResult.UnMapper); } var compilationResult2 = new MapCompiler.CompilationResult(); var sourceGetter = GetGetter(context.Map.SourceType, propertyMapBase.SourcePropertyInfo); var sourceSetter = GetSetter(context.Map.SourceType, propertyMapBase.SourcePropertyInfo); if (propertyMapBase.DestinationPropertyInfo == null) { compilationResult2.Mapper = Mappers.GetMapperToRootType(sourceGetter, mapperCollection); compilationResult2.UnMapper = Mappers.GetMapperFromRootType(propertyMapBase.SourcePropertyInfo.PropertyType, sourceSetter, unmapperCollection, objectFactory); return compilationResult2; } else { var destinationGetter = GetGetter(context.Map.DestinationType, propertyMapBase.DestinationPropertyInfo); var destinationSetter = GetSetter(context.Map.DestinationType, propertyMapBase.DestinationPropertyInfo); if (ReflectionHelper.IsComplex(propertyMapBase.SourcePropertyInfo.PropertyType) && ReflectionHelper.IsComplex(propertyMapBase.DestinationPropertyInfo.PropertyType)) { compilationResult2.Mapper = Mappers.GetComplexPropertiesMapper(sourceGetter, destinationSetter, mapperCollection, objectFactory); compilationResult2.UnMapper = Mappers.GetComplexPropertiesMapper(destinationGetter, sourceSetter, unmapperCollection, objectFactory); return compilationResult2; } else { if (ReflectionHelper.IsComplexEnumerable(propertyMapBase.SourcePropertyInfo.PropertyType) && ReflectionHelper.IsComplexEnumerable(propertyMapBase.DestinationPropertyInfo.PropertyType)) { compilationResult2.Mapper = Mappers.GetComplexEnumerablePropertiesMapper(propertyMapBase.DestinationPropertyInfo .PropertyType, sourceGetter, destinationSetter, objectFactory, mapperCollection); compilationResult2.UnMapper = Mappers.GetComplexEnumerablePropertiesMapper(propertyMapBase.SourcePropertyInfo .PropertyType, destinationGetter, sourceSetter, objectFactory, unmapperCollection); return compilationResult2; } else { return null; } } } } } private MapCompiler.CompilationResult FirstNode(MapCompiler.CompilationContext currentNodeContext) { var properties = currentNodeContext.CurrentNode.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); for (int i = 0; i < properties.Length; i++) { var propertyInfo = properties[i]; if (nodeCompilers.ContainsKey(propertyInfo)) { var value = propertyInfo.GetValue(currentNodeContext.CurrentNode, null); if (value != null) { var compilationResult = nodeCompilers[propertyInfo](new MapCompiler.CompilationContext { Map = currentNodeContext.Map, ParentNode = currentNodeContext.CurrentNode, CurrentNode = value, ContextualName = currentNodeContext.ContextualName }); if (compilationResult != null) { return compilationResult; } } } } return null; } private PropertyInfo FindDestintationProperty(Type destinationType, PropertyInfo sourcePropertyInfo, string contextualName) { var property = destinationType.GetProperty(string.Format("{0}{1}{2}", sourcePropertyInfo.DeclaringType.Name, contextualName, sourcePropertyInfo.Name)); if (property == null) { property = destinationType.GetProperty(string.Format("{0}{1}", contextualName, sourcePropertyInfo.Name)); } return property; } private Func<object, object> GetGetter(Type type, PropertyInfo pi) { if (!getters.ContainsKey(pi)) { getters.Add(pi, ReflectionHelper.CreateGetter(type, pi)); } return getters[pi]; } private Action<object, object> GetSetter(Type type, PropertyInfo pi) { if (!setters.ContainsKey(pi)) { setters.Add(pi, ReflectionHelper.CreateSetter(type, pi)); } return setters[pi]; } #endregion #region Classes internal sealed class CompilationResult { #region Public Properties public Action<object, object, TypeMappingContext> Mapper { get; set; } public Action<object, object, TypeMappingContext> UnMapper { get; set; } #endregion } private sealed class CompilationContext { #region Public Properties public TypeMapBase Map { get; set; } public object ParentNode { get; set; } public object CurrentNode { get; set; } public string ContextualName { get; set; } #endregion } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using NMahjong.Aux; using IEnumerable = System.Collections.IEnumerable; using IEnumerator = System.Collections.IEnumerator; namespace NMahjong.Base { /** <summary> Contains player-wise information. </summary> <typeparam name="T"> The type of the items containing information. </typeparam> <remarks> Use the <see cref="Quad"/> class (with no type parameter) to create an instance of <see cref="Quad{T}"/>. </remarks> <seealso cref="Quad"/> */ public sealed class Quad<T> : IList<T> { private readonly T[] mItems; private Quad(T[] items) { mItems = items; } internal static Quad<T> Create(T x0, T x1, T x2, T x3) { return new Quad<T>(new [] {x0, x1, x2, x3}); } internal static Quad<T> Create(IEnumerable<T> items) { return new Quad<T>(items.ToArray()); } /** <summary> Gets the item for the specified player number. </summary> <param name="index"> The player number of the item to get. </param> <value> The item at <paramref name="index"/>. </value> <exception cref="ArgumentOutOfRangeException"> <paramref name="index"/> is not in the range between 0 and 3. </exception> */ public T this[int index] { get { CheckArg.Range(index, "index", 0, 3); return mItems[index]; } } /** <summary> Gets the item for the specified player. </summary> <param name="player"> The player of the item to get. </param> <value> The item associated to <paramref name="player"/>. </value> */ public T this[PlayerId player] { get { return mItems[player.Id]; } } /** <summary> Returns an enumerator that iterates over this <see cref="Quad{T}"/>. </summary> <returns> An enumerator to iterate over this <see cref="Quad{T}"/>. </returns> */ public IEnumerator<T> GetEnumerator() { return (mItems as IEnumerable<T>).GetEnumerator(); } #region Explicit Interface Implementaions /** <summary> Gets or sets the item at the specified index. </summary> <param name="index"> The zero-based index of the item to get or set. </param> <value> The item at <paramref name="index"/>. </value> <exception cref="ArgumentOutOfRangeException"> <paramref name="index"/> is negative. <para>-or-</para> <paramref name="index"/> is equal to or greater than <see cref="ICollection{T}.Count"/>. </exception> <exception cref="NotSupportedException"> The property is set. </exception> */ T IList<T>.this[int index] { get { return this[index]; } set { throw new NotSupportedException("Collection is read-only."); } } /** <summary> Gets the number of items contained in this collection. </summary> <value> The number of items in this collection (4). </value> */ int ICollection<T>.Count { get { return 4; } } /** <summary> Indicates whether this collection is read-only. </summary> <value> <see langword="true"/>. </value> */ bool ICollection<T>.IsReadOnly { get { return true; } } /** <summary> Adds an item to this collection. This operation is not supported. </summary> <param name="item"> The item to add to this collection (ignored). </param> <exception cref="NotSupportedException"> Always thrown. </exception> */ void ICollection<T>.Add(T item) { throw new NotSupportedException("Collection is read-only."); } /** <summary> Removes all items from this collection. This operation is not supported. </summary> <exception cref="NotSupportedException"> Always thrown. </exception> */ void ICollection<T>.Clear() { throw new NotSupportedException("Collection is read-only."); } /** <summary> Determines whether this collection contains a specific value. </summary> <param name="item"> The object to locate in this collection. </param> <returns> <see langword="true"/> if <paramref name="item"/> is found in this collection; otherwise, <see langword="false"/>. </returns> */ bool ICollection<T>.Contains(T item) { return Array.IndexOf(mItems, item) >= 0; } /** <summary> Copies the items of this collection to an array. </summary> <param name="array"> The destination array. </param> <param name="index"> The zero-based index in <paramref name="array"/> from which the items are copied. </param> <exception cref="ArgumentNullException"> <paramref name="array"/> is <see langword="null"/>. </exception> <exception cref="ArgumentOutOfRangeException"> <paramref name="index"/> is negative. </exception> <exception cref="ArgumentException"> <paramref name="array"/> is not one-dimensional. <para>-or-</para> <paramref name="array"/> does not have space enough to store the copied items from <paramref name="index"/>. </exception> */ void ICollection<T>.CopyTo(T[] array, int index) { mItems.CopyTo(array, index); } /** <summary> Returns an enumerator that iterates over this <see cref="Quad{T}"/>. </summary> <returns> An enumerator to iterate over this <see cref="Quad{T}"/>. </returns> */ IEnumerator IEnumerable.GetEnumerator() { return mItems.GetEnumerator(); } /** <summary> Searches for the specified object and returns the zero-based index of the first occurrence in this collection. </summary> <param name="item"> The object to locate in this collection. </param> <returns> The zero-based index of the first occurrence of <paramref name="item"/> in this collection, if it is found; otherwise, -1. </returns> */ int IList<T>.IndexOf(T item) { return Array.IndexOf(mItems, item); } /** <summary> Inserts an item to this collection at the specified index. This operation is not supported. </summary> <param name="index"> The zero-based index at which <paramref name="item"/> to be inserted (ignored). </param> <param name="item"> The item to insert (ignored). </param> <exception cref="NotSupportedException"> Always thrown. </exception> */ void IList<T>.Insert(int index, T item) { throw new NotSupportedException("Collection is read-only."); } /** <summary> Removes the first occurrence of the specified object from this collection. This operation is not supported. </summary> <param name="item"> The object to be removed from this collection (ignored). </param> <returns> This method never returns a value. </returns> <exception cref="NotSupportedException"> Always thrown. </exception> */ bool ICollection<T>.Remove(T item) { throw new NotSupportedException("Collection is read-only."); } /** <summary> Removes the item at the specified index. This operation is not supported. </summary> <param name="index"> The zero-based index of the item to remove (ignored). </param> <exception cref="NotSupportedException"> Always thrown. </exception> */ void IList<T>.RemoveAt(int index) { throw new NotSupportedException("Collection is read-only."); } #endregion // Explicit Interface Implementaions } /** <summary> Provides methods to construct <see cref="Quad{T}"/> instances. </summary> */ public static class Quad { /** <summary> Creates a new instance of <see cref="Quad{T}"/> with the specified items. </summary> <param name="item0"> The item to associate to Player #0. </param> <param name="item1"> The item to associate to Player #1. </param> <param name="item2"> The item to associate to Player #2. </param> <param name="item3"> The item to associate to Player #3. </param> <returns> A <see cref="Quad{T}"/> containing the specified items. </returns> */ public static Quad<T> Of<T>(T item0, T item1, T item2, T item3) { return Quad<T>.Create(item0, item1, item2, item3); } /** <summary> Creates a new instance of <see cref="Quad{T}"/> with the specified items. </summary> <param name="items"> An <see cref="IEnumerable{T}"/> containing exactly four items. </param> <returns> A <see cref="Quad{T}"/> containing the specified items. </returns> <exception cref="ArgumentNullException"> <paramref name="items"/> is <see langword="null"/>. </exception> <exception cref="ArgumentException"> <paramref name="items"/> contains more than or less than four items. </exception> */ public static Quad<T> Of<T>(IEnumerable<T> items) { CheckArg.NotNull(items, "items"); CheckArg.Expect(items.Count() == 4, "items", "Sequence must contain exactly four items."); return Quad<T>.Create(items); } /** <summary> Creates a new instance of <see cref="Quad{T}"/> with the specified items and offset. </summary> <param name="items"> A <see cref="IList{T}"/> containing exactly four items. </param> <param name="offset"> A zero-based index of the item in <paramref name="items"/> to associate to Player #0. </param> <returns> A <see cref="Quad{T}"/> containing the specified items, in which <paramref name="items"/>[<paramref name="offset"/>] is associated to Player #0, the next one (with loop-around) is associated to Player #1, and so forth. </returns> <remarks> <para> This method is equivalent to the following code: <code language="cs"> Quad.Of(items[offset], items[(offset + 1) % 4], items[(offset + 2) % 4], items[(offset + 3) % 4]) </code> </para> </remarks> <exception cref="ArgumentNullException"> <paramref name="items"/> is <see langword="null"/>. </exception> <exception cref="ArgumentOutOfRangeException"> <paramref name="offset"/> is not in the range between 0 and 3. </exception> <exception cref="ArgumentException"> <paramref name="items"/> contains more than or less than four items. </exception> */ public static Quad<T> Of<T>(IList<T> items, int offset) { CheckArg.NotNull(items, "items"); CheckArg.Expect(items.Count == 4, "items", "Sequence must contain exactly four items."); CheckArg.Range(offset, "offset", 0, 3); return Quad.Of(index => items[(index + offset) % 4]); } /** <summary> Creates a new instance of <see cref="Quad{T}"/> with the specified item generator function. </summary> <param name="generator"> A function that takes a player number and returns the item for that player. </param> <returns> A <see cref="Quad{T}"/> containing the items generated by <paramref name="generator"/>. </returns> <exception cref="ArgumentNullException"> <paramref name="generator"/> is <see langword="null"/>. </exception> */ public static Quad<T> Of<T>(Func<Int32, T> generator) { CheckArg.NotNull(generator, "generator"); return Quad<T>.Create(Enumerable.Range(0, 4).Select(generator)); } } }
using IntuiLab.Leap.Events; using IntuiLab.Leap.Recognition.Postures; using System; using System.ComponentModel; namespace IntuiLab.Leap { /// <summary> /// A facade for the shifumi posture Enable/Disable properties and events /// </summary> public class PostureShifumiFacade : INotifyPropertyChanged, IDisposable { public event PropertyChangedEventHandler PropertyChanged; internal void NotifyPropertyChanged(String strInfo) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(strInfo)); } } #region Properties #region Enable/Disable Properties /// <summary> /// Enable or disable the Rock posture /// </summary> private bool m_enableRockPosture; public bool EnableRockPosture { get { return m_enableRockPosture; } set { if (value && !m_enableRockPosture) { LeapPlugin.Instance.LeapListener.EnablePostureRecognition(PostureType.Rock); LeapPlugin.Instance.LeapListener.RockPostureSucceed += OnRockPostureSucceed; LeapPlugin.Instance.LeapListener.RockPostureDetectionInProgress += OnRockPostureDetectionInProgress; LeapPlugin.Instance.LeapListener.RockPostureDetectionLost += OnRockPostureDetectionLost; } else if (!value && m_enableRockPosture) { LeapPlugin.Instance.LeapListener.DisablePostureRecognition(PostureType.Rock); LeapPlugin.Instance.LeapListener.RockPostureSucceed -= OnRockPostureSucceed; LeapPlugin.Instance.LeapListener.RockPostureDetectionInProgress -= OnRockPostureDetectionInProgress; LeapPlugin.Instance.LeapListener.RockPostureDetectionLost -= OnRockPostureDetectionLost; } m_enableRockPosture = value; NotifyPropertyChanged("EnableRockPosture"); } } /// <summary> /// Enable or disable the Scissors posture /// </summary> private bool m_enableScissorsPosture; public bool EnableScissorsPosture { get { return m_enableScissorsPosture; } set { if (value && !m_enableScissorsPosture) { LeapPlugin.Instance.LeapListener.EnablePostureRecognition(PostureType.Scissors); LeapPlugin.Instance.LeapListener.ScissorsPostureSucceed += OnScissorsPostureSucceed; LeapPlugin.Instance.LeapListener.ScissorsPostureDetectionInProgress += OnScissorsPostureDetectionInProgress; LeapPlugin.Instance.LeapListener.ScissorsPostureDetectionLost += OnScissorsPostureDetectionLost; } else if (!value && m_enableScissorsPosture) { LeapPlugin.Instance.LeapListener.DisablePostureRecognition(PostureType.Scissors); LeapPlugin.Instance.LeapListener.ScissorsPostureSucceed -= OnScissorsPostureSucceed; LeapPlugin.Instance.LeapListener.ScissorsPostureDetectionInProgress -= OnScissorsPostureDetectionInProgress; LeapPlugin.Instance.LeapListener.ScissorsPostureDetectionLost -= OnScissorsPostureDetectionLost; } m_enableScissorsPosture = value; NotifyPropertyChanged("EnableScissorsPosture"); } } /// <summary> /// Enable or disable the Paper posture /// </summary> private bool m_enablePaperPosture; public bool EnablePaperPosture { get { return m_enablePaperPosture; } set { if (value && !m_enablePaperPosture) { LeapPlugin.Instance.LeapListener.EnablePostureRecognition(PostureType.Paper); LeapPlugin.Instance.LeapListener.PaperPostureSucceed += OnPaperPostureSucceed; LeapPlugin.Instance.LeapListener.PaperPostureDetectionInProgress += OnPaperPostureDetectionInProgress; LeapPlugin.Instance.LeapListener.PaperPostureDetectionLost += OnPaperPostureDetectionLost; } else if (!value && m_enablePaperPosture) { LeapPlugin.Instance.LeapListener.DisablePostureRecognition(PostureType.Paper); LeapPlugin.Instance.LeapListener.PaperPostureSucceed -= OnPaperPostureSucceed; LeapPlugin.Instance.LeapListener.PaperPostureDetectionInProgress -= OnPaperPostureDetectionInProgress; LeapPlugin.Instance.LeapListener.PaperPostureDetectionLost -= OnPaperPostureDetectionLost; } m_enablePaperPosture = value; NotifyPropertyChanged("EnablePaperPosture"); } } #endregion #region Detection Time /// <summary> /// The detection time of the rock posture in milliseconds /// </summary> public int DetectionTimeForRockInMilliseconds { get { return ParametersScheduler.Instance.NbEventsForRockPostureToBeDetected * 10; } set { ParametersScheduler.Instance.NbEventsForRockPostureToBeDetected = value / 10; NotifyPropertyChanged("DetectionTimeForRockInMilliseconds"); } } /// <summary> /// The detection time of the scissors posture in milliseconds /// </summary> public int DetectionTimeForScissorsInMilliseconds { get { return ParametersScheduler.Instance.NbEventsForScissorsPostureToBeDetected * 10; } set { ParametersScheduler.Instance.NbEventsForScissorsPostureToBeDetected = value / 10; NotifyPropertyChanged("DetectionTimeForScissorsInMilliseconds"); } } /// <summary> /// The detection time of the paper posture in milliseconds /// </summary> public int DetectionTimeForPaperInMilliseconds { get { return ParametersScheduler.Instance.NbEventsForPaperPostureToBeDetected * 10; } set { ParametersScheduler.Instance.NbEventsForPaperPostureToBeDetected = value / 10; NotifyPropertyChanged("DetectionTimeForPaperInMilliseconds"); } } #endregion #endregion #region Events public event PostureEventHandler RockPostureSucceed; public event PostureEventHandler RockPostureDetectionInProgress; public event PostureEventHandler RockPostureDetectionLost; public event PostureEventHandler PaperPostureSucceed; public event PostureEventHandler PaperPostureDetectionInProgress; public event PostureEventHandler PaperPostureDetectionLost; public event PostureEventHandler ScissorsPostureSucceed; public event PostureEventHandler ScissorsPostureDetectionInProgress; public event PostureEventHandler ScissorsPostureDetectionLost; private void RaiseRockPostureSucceed(PostureEventArgs e) { if (RockPostureSucceed != null) { RockPostureSucceed(this, e); } } private void RaiseRockPostureDetectionInProgress(PostureEventArgs e) { if (RockPostureDetectionInProgress != null) { RockPostureDetectionInProgress(this, e); } } private void RaiseRockPostureDetectionLost(PostureEventArgs e) { if (RockPostureDetectionLost != null) RockPostureDetectionLost(this, e); } private void RaisePaperPostureSucceed(PostureEventArgs e) { if (PaperPostureSucceed != null) { PaperPostureSucceed(this, e); } } private void RaisePaperPostureDetectionInProgress(PostureEventArgs e) { if (PaperPostureDetectionInProgress != null) { PaperPostureDetectionInProgress(this, e); } } private void RaisePaperPostureDetectionLost(PostureEventArgs e) { if (PaperPostureDetectionLost != null) PaperPostureDetectionLost(this, e); } private void RaiseScissorsPostureSucceed(PostureEventArgs e) { if (ScissorsPostureSucceed != null) { ScissorsPostureSucceed(this, e); } } private void RaiseScissorsPostureDetectionInProgress(PostureEventArgs e) { if (ScissorsPostureDetectionInProgress != null) { ScissorsPostureDetectionInProgress(this, e); } } private void RaiseScissorsPostureDetectionLost(PostureEventArgs e) { if (ScissorsPostureDetectionLost != null) ScissorsPostureDetectionLost(this, e); } private void OnRockPostureSucceed(object sender, PostureEventArgs e) { RaiseRockPostureSucceed(e); } private void OnRockPostureDetectionInProgress(object sender, PostureEventArgs e) { RaiseRockPostureDetectionInProgress(e); } private void OnRockPostureDetectionLost(object sender, PostureEventArgs e) { RaiseRockPostureDetectionLost(e); } private void OnPaperPostureSucceed(object sender, PostureEventArgs e) { RaisePaperPostureSucceed(e); } private void OnPaperPostureDetectionInProgress(object sender, PostureEventArgs e) { RaisePaperPostureDetectionInProgress(e); } private void OnPaperPostureDetectionLost(object sender, PostureEventArgs e) { RaisePaperPostureDetectionLost(e); } private void OnScissorsPostureSucceed(object sender, PostureEventArgs e) { RaiseScissorsPostureSucceed(e); } private void OnScissorsPostureDetectionInProgress(object sender, PostureEventArgs e) { RaiseScissorsPostureDetectionInProgress(e); } private void OnScissorsPostureDetectionLost(object sender, PostureEventArgs e) { RaiseScissorsPostureDetectionLost(e); } #endregion #region Constructor public PostureShifumiFacade() { // if the LeapPlugin is not already instantiated, we do it if (LeapPlugin.Instance == null) { LeapPlugin temp = new LeapPlugin(); } this.m_enableRockPosture = false; this.m_enableScissorsPosture = false; this.m_enablePaperPosture = false; EnableRockPosture = true; EnableScissorsPosture = true; EnablePaperPosture = true; Main.RegisterFacade(this); } #endregion /// <summary> /// Clear the resources /// </summary> public void Dispose() { EnableRockPosture = false; EnableScissorsPosture = false; EnablePaperPosture = false; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration namespace _4PosBackOffice.NET { internal partial class frmLang : System.Windows.Forms.Form { int gParentID; bool grClick; private void loadKeys(ref short secID) { string sql = null; ADODB.Recordset rs = default(ADODB.Recordset); int x = 0; string kS = null; gridEdit.RowCount = 1; rs = modRecordSet.getRS(ref "SELECT LanguageLayout.LanguageLayoutID, LanguageLayout.LanguageLayout_Name From LanguageLayout WHERE (((LanguageLayout.LanguageLayoutID)=" + gParentID + "));"); if (rs.RecordCount) { modRecordSet.cnnDB.Execute("INSERT INTO LanguageLayoutLnk ( LanguageLayoutLnk_LanguageID, LanguageLayoutLnk_LanguageLayoutID, LanguageLayoutLnk_Description, LanguageLayoutLnk_RightTL, LanguageLayoutLnk_Screen ) SELECT theJoin.LanguageID, theJoin.LanguageLayoutID, 'None' AS Expr1, 0 AS Expr2, 'None' AS Expr3 FROM (SELECT Language.LanguageID, LanguageLayout.LanguageLayoutID From Language, LanguageLayout WHERE (((LanguageLayout.LanguageLayoutID)=" + gParentID + "))) AS theJoin LEFT JOIN LanguageLayoutLnk ON (theJoin.LanguageID = LanguageLayoutLnk.LanguageLayoutLnk_LanguageID) AND (theJoin.LanguageLayoutID = LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID) WHERE (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageID) Is Null));"); sql = "UPDATE LanguageLayoutLnk AS LanguageLayoutLnk_1 INNER JOIN LanguageLayoutLnk ON LanguageLayoutLnk_1.LanguageLayoutLnk_LanguageID = LanguageLayoutLnk.LanguageLayoutLnk_LanguageID SET LanguageLayoutLnk.LanguageLayoutLnk_Description = [LanguageLayoutLnk_1]![LanguageLayoutLnk_Description], LanguageLayoutLnk.LanguageLayoutLnk_RightTL = [LanguageLayoutLnk_1]![LanguageLayoutLnk_RightTL], LanguageLayoutLnk.LanguageLayoutLnk_Section = [LanguageLayoutLnk_1]![LanguageLayoutLnk_Section], LanguageLayoutLnk.LanguageLayoutLnk_Screen = [LanguageLayoutLnk_1]![LanguageLayoutLnk_Screen] "; sql = sql + "WHERE (((LanguageLayoutLnk.LanguageLayoutLnk_Description)='None') AND ((LanguageLayoutLnk.LanguageLayoutLnk_Screen)='None') AND ((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID)=" + gParentID + ") AND ((LanguageLayoutLnk_1.LanguageLayoutLnk_LanguageLayoutID)=1));"; if (gParentID != 1) modRecordSet.cnnDB.Execute(sql); this.txtName.Text = rs.Fields("LanguageLayout_Name").Value; rs = modRecordSet.getRS(ref "SELECT Language.*, LanguageLayoutLnk.* FROM LanguageLayoutLnk INNER JOIN Language ON LanguageLayoutLnk.LanguageLayoutLnk_LanguageID = Language.LanguageID Where (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID) = " + gParentID + ") AND ((LanguageLayoutLnk.LanguageLayoutLnk_Section) = " + secID + ")) ORDER BY LanguageLayoutLnk_LanguageID;"); gridEdit.RowCount = rs.RecordCount + 1; x = 0; while (!(rs.EOF)) { x = x + 1; gridEdit.row = x; gridEdit.Col = 0; gridEdit.Text = rs.Fields("LanguageLayoutLnk_Description").Value; gridEdit.CellAlignment = 1; gridEdit.Col = 1; if (rs.Fields("LanguageLayoutLnk_RightTL").Value == true) { kS = "Yes"; } else { kS = "No"; } gridEdit.Text = Strings.UCase(kS); //gridEdit.Text = getKeyDescription(rs("LanguageLayoutLnk_Key"), rs("LanguageLayoutLnk_Shift")) gridEdit.Col = 2; gridEdit.Text = (Information.IsDBNull(rs.Fields("LanguageLayoutLnk_Screen").Value) ? "NOT ASSIGNED" : rs.Fields("LanguageLayoutLnk_Screen").Value); //rs("LanguageLayoutLnk_Screen") //gridEdit.Col = 3 //gridEdit.Text = rs("LanguageLayoutLnk_Key") gridEdit.set_RowData(ref gridEdit.row, ref rs.Fields("LanguageLayoutLnk_LanguageID").Value); //gridEdit.Col = 4 //gridEdit.Text = rs("Language_Order") //gridEdit.RowData(gridEdit.row) = rs("LanguageLayoutLnk_LanguageID") //gridEdit.Col = 5 //If rs("Language_Show") = True Then // kS = "Yes" //Else // kS = "No" //End If //gridEdit.Text = UCase(kS) //gridEdit.Col = 6 //gridEdit.Text = rs("LanguageID") //gridEdit.RowData(gridEdit.row) = rs("LanguageLayoutLnk_LanguageID") rs.moveNext(); } } } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { modRecordSet.cnnDB.Execute("UPDATE LanguageLayout SET LanguageLayout.LanguageLayout_Name = '" + Strings.Replace(txtName.Text, "'", "''") + "' WHERE (((LanguageLayout.LanguageLayoutID)=" + gParentID + "));"); System.Windows.Forms.Application.DoEvents(); modRecordSet.cnnDB.Execute("UPDATE LanguageLayout SET LanguageLayout.LanguageLayout_Name = '" + Strings.Replace(txtName.Text, "'", "''") + "' WHERE (((LanguageLayout.LanguageLayoutID)=" + gParentID + "));"); this.Close(); } public void loadItem(ref short lParentID) { gParentID = lParentID; //loadKeys Option1_CheckedChanged(Option1, new System.EventArgs()); Option1.Checked = true; ShowDialog(); } private void frmLang_Load(System.Object eventSender, System.EventArgs eventArgs) { grClick = true; var _with1 = gridEdit; _with1.Col = 3; _with1.RowCount = 0; System.Windows.Forms.Application.DoEvents(); _with1.RowCount = 2; _with1.FixedRows = 1; _with1.FixedCols = 0; _with1.row = 0; _with1.Col = 0; _with1.CellFontBold = true; _with1.Text = "Translation"; _with1.set_ColWidth(0, 11200); _with1.CellAlignment = 3; _with1.Col = 1; _with1.CellFontBold = true; _with1.Text = "Right To Left"; _with1.set_ColWidth(1, 1200); _with1.CellAlignment = 4; _with1.Col = 2; _with1.CellFontBold = true; _with1.Text = "Screen"; _with1.set_ColWidth(2, 1500); _with1.CellAlignment = 1; //.Col = 3 //.CellFontBold = True //.Text = "Keycode" //.ColWidth(3) = 0 //.CellAlignment = 1 //.Col = 4 //.CellFontBold = True //.Text = "Display" //.ColWidth(4) = 800 //.CellAlignment = 1 //.Col = 5 //.CellFontBold = True //.Text = "Show" //.ColWidth(5) = 800 //.CellAlignment = 1 //.Col = 6 //.CellFontBold = True //.Text = "KEY" //.ColWidth(6) = 0 //.CellAlignment = 1 } public object getKeyDescription(ref short KeyCode, ref short Shift) { string lShift = null; string lKey = null; switch (KeyCode) { case 16: case 17: case 18: break; case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: lKey = "F" + KeyCode - 111; break; case 37: lKey = "Left"; break; case 38: lKey = "Up"; break; case 39: lKey = "Right"; break; case 40: lKey = "Down"; break; case 27: lKey = "Esc"; break; case 13: lKey = "Enter"; break; case 35: lKey = "End"; break; case 34: lKey = "PgDn"; break; case 33: lKey = "PgUp"; break; case 36: lKey = "Home"; break; case 46: lKey = "Del"; break; case 45: lKey = "Ins"; break; case 19: lKey = "Pause"; break; case 9: lKey = "Tab"; break; case 8: lKey = "Back Space"; break; default: lKey = Strings.Chr(KeyCode); break; } switch (Shift) { case 1: lShift = "Shift+"; break; case 2: lShift = "Ctrl+"; break; case 4: lShift = "Alt+"; break; default: lShift = ""; break; } //UPGRADE_WARNING: Couldn't resolve default property of object getKeyDescription. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' return lShift + lKey; } // Handles gridEdit.ClickEvent private void gridEdit_ClickEvent(System.Object eventSender, System.EventArgs eventArgs) { frmLangGet frmLanguageGet = null; int InLanguage = 0; MsgBoxResult inres = default(MsgBoxResult); int k_ID = 0; string lName = null; string sScreen = null; bool bRTL = false; string kView = null; short inRe = 0; short lKey = 0; short lShift = 0; ADODB.Recordset rs = default(ADODB.Recordset); if (grClick == true) { grClick = false; return; } lName = Strings.Trim(gridEdit.get_TextMatrix(ref gridEdit.row, ref 0)); kView = Strings.UCase(Strings.Trim(gridEdit.get_TextMatrix(ref gridEdit.row, ref 1))); if (kView == "YES") { bRTL = true; } else { bRTL = false; } sScreen = Strings.Trim(gridEdit.get_TextMatrix(ref gridEdit.row, ref 2)); My.MyProject.Forms.frmLangGet.getLanguageValue(ref lName, ref bRTL, ref sScreen); if (!string.IsNullOrEmpty(lName)) { //Set rs = getRS("SELECT Language.* From Language WHERE (((Language.Language_Shift)=" & lShift & ") AND ((Language.Language_Key)=" & lKey & "));") rs = modRecordSet.getRS(ref "SELECT Language.LanguageID, Language.Language_Description, LanguageLayoutLnk.* FROM LanguageLayoutLnk INNER JOIN Language ON LanguageLayoutLnk.LanguageLayoutLnk_LanguageID = Language.LanguageID Where (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID) = " + gParentID + ") AND ((LanguageLayoutLnk.LanguageLayoutLnk_LanguageID)=" + gridEdit.get_RowData(ref gridEdit.row) + "))"); if (rs.RecordCount) { // If rs("LanguageID") = gridEdit.RowData(gridEdit.row) Then // Else // MsgBox "Cannot allocate this key as it is allocated to '" & rs("Language_Name") & "!", vbExclamation, "Language LAYOUT" // End If //Else // lName = getKeyDescription(lKey, lShift) lName = Strings.Replace(lName, ",", "-"); lName = Strings.Replace(lName, "'", "''"); modRecordSet.cnnDB.Execute("UPDATE LanguageLayoutLnk SET LanguageLayoutLnk.LanguageLayoutLnk_RightTL = " + bRTL + ", LanguageLayoutLnk.LanguageLayoutLnk_Description = '" + lName + "' WHERE (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID)=" + gParentID + ") AND ((LanguageLayoutLnk.LanguageLayoutLnk_LanguageID)=" + gridEdit.get_RowData(ref gridEdit.row) + "));"); //cnnDB.Execute "UPDATE LanguageLayoutLnk SET LanguageLayoutLnk.LanguageLayoutLnk_Shift = " & lShift & ", LanguageLayoutLnk.LanguageLayoutLnk_Key = " & lKey & ", LanguageLayoutLnk.LanguageLayoutLnk_Description = '" & lName & "' WHERE (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID)=" & gParentID & ") AND ((LanguageLayoutLnk.LanguageLayoutLnk_LanguageID)=" & gridEdit.RowData(gridEdit.row) & "));" // gridEdit.TextMatrix(gridEdit.row, 3) = lKey if (bRTL == true) { gridEdit.set_TextMatrix(ref gridEdit.row, ref 1, ref "YES"); } else { gridEdit.set_TextMatrix(ref gridEdit.row, ref 1, ref "NO"); } gridEdit.set_TextMatrix(ref gridEdit.row, ref 0, ref lName); } } return; kView = Strings.UCase(Strings.Trim(gridEdit.get_TextMatrix(ref gridEdit.row, ref gridEdit.Col))); if (kView == "YES" | kView == "NO") { k_ID = Conversion.Val(gridEdit.get_TextMatrix(ref gridEdit.row, ref gridEdit.Col + 1)); if (kView == "YES") { inres = Interaction.MsgBox("Do you want to hide Key on Language", MsgBoxStyle.ApplicationModal + MsgBoxStyle.YesNo + MsgBoxStyle.Question, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); if (inres == MsgBoxResult.Yes) { modRecordSet.cnnDB.Execute("UPDATE Language SET Language_Show = 0 WHERE LanguageID = " + k_ID); gridEdit.set_TextMatrix(ref gridEdit.row, ref gridEdit.Col, ref "NO"); } } else if (kView == "NO") { inres = Interaction.MsgBox("Do you want to show Key on Language", MsgBoxStyle.ApplicationModal + MsgBoxStyle.YesNo + MsgBoxStyle.Question, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); if (inres == MsgBoxResult.Yes) { modRecordSet.cnnDB.Execute("UPDATE Language SET Language_Show = 1 WHERE LanguageID = " + k_ID); gridEdit.set_TextMatrix(ref gridEdit.row, ref gridEdit.Col, ref "YES"); } } return; } lName = gridEdit.get_TextMatrix(ref gridEdit.row, ref 0); //k_ID = Val(gridEdit.TextMatrix(gridEdit.row, 6)) //Do Display Option..... if (gridEdit.Col > 0) { if (Conversion.Val(kView) > 0) { if (Conversion.Val(kView) < 100) { My.MyProject.Forms.frmChangeDisplay.lblName.Text = lName; My.MyProject.Forms.frmChangeDisplay.txtNumber.Text = Strings.Trim(kView); My.MyProject.Forms.frmChangeDisplay.ShowDialog(); if (InLanguage == 200) { } else { modRecordSet.cnnDB.Execute("UPDATE Language SET Language_Order = " + InLanguage + " WHERE LanguageID = " + k_ID); var _with2 = gridEdit; _with2.Text = Conversion.Str(InLanguage); if (Option1.Checked) loadKeys(ref ref 0); if (Option2.Checked) loadKeys(ref ref 2); if (Option3.Checked) loadKeys(ref ref 1); } } return; } } lName = gridEdit.get_TextMatrix(ref gridEdit.row, ref 0); //lKey = gridEdit.TextMatrix(gridEdit.row, 3) //lShift = gridEdit.TextMatrix(gridEdit.row, 2) //UPGRADE_WARNING: Couldn't resolve default property of object frmLanguageGet.getLanguageValue. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' frmLanguageGet.getLanguageValue(ref lName, ref lKey, ref lShift); if (lKey != 0) { //Set rs = getRS("SELECT Language.* From Language WHERE (((Language.Language_Shift)=" & lShift & ") AND ((Language.Language_Key)=" & lKey & "));") rs = modRecordSet.getRS(ref "SELECT Language.LanguageID, Language.Language_Name, LanguageLayoutLnk.* FROM LanguageLayoutLnk INNER JOIN Language ON LanguageLayoutLnk.LanguageLayoutLnk_LanguageID = Language.LanguageID Where (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID) = " + gParentID + ") AND ((LanguageLayoutLnk.LanguageLayoutLnk_Shift)=" + lShift + ") AND ((LanguageLayoutLnk.LanguageLayoutLnk_Key)=" + lKey + "))"); if (rs.RecordCount) { if (rs.Fields("LanguageID").Value == gridEdit.get_RowData(ref gridEdit.row)) { } else { Interaction.MsgBox("Cannot allocate this key as it is allocated to '" + rs.Fields("Language_Name").Value + "!", MsgBoxStyle.Exclamation, "Language LAYOUT"); } } else { lName = getKeyDescription(ref lKey, ref lShift); modRecordSet.cnnDB.Execute("UPDATE LanguageLayoutLnk SET LanguageLayoutLnk.LanguageLayoutLnk_Shift = " + lShift + ", LanguageLayoutLnk.LanguageLayoutLnk_Key = " + lKey + ", LanguageLayoutLnk.LanguageLayoutLnk_Description = '" + lName + "' WHERE (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID)=" + gParentID + ") AND ((LanguageLayoutLnk.LanguageLayoutLnk_LanguageID)=" + gridEdit.get_RowData(ref gridEdit.row) + "));"); gridEdit.set_TextMatrix(ref gridEdit.row, ref 3, ref lKey); gridEdit.set_TextMatrix(ref gridEdit.row, ref 2, ref lShift); gridEdit.set_TextMatrix(ref gridEdit.row, ref 1, ref lName); } } } private void Option1_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs) { if (eventSender.Checked) { loadKeys(ref 0); } } private void Option2_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs) { if (eventSender.Checked) { loadKeys(ref 2); } } private void Option3_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs) { if (eventSender.Checked) { loadKeys(ref 1); } } private void Option4_Click() { int secID = 0; string sql = null; grClick = true; var _with3 = gridEdit; _with3.Col = 1; _with3.RowCount = 0; System.Windows.Forms.Application.DoEvents(); _with3.RowCount = 2; _with3.FixedRows = 1; _with3.FixedCols = 0; _with3.row = 0; _with3.Col = 0; _with3.CellFontBold = true; _with3.Text = "Translation"; _with3.set_ColWidth(0, 11200); _with3.CellAlignment = 3; ADODB.Recordset rs = default(ADODB.Recordset); int x = 0; string kS = null; gridEdit.RowCount = 1; rs = modRecordSet.getRS(ref "SELECT * FROM Menu;"); if (rs.RecordCount) { modRecordSet.cnnDB.Execute("INSERT INTO LanguageLayoutLnk ( LanguageLayoutLnk_LanguageID, LanguageLayoutLnk_LanguageLayoutID, LanguageLayoutLnk_Description, LanguageLayoutLnk_RightTL, LanguageLayoutLnk_Screen ) SELECT theJoin.LanguageID, theJoin.LanguageLayoutID, 'None' AS Expr1, 0 AS Expr2, 'None' AS Expr3 FROM (SELECT Language.LanguageID, LanguageLayout.LanguageLayoutID From Language, LanguageLayout WHERE (((LanguageLayout.LanguageLayoutID)=" + gParentID + "))) AS theJoin LEFT JOIN LanguageLayoutLnk ON (theJoin.LanguageID = LanguageLayoutLnk.LanguageLayoutLnk_LanguageID) AND (theJoin.LanguageLayoutID = LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID) WHERE (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageID) Is Null));"); sql = "UPDATE LanguageLayoutLnk AS LanguageLayoutLnk_1 INNER JOIN LanguageLayoutLnk ON LanguageLayoutLnk_1.LanguageLayoutLnk_LanguageID = LanguageLayoutLnk.LanguageLayoutLnk_LanguageID SET LanguageLayoutLnk.LanguageLayoutLnk_Description = [LanguageLayoutLnk_1]![LanguageLayoutLnk_Description], LanguageLayoutLnk.LanguageLayoutLnk_RightTL = [LanguageLayoutLnk_1]![LanguageLayoutLnk_RightTL], LanguageLayoutLnk.LanguageLayoutLnk_Section = [LanguageLayoutLnk_1]![LanguageLayoutLnk_Section], LanguageLayoutLnk.LanguageLayoutLnk_Screen = [LanguageLayoutLnk_1]![LanguageLayoutLnk_Screen] "; sql = sql + "WHERE (((LanguageLayoutLnk.LanguageLayoutLnk_Description)='None') AND ((LanguageLayoutLnk.LanguageLayoutLnk_Screen)='None') AND ((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID)=" + gParentID + ") AND ((LanguageLayoutLnk_1.LanguageLayoutLnk_LanguageLayoutID)=1));"; if (gParentID != 1) modRecordSet.cnnDB.Execute(sql); this.txtName.Text = rs.Fields("LanguageLayout_Name").Value; rs = modRecordSet.getRS(ref "SELECT Language.*, LanguageLayoutLnk.* FROM LanguageLayoutLnk INNER JOIN Language ON LanguageLayoutLnk.LanguageLayoutLnk_LanguageID = Language.LanguageID Where (((LanguageLayoutLnk.LanguageLayoutLnk_LanguageLayoutID) = " + gParentID + ") AND ((LanguageLayoutLnk.LanguageLayoutLnk_Section) = " + secID + ")) ORDER BY LanguageLayoutLnk_LanguageID;"); gridEdit.RowCount = rs.RecordCount + 1; x = 0; while (!(rs.EOF)) { x = x + 1; gridEdit.row = x; gridEdit.Col = 0; gridEdit.Text = rs.Fields("LanguageLayoutLnk_Description").Value; gridEdit.CellAlignment = 1; gridEdit.Col = 1; if (rs.Fields("LanguageLayoutLnk_RightTL").Value == true) { kS = "Yes"; } else { kS = "No"; } gridEdit.Text = Strings.UCase(kS); //gridEdit.Text = getKeyDescription(rs("LanguageLayoutLnk_Key"), rs("LanguageLayoutLnk_Shift")) gridEdit.Col = 2; gridEdit.Text = (Information.IsDBNull(rs.Fields("LanguageLayoutLnk_Screen").Value) ? "NOT ASSIGNED" : rs.Fields("LanguageLayoutLnk_Screen").Value); //rs("LanguageLayoutLnk_Screen") //gridEdit.Col = 3 //gridEdit.Text = rs("LanguageLayoutLnk_Key") gridEdit.set_RowData(ref gridEdit.row, ref rs.Fields("LanguageLayoutLnk_LanguageID").Value); //gridEdit.Col = 4 //gridEdit.Text = rs("Language_Order") //gridEdit.RowData(gridEdit.row) = rs("LanguageLayoutLnk_LanguageID") //gridEdit.Col = 5 //If rs("Language_Show") = True Then // kS = "Yes" //Else // kS = "No" //End If //gridEdit.Text = UCase(kS) //gridEdit.Col = 6 //gridEdit.Text = rs("LanguageID") //gridEdit.RowData(gridEdit.row) = rs("LanguageLayoutLnk_LanguageID") rs.moveNext(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using FileHelpers.Events; using FileHelpers.Helpers; using FileHelpers.Options; namespace FileHelpers.MasterDetail { /// <summary> /// Read a master detail file, eg Orders followed by detail records /// </summary> public sealed class MasterDetailEngine : MasterDetailEngine<object, object> { #region " Constructor " /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr/*'/> public MasterDetailEngine(Type masterType, Type detailType) : this(masterType, detailType, null) {} /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr/*'/> /// <param name="masterType">The master record class.</param> /// <param name="detailType">The detail record class.</param> /// <param name="recordSelector">The <see cref="MasterDetailSelector" /> to get the <see cref="RecordAction" /> (only for read operations)</param> public MasterDetailEngine(Type masterType, Type detailType, MasterDetailSelector recordSelector) : base(masterType, detailType, recordSelector) {} /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr/*'/> /// <param name="masterType">The master record class.</param> /// <param name="detailType">The detail record class.</param> /// <param name="action">The <see cref="CommonSelector" /> used by the engine (only for read operations)</param> /// <param name="selector">The string passed as the selector.</param> public MasterDetailEngine(Type masterType, Type detailType, CommonSelector action, string selector) : base(masterType, detailType, action, selector) {} #endregion } /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngine/*'/> /// <include file='Examples.xml' path='doc/examples/MasterDetailEngine/*'/> /// <typeparam name="TMaster">The Master Record Type</typeparam> /// <typeparam name="TDetail">The Detail Record Type</typeparam> public class MasterDetailEngine<TMaster, TDetail> : EngineBase where TMaster : class where TDetail : class { #region " Constructor " /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr1/*'/> public MasterDetailEngine() : this(null) {} /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr1/*'/> public MasterDetailEngine(MasterDetailSelector recordSelector) : this(typeof (TMaster), typeof (TDetail), recordSelector) {} /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr1/*'/> internal MasterDetailEngine(Type masterType, Type detailType, MasterDetailSelector recordSelector) : base(detailType) { mMasterType = masterType; mMasterInfo = FileHelpers.RecordInfo.Resolve(mMasterType); MasterOptions = CreateRecordOptionsCore(mMasterInfo); mRecordSelector = recordSelector; } /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr2/*'/> public MasterDetailEngine(CommonSelector action, string selector) : this(typeof (TMaster), typeof (TDetail), action, selector) {} /// <include file='MasterDetailEngine.docs.xml' path='doc/MasterDetailEngineCtr2/*'/> internal MasterDetailEngine(Type masterType, Type detailType, CommonSelector action, string selector) : base(detailType) { mMasterType = masterType; mMasterInfo = FileHelpers.RecordInfo.Resolve(mMasterType); MasterOptions = CreateRecordOptionsCore(mMasterInfo); var sel = new MasterDetailEngine<object, object>.CommonSelectorInternal(action, selector, mMasterInfo.IgnoreEmptyLines || RecordInfo.IgnoreEmptyLines); mRecordSelector = new MasterDetailSelector(sel.CommonSelectorMethod); } #endregion /// <summary> /// Allows you to change some record layout options at runtime /// </summary> public RecordOptions MasterOptions { get; private set; } #region CommonSelectorInternal internal class CommonSelectorInternal { private readonly CommonSelector mAction; private readonly string mSelector; private readonly bool mIgnoreEmpty = false; internal CommonSelectorInternal(CommonSelector action, string selector, bool ignoreEmpty) { mAction = action; mSelector = selector; mIgnoreEmpty = ignoreEmpty; } internal RecordAction CommonSelectorMethod(string recordString) { if (mIgnoreEmpty && recordString == string.Empty) return RecordAction.Skip; switch (mAction) { case CommonSelector.DetailIfContains: if (recordString.IndexOf(mSelector) >= 0) return RecordAction.Detail; else return RecordAction.Master; case CommonSelector.MasterIfContains: if (recordString.IndexOf(mSelector) >= 0) return RecordAction.Master; else return RecordAction.Detail; case CommonSelector.DetailIfBegins: if (recordString.StartsWith(mSelector)) return RecordAction.Detail; else return RecordAction.Master; case CommonSelector.MasterIfBegins: if (recordString.StartsWith(mSelector)) return RecordAction.Master; else return RecordAction.Detail; case CommonSelector.DetailIfEnds: if (recordString.EndsWith(mSelector)) return RecordAction.Detail; else return RecordAction.Master; case CommonSelector.MasterIfEnds: if (recordString.EndsWith(mSelector)) return RecordAction.Master; else return RecordAction.Detail; case CommonSelector.DetailIfEnclosed: if (recordString.StartsWith(mSelector) && recordString.EndsWith(mSelector)) return RecordAction.Detail; else return RecordAction.Master; case CommonSelector.MasterIfEnclosed: if (recordString.StartsWith(mSelector) && recordString.EndsWith(mSelector)) return RecordAction.Master; else return RecordAction.Detail; } return RecordAction.Skip; } } #endregion [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly IRecordInfo mMasterInfo; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private MasterDetailSelector mRecordSelector; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Type mMasterType; /// <summary> /// the type of the master records handled by this engine. /// </summary> public Type MasterType { get { return mMasterType; } } /// <summary> /// The <see cref="MasterDetailSelector" /> to get the <see cref="RecordAction" /> (only for read operations) /// </summary> public MasterDetailSelector RecordSelector { get { return mRecordSelector; } set { mRecordSelector = value; } } #region " ReadFile " /// <include file='MasterDetailEngine.docs.xml' path='doc/ReadFile/*'/> public MasterDetails<TMaster, TDetail>[] ReadFile(string fileName) { using (var fs = new StreamReader(fileName, mEncoding, true, DefaultReadBufferSize)) { MasterDetails<TMaster, TDetail>[] tempRes; tempRes = ReadStream(fs); fs.Close(); return tempRes; } } #endregion #region " ReadStream " /// <include file='MasterDetailEngine.docs.xml' path='doc/ReadStream/*'/> public MasterDetails<TMaster, TDetail>[] ReadStream(TextReader reader) { if (reader == null) //?StreamReaderIsNull"The reader of the Stream can't be null" throw new FileHelpersException("FileHelperMsg_StreamReaderIsNull", null); if (RecordSelector == null) //?RecordSelectorIsNullOnRead"The RecordSelector can't be null on read operations." throw new BadUsageException("FileHelperMsg_RecordSelectorIsNullOnRead", null); var recordReader = new NewLineDelimitedRecordReader(reader); ResetFields(); HeaderText = String.Empty; mFooterText = String.Empty; var resArray = new ArrayList(); using (var freader = new ForwardReader(recordReader, mMasterInfo.IgnoreLast)) { freader.DiscardForward = true; mLineNumber = 1; var completeLine = freader.ReadNextLine(); var currentLine = completeLine; if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(0, -1)); int currentRecord = 0; if (mMasterInfo.IgnoreFirst > 0) { for (int i = 0; i < mMasterInfo.IgnoreFirst && currentLine != null; i++) { HeaderText += currentLine + StringHelper.NewLine; currentLine = freader.ReadNextLine(); mLineNumber++; } } bool byPass = false; MasterDetails<TMaster, TDetail> record = null; var tmpDetails = new ArrayList(); var line = new LineInfo(currentLine) { mReader = freader }; var valuesMaster = new object[mMasterInfo.FieldCount]; var valuesDetail = new object[RecordInfo.FieldCount]; while (currentLine != null) { try { currentRecord++; line.ReLoad(currentLine); if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(currentRecord, -1)); var action = RecordAction.Skip; try { action = RecordSelector(currentLine); } catch (Exception ex) { //?SuppliedRecordSelectorFailed"Supplied Record selector failed to process record" throw new FileHelpersException("FileHelperMsg_SuppliedRecordSelectorFailed", null, ex); } Tuple<int, int>[] valuesPosition; switch (action) { case RecordAction.Master: if (record != null) { record.Details = (TDetail[]) tmpDetails.ToArray(typeof (TDetail)); resArray.Add(record); } mTotalRecords++; record = new MasterDetails<TMaster, TDetail>(); tmpDetails.Clear(); var lastMaster = (TMaster) mMasterInfo.Operations.StringToRecord(line, valuesMaster, ErrorManager, -1, out valuesPosition); if (lastMaster != null) record.Master = lastMaster; break; case RecordAction.Detail: var lastChild = (TDetail) RecordInfo.Operations.StringToRecord(line, valuesDetail, ErrorManager, -1, out valuesPosition); if (lastChild != null) tmpDetails.Add(lastChild); break; default: break; } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: byPass = true; throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo { mLineNumber = mLineNumber, mExceptionInfo = ex, mRecordString = completeLine, mRecordTypeName = RecordInfo.RecordType.Name }; mErrorManager.AddError(err); break; } } finally { if (byPass == false) { currentLine = freader.ReadNextLine(); completeLine = currentLine; mLineNumber = freader.LineNumber; } } } if (record != null) { record.Details = (TDetail[]) tmpDetails.ToArray(typeof (TDetail)); resArray.Add(record); } if (mMasterInfo.IgnoreLast > 0) mFooterText = freader.RemainingText; } return (MasterDetails<TMaster, TDetail>[]) resArray.ToArray(typeof (MasterDetails<TMaster, TDetail>)); } #endregion #region " ReadString " /// <include file='MasterDetailEngine.docs.xml' path='doc/ReadString/*'/> public MasterDetails<TMaster, TDetail>[] ReadString(string source) { var reader = new StringReader(source); MasterDetails<TMaster, TDetail>[] res = ReadStream(reader); reader.Close(); return res; } #endregion #region " WriteFile " /// <include file='MasterDetailEngine.docs.xml' path='doc/WriteFile/*'/> public void WriteFile(string fileName, IEnumerable<MasterDetails<TMaster, TDetail>> records) { WriteFile(fileName, records, -1); } /// <include file='MasterDetailEngine.docs.xml' path='doc/WriteFile2/*'/> public void WriteFile(string fileName, IEnumerable<MasterDetails<TMaster, TDetail>> records, int maxRecords) { using (var fs = new StreamWriter(fileName, false, mEncoding, DefaultWriteBufferSize)) { WriteStream(fs, records, maxRecords); fs.Close(); } } #endregion #region " WriteStream " /// <include file='MasterDetailEngine.docs.xml' path='doc/WriteStream/*'/> public void WriteStream(TextWriter writer, IEnumerable<MasterDetails<TMaster, TDetail>> records) { WriteStream(writer, records, -1); } /// <include file='MasterDetailEngine.docs.xml' path='doc/WriteStream2/*'/> public void WriteStream(TextWriter writer, IEnumerable<MasterDetails<TMaster, TDetail>> records, int maxRecords) { if (writer == null) //?StreamWriterIsNull"The writer of the Stream can be null" throw new FileHelpersException("FileHelperMsg_StreamWriterIsNull", null); if (records == null) //?RecordsCannotBeNull"The records cannot be null. Try with an empty array." throw new FileHelpersException("FileHelperMsg_RecordsCannotBeNull", null); ResetFields(); writer.NewLine = NewLineForWrite; WriteHeader(writer); string currentLine = null; int max = maxRecords; if (records is IList) { max = Math.Min(max < 0 ? int.MaxValue : max, ((IList) records).Count); } if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(0, max)); int recIndex = 0; foreach (var rec in records) { if (recIndex == maxRecords) break; try { if (rec == null) //?RecordIsNullAtIndex"The record at index {0} is null." throw new BadUsageException("FileHelperMsg_RecordIsNullAtIndex", new List<string>() { recIndex.ToString() }); if (MustNotifyProgress) // Avoid object creation OnProgress(new ProgressEventArgs(recIndex + 1, max)); currentLine = mMasterInfo.Operations.RecordToString(rec.Master); writer.WriteLine(currentLine); if (rec.Details != null) { for (int d = 0; d < rec.Details.Length; d++) { currentLine = RecordInfo.Operations.RecordToString(rec.Details[d]); writer.WriteLine(currentLine); } } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo { mLineNumber = mLineNumber, mExceptionInfo = ex, mRecordString = currentLine, mRecordTypeName = RecordInfo.RecordType.Name }; mErrorManager.AddError(err); break; } } } mTotalRecords = recIndex; WriteFooter(writer); } #endregion #region " WriteString " /// <include file='MasterDetailEngine.docs.xml' path='doc/WriteString/*'/> public string WriteString(IEnumerable<MasterDetails<TMaster, TDetail>> records) { return WriteString(records, -1); } /// <include file='MasterDetailEngine.docs.xml' path='doc/WriteString2/*'/> public string WriteString(IEnumerable<MasterDetails<TMaster, TDetail>> records, int maxRecords) { var sb = new StringBuilder(); var writer = new StringWriter(sb); WriteStream(writer, records, maxRecords); string res = writer.ToString(); writer.Close(); return res; } #endregion #region " AppendToFile " /// <include file='MasterDetailEngine.docs.xml' path='doc/AppendToFile1/*'/> public void AppendToFile(string fileName, MasterDetails<TMaster, TDetail> record) { AppendToFile(fileName, new MasterDetails<TMaster, TDetail>[] {record}); } /// <include file='MasterDetailEngine.docs.xml' path='doc/AppendToFile2/*'/> public void AppendToFile(string fileName, IEnumerable<MasterDetails<TMaster, TDetail>> records) { using ( TextWriter writer = StreamHelper.CreateFileAppender(fileName, mEncoding, true, false, DefaultWriteBufferSize)) { HeaderText = String.Empty; mFooterText = String.Empty; WriteStream(writer, records); writer.Close(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.Reflection; using Microsoft.Win32; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { public partial class EventSource { #if FEATURE_MANAGED_ETW && FEATURE_PERFTRACING // For non-Windows, we use a thread-local variable to hold the activity ID. // On Windows, ETW has it's own thread-local variable and we participate in its use. [ThreadStatic] private static Guid s_currentThreadActivityId; #endif // FEATURE_MANAGED_ETW && FEATURE_PERFTRACING // ActivityID support (see also WriteEventWithRelatedActivityIdCore) /// <summary> /// When a thread starts work that is on behalf of 'something else' (typically another /// thread or network request) it should mark the thread as working on that other work. /// This API marks the current thread as working on activity 'activityID'. This API /// should be used when the caller knows the thread's current activity (the one being /// overwritten) has completed. Otherwise, callers should prefer the overload that /// return the oldActivityThatWillContinue (below). /// /// All events created with the EventSource on this thread are also tagged with the /// activity ID of the thread. /// /// It is common, and good practice after setting the thread to an activity to log an event /// with a 'start' opcode to indicate that precise time/thread where the new activity /// started. /// </summary> /// <param name="activityId">A Guid that represents the new activity with which to mark /// the current thread</param> public static void SetCurrentThreadActivityId(Guid activityId) { if (TplEtwProvider.Log != null) TplEtwProvider.Log.SetActivityId(activityId); #if FEATURE_MANAGED_ETW #if FEATURE_ACTIVITYSAMPLING Guid newId = activityId; #endif // FEATURE_ACTIVITYSAMPLING // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. #if FEATURE_PERFTRACING s_currentThreadActivityId = activityId; #elif PLATFORM_WINDOWS if (UnsafeNativeMethods.ManifestEtw.EventActivityIdControl( UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref activityId) == 0) #endif // FEATURE_PERFTRACING { #if FEATURE_ACTIVITYSAMPLING var activityDying = s_activityDying; if (activityDying != null && newId != activityId) { if (activityId == Guid.Empty) { activityId = FallbackActivityId; } // OutputDebugString(string.Format("Activity dying: {0} -> {1}", activityId, newId)); activityDying(activityId); // This is actually the OLD activity ID. } #endif // FEATURE_ACTIVITYSAMPLING } #endif // FEATURE_MANAGED_ETW } /// <summary> /// When a thread starts work that is on behalf of 'something else' (typically another /// thread or network request) it should mark the thread as working on that other work. /// This API marks the current thread as working on activity 'activityID'. It returns /// whatever activity the thread was previously marked with. There is a convention that /// callers can assume that callees restore this activity mark before the callee returns. /// To encourage this, this API returns the old activity, so that it can be restored later. /// /// All events created with the EventSource on this thread are also tagged with the /// activity ID of the thread. /// /// It is common, and good practice after setting the thread to an activity to log an event /// with a 'start' opcode to indicate that precise time/thread where the new activity /// started. /// </summary> /// <param name="activityId">A Guid that represents the new activity with which to mark /// the current thread</param> /// <param name="oldActivityThatWillContinue">The Guid that represents the current activity /// which will continue at some point in the future, on the current thread</param> public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue) { oldActivityThatWillContinue = activityId; #if FEATURE_MANAGED_ETW // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. #if FEATURE_PERFTRACING oldActivityThatWillContinue = s_currentThreadActivityId; s_currentThreadActivityId = activityId; #elif PLATFORM_WINDOWS UnsafeNativeMethods.ManifestEtw.EventActivityIdControl( UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref oldActivityThatWillContinue); #endif // FEATURE_PERFTRACING #endif // FEATURE_MANAGED_ETW // We don't call the activityDying callback here because the caller has declared that // it is not dying. if (TplEtwProvider.Log != null) TplEtwProvider.Log.SetActivityId(activityId); } /// <summary> /// Retrieves the ETW activity ID associated with the current thread. /// </summary> public static Guid CurrentThreadActivityId { get { // We ignore errors to keep with the convention that EventSources do not throw // errors. Note we can't access m_throwOnWrites because this is a static method. Guid retVal = new Guid(); #if FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING retVal = s_currentThreadActivityId; #elif PLATFORM_WINDOWS UnsafeNativeMethods.ManifestEtw.EventActivityIdControl( UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID, ref retVal); #endif // FEATURE_PERFTRACING #endif // FEATURE_MANAGED_ETW return retVal; } } private int GetParameterCount(EventMetadata eventData) { return eventData.Parameters.Length; } private Type GetDataType(EventMetadata eventData, int parameterId) { return eventData.Parameters[parameterId].ParameterType; } private static string GetResourceString(string key, params object[] args) { return string.Format(Resources.GetResourceString(key), args); } private static readonly bool m_EventSourcePreventRecursion = false; } internal partial class ManifestBuilder { private string GetTypeNameHelper(Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: return "win:Boolean"; case TypeCode.Byte: return "win:UInt8"; case TypeCode.Char: case TypeCode.UInt16: return "win:UInt16"; case TypeCode.UInt32: return "win:UInt32"; case TypeCode.UInt64: return "win:UInt64"; case TypeCode.SByte: return "win:Int8"; case TypeCode.Int16: return "win:Int16"; case TypeCode.Int32: return "win:Int32"; case TypeCode.Int64: return "win:Int64"; case TypeCode.String: return "win:UnicodeString"; case TypeCode.Single: return "win:Float"; case TypeCode.Double: return "win:Double"; case TypeCode.DateTime: return "win:FILETIME"; default: if (type == typeof(Guid)) return "win:GUID"; else if (type == typeof(IntPtr)) return "win:Pointer"; else if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte)) return "win:Binary"; ManifestError(SR.Format(SR.EventSource_UnsupportedEventTypeInManifest, type.Name), true); return string.Empty; } } } internal partial class EventProvider { internal unsafe int SetInformation( UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass, IntPtr data, uint dataSize) { int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED; if (!m_setInformationMissing) { try { status = UnsafeNativeMethods.ManifestEtw.EventSetInformation( m_regHandle, eventInfoClass, (void*)data, (int)dataSize); } catch (TypeLoadException) { m_setInformationMissing = true; } } return status; } } internal static class Resources { internal static string GetResourceString(string key, params object[] args) { return string.Format(Resources.GetResourceString(key), args); } } } #if ES_BUILD_STANDALONE namespace Internal.Runtime.Augments { internal static class RuntimeThread { internal static ulong CurrentOSThreadId { get { return GetCurrentThreadId(); } } [DllImport("kernel32.dll")] private static extern uint GetCurrentThreadId(); } } #endif
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Achartengine.Chart { // Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']" [global::Android.Runtime.Register ("org/achartengine/chart/PieMapper", DoNotGenerateAcw=true)] public partial class PieMapper : global::Java.Lang.Object, global::Java.IO.ISerializable { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/achartengine/chart/PieMapper", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (PieMapper); } } protected PieMapper (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']/constructor[@name='PieMapper' and count(parameter)=0]" [Register (".ctor", "()V", "")] public PieMapper () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (PieMapper)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } static Delegate cb_addPieSegment_IFFF; #pragma warning disable 0169 static Delegate GetAddPieSegment_IFFFHandler () { if (cb_addPieSegment_IFFF == null) cb_addPieSegment_IFFF = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, float, float, float>) n_AddPieSegment_IFFF); return cb_addPieSegment_IFFF; } static void n_AddPieSegment_IFFF (IntPtr jnienv, IntPtr native__this, int p0, float p1, float p2, float p3) { global::Org.Achartengine.Chart.PieMapper __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PieMapper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.AddPieSegment (p0, p1, p2, p3); } #pragma warning restore 0169 static IntPtr id_addPieSegment_IFFF; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']/method[@name='addPieSegment' and count(parameter)=4 and parameter[1][@type='int'] and parameter[2][@type='float'] and parameter[3][@type='float'] and parameter[4][@type='float']]" [Register ("addPieSegment", "(IFFF)V", "GetAddPieSegment_IFFFHandler")] public virtual void AddPieSegment (int p0, float p1, float p2, float p3) { if (id_addPieSegment_IFFF == IntPtr.Zero) id_addPieSegment_IFFF = JNIEnv.GetMethodID (class_ref, "addPieSegment", "(IFFF)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_addPieSegment_IFFF, new JValue (p0), new JValue (p1), new JValue (p2), new JValue (p3)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_addPieSegment_IFFF, new JValue (p0), new JValue (p1), new JValue (p2), new JValue (p3)); } static Delegate cb_areAllSegmentPresent_I; #pragma warning disable 0169 static Delegate GetAreAllSegmentPresent_IHandler () { if (cb_areAllSegmentPresent_I == null) cb_areAllSegmentPresent_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, bool>) n_AreAllSegmentPresent_I); return cb_areAllSegmentPresent_I; } static bool n_AreAllSegmentPresent_I (IntPtr jnienv, IntPtr native__this, int p0) { global::Org.Achartengine.Chart.PieMapper __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PieMapper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.AreAllSegmentPresent (p0); } #pragma warning restore 0169 static IntPtr id_areAllSegmentPresent_I; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']/method[@name='areAllSegmentPresent' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("areAllSegmentPresent", "(I)Z", "GetAreAllSegmentPresent_IHandler")] public virtual bool AreAllSegmentPresent (int p0) { if (id_areAllSegmentPresent_I == IntPtr.Zero) id_areAllSegmentPresent_I = JNIEnv.GetMethodID (class_ref, "areAllSegmentPresent", "(I)Z"); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_areAllSegmentPresent_I, new JValue (p0)); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, id_areAllSegmentPresent_I, new JValue (p0)); } static Delegate cb_clearPieSegments; #pragma warning disable 0169 static Delegate GetClearPieSegmentsHandler () { if (cb_clearPieSegments == null) cb_clearPieSegments = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_ClearPieSegments); return cb_clearPieSegments; } static void n_ClearPieSegments (IntPtr jnienv, IntPtr native__this) { global::Org.Achartengine.Chart.PieMapper __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PieMapper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.ClearPieSegments (); } #pragma warning restore 0169 static IntPtr id_clearPieSegments; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']/method[@name='clearPieSegments' and count(parameter)=0]" [Register ("clearPieSegments", "()V", "GetClearPieSegmentsHandler")] public virtual void ClearPieSegments () { if (id_clearPieSegments == IntPtr.Zero) id_clearPieSegments = JNIEnv.GetMethodID (class_ref, "clearPieSegments", "()V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_clearPieSegments); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_clearPieSegments); } static Delegate cb_getAngle_Lorg_achartengine_model_Point_; #pragma warning disable 0169 static Delegate GetGetAngle_Lorg_achartengine_model_Point_Handler () { if (cb_getAngle_Lorg_achartengine_model_Point_ == null) cb_getAngle_Lorg_achartengine_model_Point_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, double>) n_GetAngle_Lorg_achartengine_model_Point_); return cb_getAngle_Lorg_achartengine_model_Point_; } static double n_GetAngle_Lorg_achartengine_model_Point_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Achartengine.Chart.PieMapper __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PieMapper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Achartengine.Model.Point p0 = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.Point> (native_p0, JniHandleOwnership.DoNotTransfer); double __ret = __this.GetAngle (p0); return __ret; } #pragma warning restore 0169 static IntPtr id_getAngle_Lorg_achartengine_model_Point_; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']/method[@name='getAngle' and count(parameter)=1 and parameter[1][@type='org.achartengine.model.Point']]" [Register ("getAngle", "(Lorg/achartengine/model/Point;)D", "GetGetAngle_Lorg_achartengine_model_Point_Handler")] public virtual double GetAngle (global::Org.Achartengine.Model.Point p0) { if (id_getAngle_Lorg_achartengine_model_Point_ == IntPtr.Zero) id_getAngle_Lorg_achartengine_model_Point_ = JNIEnv.GetMethodID (class_ref, "getAngle", "(Lorg/achartengine/model/Point;)D"); double __ret; if (GetType () == ThresholdType) __ret = JNIEnv.CallDoubleMethod (Handle, id_getAngle_Lorg_achartengine_model_Point_, new JValue (p0)); else __ret = JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getAngle_Lorg_achartengine_model_Point_, new JValue (p0)); return __ret; } static Delegate cb_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_; #pragma warning disable 0169 static Delegate GetGetSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_Handler () { if (cb_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_ == null) cb_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_GetSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_); return cb_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_; } static IntPtr n_GetSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Achartengine.Chart.PieMapper __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PieMapper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Achartengine.Model.Point p0 = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.Point> (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.GetSeriesAndPointForScreenCoordinate (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']/method[@name='getSeriesAndPointForScreenCoordinate' and count(parameter)=1 and parameter[1][@type='org.achartengine.model.Point']]" [Register ("getSeriesAndPointForScreenCoordinate", "(Lorg/achartengine/model/Point;)Lorg/achartengine/model/SeriesSelection;", "GetGetSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_Handler")] public virtual global::Org.Achartengine.Model.SeriesSelection GetSeriesAndPointForScreenCoordinate (global::Org.Achartengine.Model.Point p0) { if (id_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_ == IntPtr.Zero) id_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_ = JNIEnv.GetMethodID (class_ref, "getSeriesAndPointForScreenCoordinate", "(Lorg/achartengine/model/Point;)Lorg/achartengine/model/SeriesSelection;"); global::Org.Achartengine.Model.SeriesSelection __ret; if (GetType () == ThresholdType) __ret = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.SeriesSelection> (JNIEnv.CallObjectMethod (Handle, id_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_, new JValue (p0)), JniHandleOwnership.TransferLocalRef); else __ret = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.SeriesSelection> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getSeriesAndPointForScreenCoordinate_Lorg_achartengine_model_Point_, new JValue (p0)), JniHandleOwnership.TransferLocalRef); return __ret; } static Delegate cb_isOnPieChart_Lorg_achartengine_model_Point_; #pragma warning disable 0169 static Delegate GetIsOnPieChart_Lorg_achartengine_model_Point_Handler () { if (cb_isOnPieChart_Lorg_achartengine_model_Point_ == null) cb_isOnPieChart_Lorg_achartengine_model_Point_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_IsOnPieChart_Lorg_achartengine_model_Point_); return cb_isOnPieChart_Lorg_achartengine_model_Point_; } static bool n_IsOnPieChart_Lorg_achartengine_model_Point_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Achartengine.Chart.PieMapper __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PieMapper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Achartengine.Model.Point p0 = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.Point> (native_p0, JniHandleOwnership.DoNotTransfer); bool __ret = __this.IsOnPieChart (p0); return __ret; } #pragma warning restore 0169 static IntPtr id_isOnPieChart_Lorg_achartengine_model_Point_; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']/method[@name='isOnPieChart' and count(parameter)=1 and parameter[1][@type='org.achartengine.model.Point']]" [Register ("isOnPieChart", "(Lorg/achartengine/model/Point;)Z", "GetIsOnPieChart_Lorg_achartengine_model_Point_Handler")] public virtual bool IsOnPieChart (global::Org.Achartengine.Model.Point p0) { if (id_isOnPieChart_Lorg_achartengine_model_Point_ == IntPtr.Zero) id_isOnPieChart_Lorg_achartengine_model_Point_ = JNIEnv.GetMethodID (class_ref, "isOnPieChart", "(Lorg/achartengine/model/Point;)Z"); bool __ret; if (GetType () == ThresholdType) __ret = JNIEnv.CallBooleanMethod (Handle, id_isOnPieChart_Lorg_achartengine_model_Point_, new JValue (p0)); else __ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, id_isOnPieChart_Lorg_achartengine_model_Point_, new JValue (p0)); return __ret; } static Delegate cb_setDimensions_III; #pragma warning disable 0169 static Delegate GetSetDimensions_IIIHandler () { if (cb_setDimensions_III == null) cb_setDimensions_III = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int, int>) n_SetDimensions_III); return cb_setDimensions_III; } static void n_SetDimensions_III (IntPtr jnienv, IntPtr native__this, int p0, int p1, int p2) { global::Org.Achartengine.Chart.PieMapper __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PieMapper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.SetDimensions (p0, p1, p2); } #pragma warning restore 0169 static IntPtr id_setDimensions_III; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='PieMapper']/method[@name='setDimensions' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int']]" [Register ("setDimensions", "(III)V", "GetSetDimensions_IIIHandler")] public virtual void SetDimensions (int p0, int p1, int p2) { if (id_setDimensions_III == IntPtr.Zero) id_setDimensions_III = JNIEnv.GetMethodID (class_ref, "setDimensions", "(III)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setDimensions_III, new JValue (p0), new JValue (p1), new JValue (p2)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setDimensions_III, new JValue (p0), new JValue (p1), new JValue (p2)); } } }
using System; using System.Runtime.InteropServices; using Avalonia.Controls.Platform; using Avalonia.Platform; using Avalonia.VisualTree; using Avalonia.Win32.Interop; namespace Avalonia.Win32 { class Win32NativeControlHost : INativeControlHostImpl { public WindowImpl Window { get; } public Win32NativeControlHost(WindowImpl window) { Window = window; } void AssertCompatible(IPlatformHandle handle) { if (!IsCompatibleWith(handle)) throw new ArgumentException($"Don't know what to do with {handle.HandleDescriptor}"); } public INativeControlHostDestroyableControlHandle CreateDefaultChild(IPlatformHandle parent) { AssertCompatible(parent); return new DumbWindow(parent.Handle); } public INativeControlHostControlTopLevelAttachment CreateNewAttachment(Func<IPlatformHandle, IPlatformHandle> create) { var holder = new DumbWindow(Window.Handle.Handle); Win32NativeControlAttachment attachment = null; try { var child = create(holder); // ReSharper disable once UseObjectOrCollectionInitializer // It has to be assigned to the variable before property setter is called so we dispose it on exception attachment = new Win32NativeControlAttachment(holder, child); attachment.AttachedTo = this; return attachment; } catch { attachment?.Dispose(); holder?.Destroy(); throw; } } public INativeControlHostControlTopLevelAttachment CreateNewAttachment(IPlatformHandle handle) { AssertCompatible(handle); return new Win32NativeControlAttachment(new DumbWindow(Window.Handle.Handle), handle) { AttachedTo = this }; } public bool IsCompatibleWith(IPlatformHandle handle) => handle.HandleDescriptor == "HWND"; class DumbWindow : IDisposable, INativeControlHostDestroyableControlHandle { public IntPtr Handle { get;} public string HandleDescriptor => "HWND"; public void Destroy() => Dispose(); UnmanagedMethods.WndProc _wndProcDelegate; private readonly string _className; public DumbWindow(IntPtr? parent = null) { _wndProcDelegate = WndProc; var wndClassEx = new UnmanagedMethods.WNDCLASSEX { cbSize = Marshal.SizeOf<UnmanagedMethods.WNDCLASSEX>(), hInstance = UnmanagedMethods.GetModuleHandle(null), lpfnWndProc = _wndProcDelegate, lpszClassName = _className = "AvaloniaDumbWindow-" + Guid.NewGuid(), }; var atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx); Handle = UnmanagedMethods.CreateWindowEx( 0, atom, null, (int)UnmanagedMethods.WindowStyles.WS_CHILD, 0, 0, 640, 480, parent ?? OffscreenParentWindow.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } protected virtual unsafe IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam); } private void ReleaseUnmanagedResources() { UnmanagedMethods.DestroyWindow(Handle); UnmanagedMethods.UnregisterClass(_className, UnmanagedMethods.GetModuleHandle(null)); } public void Dispose() { ReleaseUnmanagedResources(); GC.SuppressFinalize(this); } ~DumbWindow() { ReleaseUnmanagedResources(); } } class Win32NativeControlAttachment : INativeControlHostControlTopLevelAttachment { private DumbWindow _holder; private IPlatformHandle _child; private Win32NativeControlHost _attachedTo; public Win32NativeControlAttachment(DumbWindow holder, IPlatformHandle child) { _holder = holder; _child = child; UnmanagedMethods.SetParent(child.Handle, _holder.Handle); UnmanagedMethods.ShowWindow(child.Handle, UnmanagedMethods.ShowWindowCommand.Show); } void CheckDisposed() { if (_holder == null) throw new ObjectDisposedException(nameof(Win32NativeControlAttachment)); } public void Dispose() { if (_child != null) UnmanagedMethods.SetParent(_child.Handle, OffscreenParentWindow.Handle); _holder?.Dispose(); _holder = null; _child = null; _attachedTo = null; } public INativeControlHostImpl AttachedTo { get => _attachedTo; set { CheckDisposed(); _attachedTo = (Win32NativeControlHost) value; if (_attachedTo == null) { UnmanagedMethods.ShowWindow(_holder.Handle, UnmanagedMethods.ShowWindowCommand.Hide); UnmanagedMethods.SetParent(_holder.Handle, OffscreenParentWindow.Handle); } else UnmanagedMethods.SetParent(_holder.Handle, _attachedTo.Window.Handle.Handle); } } public bool IsCompatibleWith(INativeControlHostImpl host) => host is Win32NativeControlHost; public void HideWithSize(Size size) { UnmanagedMethods.SetWindowPos(_holder.Handle, IntPtr.Zero, -100, -100, 1, 1, UnmanagedMethods.SetWindowPosFlags.SWP_HIDEWINDOW | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); if (_attachedTo == null || _child == null) return; size *= _attachedTo.Window.RenderScaling; UnmanagedMethods.MoveWindow(_child.Handle, 0, 0, Math.Max(1, (int)size.Width), Math.Max(1, (int)size.Height), false); } public unsafe void ShowInBounds(Rect bounds) { CheckDisposed(); if (_attachedTo == null) throw new InvalidOperationException("The control isn't currently attached to a toplevel"); bounds *= _attachedTo.Window.RenderScaling; var pixelRect = new PixelRect((int)bounds.X, (int)bounds.Y, Math.Max(1, (int)bounds.Width), Math.Max(1, (int)bounds.Height)); UnmanagedMethods.MoveWindow(_child.Handle, 0, 0, pixelRect.Width, pixelRect.Height, true); UnmanagedMethods.SetWindowPos(_holder.Handle, IntPtr.Zero, pixelRect.X, pixelRect.Y, pixelRect.Width, pixelRect.Height, UnmanagedMethods.SetWindowPosFlags.SWP_SHOWWINDOW | UnmanagedMethods.SetWindowPosFlags.SWP_NOZORDER | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); UnmanagedMethods.InvalidateRect(_attachedTo.Window.Handle.Handle, null, false); } } } }
//--------------------------------------------------------------------------- // // <copyright file="PixelShader.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.KnownBoxes; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Effects { sealed partial class PixelShader : Animatable, DUCE.IResource { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new PixelShader Clone() { return (PixelShader)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new PixelShader CloneCurrentValue() { return (PixelShader)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void UriSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { PixelShader target = ((PixelShader) d); target.UriSourcePropertyChangedHook(e); target.PropertyChanged(UriSourceProperty); } private static void ShaderRenderModePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { PixelShader target = ((PixelShader) d); target.PropertyChanged(ShaderRenderModeProperty); } #region Public Properties /// <summary> /// UriSource - Uri. Default value is null. /// </summary> public Uri UriSource { get { return (Uri) GetValue(UriSourceProperty); } set { SetValueInternal(UriSourceProperty, value); } } /// <summary> /// ShaderRenderMode - ShaderRenderMode. Default value is ShaderRenderMode.Auto. /// </summary> public ShaderRenderMode ShaderRenderMode { get { return (ShaderRenderMode) GetValue(ShaderRenderModeProperty); } set { SetValueInternal(ShaderRenderModeProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new PixelShader(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { ManualUpdateResource(channel, skipOnChannelCheck); base.UpdateResource(channel, skipOnChannelCheck); } DUCE.ResourceHandle DUCE.IResource.AddRefOnChannel(DUCE.Channel channel) { using (CompositionEngineLock.Acquire()) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_PIXELSHADER)) { AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } } void DUCE.IResource.ReleaseOnChannel(DUCE.Channel channel) { using (CompositionEngineLock.Acquire()) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { ReleaseOnChannelAnimations(channel); } } } DUCE.ResourceHandle DUCE.IResource.GetHandle(DUCE.Channel channel) { DUCE.ResourceHandle h; // Reconsider the need for this lock when removing the MultiChannelResource. using (CompositionEngineLock.Acquire()) { h = _duceResource.GetHandle(channel); } return h; } int DUCE.IResource.GetChannelCount() { // must already be in composition lock here return _duceResource.GetChannelCount(); } DUCE.Channel DUCE.IResource.GetChannel(int index) { // in a lock already return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // // This property finds the correct initial size for the _effectiveValues store on the // current DependencyObject as a performance optimization // // This includes: // UriSource // internal override int EffectiveValuesInitialSize { get { return 1; } } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the PixelShader.UriSource property. /// </summary> public static readonly DependencyProperty UriSourceProperty; /// <summary> /// The DependencyProperty for the PixelShader.ShaderRenderMode property. /// </summary> public static readonly DependencyProperty ShaderRenderModeProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal static Uri s_UriSource = null; internal const ShaderRenderMode c_ShaderRenderMode = ShaderRenderMode.Auto; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static PixelShader() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(PixelShader); UriSourceProperty = RegisterProperty("UriSource", typeof(Uri), typeofThis, null, new PropertyChangedCallback(UriSourcePropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); ShaderRenderModeProperty = RegisterProperty("ShaderRenderMode", typeof(ShaderRenderMode), typeofThis, ShaderRenderMode.Auto, new PropertyChangedCallback(ShaderRenderModePropertyChanged), new ValidateValueCallback(System.Windows.Media.Effects.ValidateEnums.IsShaderRenderModeValid), /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); } #endregion Constructors } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using AjaxPro; using ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Core; using ASC.Core.Users; using ASC.Notify.Model; using ASC.Notify.Recipients; using ASC.Web.Core; using ASC.Web.Core.Subscriptions; using ASC.Web.Studio.Core; using ASC.Web.Studio.Core.Notify; using ASC.Web.Studio.PublicResources; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.UserControls.Users { [AjaxNamespace("AjaxPro.SubscriptionManager")] public partial class UserSubscriptions : UserControl { public static string Location { get { return "~/UserControls/Users/UserSubscriptions/UserSubscriptions.ascx"; } } protected UserInfo CurrentUser; protected bool IsAdmin; protected void Page_Load(object sender, EventArgs e) { AjaxPro.Utility.RegisterTypeForAjax(GetType()); CurrentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); IsAdmin = CurrentUser.IsAdmin(); } #region Init Notify by comboboxes protected override void OnInit(EventArgs e) { base.OnInit(e); try { Page.RegisterBodyScripts("~/UserControls/Users/UserSubscriptions/js/subscription_manager.js") .RegisterInlineScript("CommonSubscriptionManager.InitNotifyByComboboxes();") .RegisterStyle("~/UserControls/Users/UserSubscriptions/css/subscriptions.less"); } catch { } } #endregion [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public object GetAllSubscriptions() { var result = new { Items = new List<object>() }; var isFirst = true; foreach (var item in WebItemManager.Instance.GetItems(Web.Core.WebZones.WebZoneType.All) .FindAll(i => i.Context != null && i.Context.SubscriptionManager is IProductSubscriptionManager)) { try { result.Items.Add(GetItemSubscriptions(item, isFirst)); isFirst = false; } catch (Exception) { } } return result; } private object GetItemSubscriptions(IWebItem webItem, bool isOpen) { var isEmpty = true; var canUnsubscribe = false; var groups = new List<object>(); var types = new List<object>(); var itemType = 1; var recipient = GetCurrentRecipient(); var productSubscriptionManager = webItem.Context.SubscriptionManager as IProductSubscriptionManager; if (productSubscriptionManager.GroupByType == GroupByType.Modules) { foreach (var subItem in WebItemManager.Instance.GetSubItems(webItem.ID)) { if (subItem.Context == null || subItem.Context.SubscriptionManager == null) continue; var subscriptionTypes = subItem.Context.SubscriptionManager.GetSubscriptionTypes(); if (subscriptionTypes == null || subscriptionTypes.Count == 0) continue; else subscriptionTypes = subscriptionTypes.FindAll(type => (type.IsEmptySubscriptionType != null && !type.IsEmptySubscriptionType(webItem.ID, subItem.ID, type.ID))); if (subscriptionTypes == null || subscriptionTypes.Count == 0) continue; var group = new { Id = subItem.ID, ImageUrl = subItem.GetIconAbsoluteURL(), Name = subItem.Name.HtmlEncode(), Types = new List<object>() }; foreach (var type in subscriptionTypes) { var t = new { Id = type.ID, Name = type.Name.HtmlEncode(), Single = type.Single, IsSubscribed = type.CanSubscribe ? subItem.Context.SubscriptionManager.SubscriptionProvider.IsSubscribed(type.NotifyAction, recipient, null) : true }; if (t.IsSubscribed) canUnsubscribe = true; group.Types.Add(t); } groups.Add(group); isEmpty = false; } } else if (productSubscriptionManager.GroupByType == GroupByType.Groups) { var subscriptionTypes = productSubscriptionManager.GetSubscriptionTypes(); var subscriptionGroups = productSubscriptionManager.GetSubscriptionGroups(); if (subscriptionTypes != null && subscriptionGroups != null) { foreach (var gr in subscriptionGroups) { var sTypes = subscriptionTypes.FindAll(type => (type.IsEmptySubscriptionType != null && !type.IsEmptySubscriptionType(webItem.ID, gr.ID, type.ID))); if (sTypes == null || sTypes.Count == 0) continue; var group = new { Id = gr.ID, ImageUrl = "", Name = gr.Name.HtmlEncode(), Types = new List<object>() }; foreach (var type in sTypes) { var t = new { Id = type.ID, Name = type.Name.HtmlEncode(), Single = type.Single, IsSubscribed = type.CanSubscribe ? productSubscriptionManager.SubscriptionProvider.IsSubscribed(type.NotifyAction, recipient, null) : true }; if (t.IsSubscribed) canUnsubscribe = true; group.Types.Add(t); } groups.Add(group); isEmpty = false; } } } else if (productSubscriptionManager.GroupByType == GroupByType.Simple) { itemType = 0; var subscriptionTypes = productSubscriptionManager.GetSubscriptionTypes(); if (subscriptionTypes != null) { foreach (var type in subscriptionTypes) { if (type.IsEmptySubscriptionType != null && type.IsEmptySubscriptionType(webItem.ID, webItem.ID, type.ID)) continue; var t = new { Id = type.ID, Name = type.Name.HtmlEncode(), Single = type.Single, IsSubscribed = !type.CanSubscribe || !productSubscriptionManager.SubscriptionProvider.IsUnsubscribe((IDirectRecipient)recipient, type.NotifyAction, null) }; if (t.IsSubscribed) canUnsubscribe = true; types.Add(t); isEmpty = false; } } } return new { Id = webItem.ID, LogoUrl = webItem.GetIconAbsoluteURL(), Name = HttpUtility.HtmlEncode(webItem.Name), IsEmpty = isEmpty, IsOpen = isOpen, CanUnSubscribe = canUnsubscribe, NotifyType = GetNotifyByMethod(webItem.ID), Groups = groups, Types = types, Type = itemType, Class = webItem.ProductClassName }; } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public object RenderGroupItemSubscriptions(Guid itemId, Guid subItemId, Guid subscriptionTypeId) { try { SubscriptionType type = null; var productSubscriptionManager = WebItemManager.Instance[itemId].Context.SubscriptionManager as IProductSubscriptionManager; ISubscriptionManager subscriptionManager = productSubscriptionManager; if (productSubscriptionManager.GroupByType == GroupByType.Modules) subscriptionManager = WebItemManager.Instance[subItemId].Context.SubscriptionManager; var subscriptionTypes = subscriptionManager.GetSubscriptionTypes(); if (subscriptionTypes != null && subscriptionTypes.Count != 0) { type = (from s in subscriptionTypes where s.ID.Equals(subscriptionTypeId) select s).Single<SubscriptionType>(); } var result = new { Status = 1, ItemId = itemId, SubItemId = subItemId, TypeId = subscriptionTypeId, Objects = new List<object>() }; if (type.Single || type.CanSubscribe) return result; if (type.IsEmptySubscriptionType != null && type.IsEmptySubscriptionType(itemId, subItemId, subscriptionTypeId)) return result; if (type.GetSubscriptionObjects == null) return result; var typeObjects = type.GetSubscriptionObjects(itemId, subItemId, subscriptionTypeId); if (typeObjects == null || typeObjects.Count == 0) return result; typeObjects.Sort((s1, s2) => String.Compare(s1.Name, s2.Name, true)); foreach (var subscription in typeObjects) { result.Objects.Add(new { Id = subscription.ID, Name = HttpUtility.HtmlEncode(subscription.Name), Url = String.IsNullOrEmpty(subscription.URL) ? "" : subscription.URL, IsSubscribed = subscriptionManager.SubscriptionProvider.IsSubscribed(type.NotifyAction, GetCurrentRecipient(), subscription.ID) }); } return result; } catch (Exception e) { return new { Status = 0, Message = e.Message.HtmlEncode() }; } } #region what's new protected string RenderWhatsNewSubscriptionState() { return RenderWhatsNewSubscriptionState(StudioNotifyHelper.IsSubscribedToNotify(CurrentUser, Actions.SendWhatsNew)); } protected string RenderWhatsNewSubscriptionState(bool isSubscribe) { if (isSubscribe) return "<a class=\"on_off_button on\" href=\"javascript:CommonSubscriptionManager.SubscribeToWhatsNew();\" title=\"" + Resource.UnsubscribeButton + "\"></a>"; else return "<a class=\"on_off_button off\" href=\"javascript:CommonSubscriptionManager.SubscribeToWhatsNew();\" title=\"" + Resource.SubscribeButton + "\"></a>"; } protected string RenderWhatsNewNotifyByCombobox() { var notifyBy = ConvertToNotifyByValue(StudioSubscriptionManager.Instance, Actions.SendWhatsNew); return string.Format("<span class=\"subsSelector subs-notice-text\" data-notify=\"{0}\" data-function=\"SetWhatsNewNotifyByMethod\"></span>", (int)notifyBy); } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SetWhatsNewNotifyByMethod(int notifyBy) { try { var resp = new AjaxResponse(); var notifyByList = ConvertToNotifyByList((NotifyBy)notifyBy); SetNotifyBySubsriptionTypes(notifyByList, StudioSubscriptionManager.Instance, Actions.SendWhatsNew); return resp; } catch { return null; } } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeToWhatsNew() { var resp = new AjaxResponse { rs1 = "0" }; try { var recipient = StudioNotifyHelper.ToRecipient(SecurityContext.CurrentAccount.ID); var isSubscribed = StudioNotifyHelper.IsSubscribedToNotify(recipient, Actions.SendWhatsNew); StudioNotifyHelper.SubscribeToNotify(recipient, Actions.SendWhatsNew, !isSubscribed); resp.rs2 = RenderWhatsNewSubscriptionState(!isSubscribed); resp.rs1 = "1"; } catch (Exception e) { resp.rs2 = e.Message.HtmlEncode(); } return resp; } #endregion #region tips&tricks protected string RenderTipsAndTricksSubscriptionState() { return RenderTipsAndTricksSubscriptionState(StudioNotifyHelper.IsSubscribedToNotify(CurrentUser, Actions.PeriodicNotify)); } protected string RenderTipsAndTricksSubscriptionState(bool isSubscribe) { if (isSubscribe) return "<a class=\"on_off_button on\" href=\"javascript:CommonSubscriptionManager.SubscribeToTipsAndTricks();\" title=\"" + Resource.UnsubscribeButton + "\"></a>"; else return "<a class=\"on_off_button off\" href=\"javascript:CommonSubscriptionManager.SubscribeToTipsAndTricks();\" title=\"" + Resource.SubscribeButton + "\"></a>"; } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeToTipsAndTricks() { var resp = new AjaxResponse { rs1 = "0" }; try { var recipient = StudioNotifyHelper.ToRecipient(SecurityContext.CurrentAccount.ID); var isSubscribe = StudioNotifyHelper.IsSubscribedToNotify(recipient, Actions.PeriodicNotify); StudioNotifyHelper.SubscribeToNotify(recipient, Actions.PeriodicNotify, !isSubscribe); resp.rs2 = RenderTipsAndTricksSubscriptionState(!isSubscribe); resp.rs1 = "1"; } catch (Exception e) { resp.rs2 = e.Message.HtmlEncode(); } return resp; } #endregion #region spam protected bool IsVisibleSpamSubscription() { return TenantExtra.Saas && SetupInfo.IsVisibleSettings("SpamSubscription"); } private const string TeamlabSiteDbId = "teamlabsite"; private const string TemplateUnsubscribeTable = "template_unsubscribe"; private static IDbManager GetDb() { return DbManager.FromHttpContext(TeamlabSiteDbId); } private static void UnsubscribeFromSpam(string email) { using (var db = GetDb()) { var query = new SqlInsert(TemplateUnsubscribeTable, true) .InColumnValue("email", email.ToLowerInvariant()); db.ExecuteScalar<int>(query); } } private static void SubscribeToSpam(string email) { using (var db = GetDb()) { db.ExecuteScalar<int>(new SqlDelete(TemplateUnsubscribeTable).Where("email", email.ToLowerInvariant())); } } private static bool IsSubscribedToSpam(string email) { using (var db = GetDb()) { var query = new SqlQuery(TemplateUnsubscribeTable) .SelectCount() .Where("email", email); return db.ExecuteScalar<int>(query) == 0; } } protected string RenderSpamSubscriptionState() { var isSubscribed = IsSubscribedToSpam(CurrentUser.Email); return RenderSpamSubscriptionState(isSubscribed); } protected string RenderSpamSubscriptionState(bool isSubscribed) { if (isSubscribed) return "<a class=\"on_off_button on\" href=\"javascript:CommonSubscriptionManager.SubscribeToSpam();\" title=\"" + Resource.UnsubscribeButton + "\"></a>"; else return "<a class=\"on_off_button off\" href=\"javascript:CommonSubscriptionManager.SubscribeToSpam();\" title=\"" + Resource.SubscribeButton + "\"></a>"; } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeToSpam() { var resp = new AjaxResponse { rs1 = "0" }; try { if (!IsVisibleSpamSubscription()) throw new MissingMethodException(); var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); var isSubscribed = IsSubscribedToSpam(user.Email); if (isSubscribed) { UnsubscribeFromSpam(user.Email); } else { SubscribeToSpam(user.Email); } resp.rs2 = RenderTipsAndTricksSubscriptionState(!isSubscribed); resp.rs1 = "1"; } catch (Exception e) { resp.rs2 = e.Message.HtmlEncode(); } return resp; } #endregion #region admin notifies protected string RenderAdminNotifySubscriptionState() { return RenderAdminNotifySubscriptionState(StudioNotifyHelper.IsSubscribedToNotify(CurrentUser, Actions.AdminNotify)); } protected string RenderAdminNotifySubscriptionState(bool isSubscribe) { if (isSubscribe) return "<a class=\"on_off_button on\" href=\"javascript:CommonSubscriptionManager.SubscribeToAdminNotify();\" title=\"" + Resource.UnsubscribeButton + "\"></a>"; else return "<a class=\"on_off_button off\" href=\"javascript:CommonSubscriptionManager.SubscribeToAdminNotify();\" title=\"" + Resource.SubscribeButton + "\"></a>"; } protected string RenderAdminNotifyNotifyByCombobox() { var notifyBy = ConvertToNotifyByValue(StudioSubscriptionManager.Instance, Actions.AdminNotify); return string.Format("<span class=\"subsSelector subs-notice-text\" data-notify=\"{0}\" data-function=\"SetAdminNotifyNotifyByMethod\"></span>", (int)notifyBy); } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SetAdminNotifyNotifyByMethod(int notifyBy) { try { var resp = new AjaxResponse(); var notifyByList = ConvertToNotifyByList((NotifyBy)notifyBy); SetNotifyBySubsriptionTypes(notifyByList, StudioSubscriptionManager.Instance, Actions.AdminNotify); return resp; } catch { return null; } } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeToAdminNotify() { var resp = new AjaxResponse { rs1 = "0" }; try { var recipient = StudioNotifyHelper.ToRecipient(SecurityContext.CurrentAccount.ID); var isSubscribe = StudioNotifyHelper.IsSubscribedToNotify(recipient, Actions.AdminNotify); StudioNotifyHelper.SubscribeToNotify(recipient, Actions.AdminNotify, !isSubscribe); resp.rs2 = RenderAdminNotifySubscriptionState(!isSubscribe); resp.rs1 = "1"; } catch (Exception e) { resp.rs2 = e.Message.HtmlEncode(); } return resp; } #endregion private IRecipient GetCurrentRecipient() { return new DirectRecipient(SecurityContext.CurrentAccount.ID.ToString(), SecurityContext.CurrentAccount.Name); } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeObject(Guid itemId, Guid subItemID, Guid subscriptionTypeID, string objID, bool subscribe) { var resp = new AjaxResponse { rs2 = itemId.ToString(), rs3 = subItemID.ToString(), rs4 = subscriptionTypeID.ToString() }; try { ISubscriptionManager subscriptionManager = null; var item = WebItemManager.Instance[itemId]; var productSubscriptionManager = item.Context.SubscriptionManager as IProductSubscriptionManager; if (productSubscriptionManager.GroupByType == GroupByType.Groups || productSubscriptionManager.GroupByType == GroupByType.Simple) subscriptionManager = productSubscriptionManager; else if (productSubscriptionManager.GroupByType == GroupByType.Modules) subscriptionManager = WebItemManager.Instance[subItemID].Context.SubscriptionManager; if (subscriptionManager != null) { var types = subscriptionManager.GetSubscriptionTypes(); var type = types.Find(t => t.ID.Equals(subscriptionTypeID)); resp.rs5 = objID; if (subscribe) subscriptionManager.SubscriptionProvider.Subscribe(type.NotifyAction, objID, GetCurrentRecipient()); else subscriptionManager.SubscriptionProvider.UnSubscribe(type.NotifyAction, objID, GetCurrentRecipient()); } resp.rs1 = "1"; } catch (Exception e) { resp.rs1 = "0"; resp.rs6 = "<div class='errorBox'>" + HttpUtility.HtmlEncode(e.Message) + "</div>"; } return resp; } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public object UnsubscribeType(Guid itemId, Guid subItemId, Guid subscriptionTypeID) { try { var item = WebItemManager.Instance[itemId]; var productSubscriptionManager = item.Context.SubscriptionManager as IProductSubscriptionManager; if (productSubscriptionManager.GroupByType == GroupByType.Groups) { var type = productSubscriptionManager.GetSubscriptionTypes().Find(t => t.ID.Equals(subscriptionTypeID)); if (type != null && type.CanSubscribe) productSubscriptionManager.SubscriptionProvider.UnSubscribe(type.NotifyAction, null, GetCurrentRecipient()); else { var objs = productSubscriptionManager.GetSubscriptionObjects(subItemId); objs.RemoveAll(o => !o.SubscriptionGroup.ID.Equals(subItemId) || !o.SubscriptionType.ID.Equals(subscriptionTypeID)); var subscriptionProvider = productSubscriptionManager.SubscriptionProvider; var currentRecipient = GetCurrentRecipient(); foreach (var o in objs) subscriptionProvider.UnSubscribe(o.SubscriptionType.NotifyAction, o.ID, currentRecipient); } } else if (productSubscriptionManager.GroupByType == GroupByType.Modules || productSubscriptionManager.GroupByType == GroupByType.Simple) { var subItem = WebItemManager.Instance[subItemId]; if (subItem != null && subItem.Context != null && subItem.Context.SubscriptionManager != null) { var subscriptionType = subItem.Context.SubscriptionManager.GetSubscriptionTypes().Find(st => st.ID.Equals(subscriptionTypeID)); if (subscriptionType.CanSubscribe) subItem.Context.SubscriptionManager.SubscriptionProvider.UnSubscribe(subscriptionType.NotifyAction, null, GetCurrentRecipient()); else subItem.Context.SubscriptionManager.SubscriptionProvider.UnSubscribe(subscriptionType.NotifyAction, GetCurrentRecipient()); } } var data = GetItemSubscriptions(item, true); return new { Status = 1, Message = "", Data = data, SubItemId = subItemId, SubscriptionTypeID = subscriptionTypeID }; } catch (Exception e) { return new { Status = 0, Message = HttpUtility.HtmlEncode(e.Message) }; } } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public object SubscribeType(Guid itemId, Guid subItemId, Guid subscriptionTypeID) { try { var item = WebItemManager.Instance[itemId]; ISubscriptionManager subscriptionManager = null; var productSubscriptionManager = item.Context.SubscriptionManager as IProductSubscriptionManager; if (productSubscriptionManager.GroupByType == GroupByType.Modules || productSubscriptionManager.GroupByType == GroupByType.Simple) { var subItem = WebItemManager.Instance[subItemId]; subscriptionManager = subItem.Context.SubscriptionManager; } else subscriptionManager = productSubscriptionManager; var types = subscriptionManager.GetSubscriptionTypes(); if (types != null) { var type = types.Find(t => t.ID.Equals(subscriptionTypeID) && t.CanSubscribe); if (type != null) subscriptionManager.SubscriptionProvider.Subscribe(type.NotifyAction, null, GetCurrentRecipient()); } var data = GetItemSubscriptions(item, true); return new { Status = 1, Message = "", Data = data, SubItemId = subItemId, SubscriptionTypeID = subscriptionTypeID }; } catch (Exception e) { return new { Status = 0, Message = HttpUtility.HtmlEncode(e.Message) }; } } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public object UnsubscribeProduct(Guid itemId) { try { var item = WebItemManager.Instance[itemId]; var productSubscriptionManager = item.Context.SubscriptionManager as IProductSubscriptionManager; if (productSubscriptionManager.GroupByType == GroupByType.Modules) { foreach (var subItem in WebItemManager.Instance.GetSubItems(item.ID)) { if (subItem.Context != null && subItem.Context.SubscriptionManager != null) { foreach (var subscriptionType in subItem.Context.SubscriptionManager.GetSubscriptionTypes()) { if (subscriptionType.CanSubscribe) subItem.Context.SubscriptionManager.SubscriptionProvider.UnSubscribe(subscriptionType.NotifyAction, null, GetCurrentRecipient()); else subItem.Context.SubscriptionManager.SubscriptionProvider.UnSubscribe(subscriptionType.NotifyAction, GetCurrentRecipient()); } } } } else if (productSubscriptionManager.GroupByType == GroupByType.Groups || productSubscriptionManager.GroupByType == GroupByType.Simple) { foreach (var subscriptionType in productSubscriptionManager.GetSubscriptionTypes()) { if (subscriptionType.CanSubscribe) productSubscriptionManager.SubscriptionProvider.UnSubscribe(subscriptionType.NotifyAction, null, GetCurrentRecipient()); else productSubscriptionManager.SubscriptionProvider.UnSubscribe(subscriptionType.NotifyAction, GetCurrentRecipient()); } } var data = GetItemSubscriptions(item, true); return new { Status = 1, Message = "", Data = data }; } catch (Exception e) { return new { Status = 0, Message = HttpUtility.HtmlEncode(e.Message) }; } } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SetNotifyByMethod(Guid productID, int notifyBy) { var resp = new AjaxResponse { rs2 = productID.ToString() }; try { var notifyByList = ConvertToNotifyByList((NotifyBy)notifyBy); var productSubscriptionManager = WebItemManager.Instance[productID].Context.SubscriptionManager as IProductSubscriptionManager; if (productSubscriptionManager.GroupByType == GroupByType.Modules) { foreach (var item in WebItemManager.Instance.GetSubItems(productID)) { if (item.Context != null && item.Context.SubscriptionManager != null) SetNotifyBySubsriptionTypes(notifyByList, item.Context.SubscriptionManager); } } else if (productSubscriptionManager.GroupByType == GroupByType.Groups || productSubscriptionManager.GroupByType == GroupByType.Simple) { SetNotifyBySubsriptionTypes(notifyByList, productSubscriptionManager); } resp.rs1 = "1"; } catch (Exception e) { resp.rs1 = "0"; resp.rs6 = "<div class='errorBox'>" + HttpUtility.HtmlEncode(e.Message) + "</div>"; } return null; } private static IList<string> ConvertToNotifyByList(NotifyBy notifyBy) { IList<string> notifyByList = new List<string>(); NotifyByBindings.Keys.Where(n => notifyBy.HasFlag(n)).ToList().ForEach(n => notifyByList.Add(NotifyByBindings[n])); return notifyByList; } [Flags] public enum NotifyBy { None = 0, Email = 1, TMTalk = 2, Push = 4, Telegram = 8, SignalR = 16 } protected static readonly Dictionary<NotifyBy, string> NotifyByBindings = new Dictionary<NotifyBy, string>() { { NotifyBy.Email, ASC.Core.Configuration.Constants.NotifyEMailSenderSysName }, { NotifyBy.TMTalk, ASC.Core.Configuration.Constants.NotifyMessengerSenderSysName }, { NotifyBy.Telegram, ASC.Core.Configuration.Constants.NotifyTelegramSenderSysName } }; protected static readonly Dictionary<string, NotifyBy> NotifyByBindingsReverse = NotifyByBindings.ToDictionary(kv => kv.Value, kv => kv.Key); protected string GetNotifyLabel(NotifyBy notify) { try { return Resource.ResourceManager.GetString("NotifyBy" + notify.ToString()); } catch { return "Unknown"; } } private void SetNotifyBySubsriptionTypes(IList<string> notifyByList, ISubscriptionManager subscriptionManager) { var subscriptionTypes = subscriptionManager.GetSubscriptionTypes(); if (subscriptionTypes != null) { foreach (var type in subscriptionTypes) SetNotifyBySubsriptionTypes(notifyByList, subscriptionManager, type.NotifyAction); } } private void SetNotifyBySubsriptionTypes(IList<string> notifyByList, ISubscriptionManager subscriptionManager, INotifyAction action) { subscriptionManager .SubscriptionProvider .UpdateSubscriptionMethod( action, GetCurrentRecipient(), notifyByList.ToArray()); } private NotifyBy GetNotifyByMethod(Guid itemID) { var productSubscriptionManager = WebItemManager.Instance[itemID].Context.SubscriptionManager as IProductSubscriptionManager; if (productSubscriptionManager == null) return 0; if (productSubscriptionManager.GroupByType == GroupByType.Modules) { foreach (var item in WebItemManager.Instance.GetSubItems(itemID)) { if (item.Context == null || item.Context.SubscriptionManager == null) continue; foreach (var s in item.Context.SubscriptionManager.GetSubscriptionTypes()) return ConvertToNotifyByValue(item.Context.SubscriptionManager, s); } } else if (productSubscriptionManager.GroupByType == GroupByType.Groups || productSubscriptionManager.GroupByType == GroupByType.Simple) { foreach (var s in productSubscriptionManager.GetSubscriptionTypes()) return ConvertToNotifyByValue(productSubscriptionManager, s); } return 0; } private NotifyBy ConvertToNotifyByValue(ISubscriptionManager subscriptionManager, SubscriptionType s) { return ConvertToNotifyByValue(subscriptionManager, s.NotifyAction); } private NotifyBy ConvertToNotifyByValue(ISubscriptionManager subscriptionManager, INotifyAction action) { var notifyByArray = subscriptionManager.SubscriptionProvider.GetSubscriptionMethod(action, GetCurrentRecipient()).ToList(); var notify = NotifyBy.None; notifyByArray.ForEach(n => notify |= NotifyByBindingsReverse[n]); return notify; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Text; using System.Xml; using MetX.Standard.Library.Extensions; namespace MetX.Standard.IO { /// <summary>Helper functions to simplify working with sql connections</summary> public static class Sql { /// <summary>This returns the string representation of a column from a reader. Supports DBNull (default return value), guid, int, and datetime. All other types simply call GetString() on the reader.</summary> /// <param name="rst">The reader</param> /// <param name="index">The column to retreive as a string</param> /// <param name="defaultReturnValue">If the column is DBNull, this will be the return value</param> /// <returns>String representation of the field</returns> /// /// <example><c>GetString(reader, 0, "Something");</c> /// Retrieves field 0. If it's DbNull, the string "Something" will be returned. </example> public static string GetString(SqlDataReader rst, int index , string defaultReturnValue ) { if (rst.IsDBNull(index)) return defaultReturnValue; if ( rst.GetFieldType(index) == Guid.Empty.GetType() ) return rst.GetGuid(index).ToString(); if ( rst.GetFieldType(index) == int.MinValue.GetType() ) return rst.GetInt32(index).ToString(); if ( rst.GetFieldType(index) == DateTime.MinValue.GetType() ) return rst.GetDateTime(index).ToString(CultureInfo.InvariantCulture); return rst.GetString(index); } /// <summary>This returns the string representation of a column from a reader. Supports DBNull (as an empty string), guid, int, and datetime. All other types simply call GetString() on the reader.</summary> /// <param name="rst">The reader</param> /// <param name="index">The column to retreive</param> /// <returns>String representation of the field</returns> /// /// <example><c>GetString(reader, 0);</c> /// Retrieves field 0. If it's DbNull, the string "" will be returned. </example> public static string GetString(SqlDataReader rst, int index) { return GetString(rst, index, string.Empty); } /// <summary>This returns the DateTime representation of a column from a reader. Supports DBNull (as an empty string), guid, int, and datetime. All other types simply call GetDateTime() on the reader.</summary> /// <param name="rst">The reader</param> /// <param name="index">The column to retreive</param> /// <returns>String representation of the field</returns> /// /// <example><c>GetDateTime(reader, 0);</c> /// Retrieves field 0. If it's DbNull, DateTime.MinValue will be returned. </example> public static DateTime GetDateTime(SqlDataReader rst, int index) { var returnValue = new DateTime(0); if (rst.IsDBNull(index)) return returnValue; if ( rst.GetFieldType(index) == DateTime.MinValue.GetType() ) returnValue = rst.GetDateTime(index); return returnValue; } /// <summary>Returns the first value of the first row of the passed sql as a string. If DbNull is the value, DefaultReturnValue is returned instead.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one row with one column, it is recommended the SQL be tailored to do so.</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <param name="defaultReturnValue">The value to return when DbNull is encountered.</param> /// <returns>String value of the first column of the first row</returns> public static string RetrieveSingleStringValue(string sql, string connectionName, string defaultReturnValue) { SqlDataReader rst = null; var cmd = new SqlCommand(sql); string returnValue; var conn = GetConnection(connectionName); try { cmd.Connection = conn; rst = cmd.ExecuteReader(CommandBehavior.SingleRow); if (rst.Read()) { if (rst.IsDBNull(0)) returnValue = defaultReturnValue; else if ( rst.GetFieldType(0) == typeof(Guid) ) returnValue = rst.GetGuid(0).ToString(); else returnValue = GetString(rst, 0); } else returnValue = defaultReturnValue; } catch( Exception e ) { throw new Exception("SQL: " + sql + "\r\n\r\n" + e ); } finally { rst?.Close(); cmd.Dispose(); conn.Close(); conn.Dispose(); } return returnValue; } /// <summary>Returns the first value of the first row of the passed sql as a string. If DbNull is the value, A blank string is returned instead.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one row with one column, it is recommended the SQL be tailored to do so.</param> /// <returns>String value of the first column of the first row</returns> public static string RetrieveSingleStringValue(string sql) { return RetrieveSingleStringValue(sql, null); } public static string RetrieveSingleStringValue(IDataReader idr) { if (idr != null) if (idr.Read()) { var ret = idr.GetString(0); idr.Close(); idr.Dispose(); return ret; } else { idr.Close(); idr.Dispose(); } return null; } /// <summary>Returns the first value of the first row of the passed sql as a string. If DbNull is the value, a blank string is returned instead.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one row with one column, it is recommended the SQL be tailored to do so.</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <returns>String value of the first column of the first row</returns> public static string RetrieveSingleStringValue(string sql, string connectionName) { var g = new Guid(); SqlDataReader rst = null; string returnValue; var conn = GetConnection(connectionName); var cmd = new SqlCommand(sql, conn); try { rst = cmd.ExecuteReader(CommandBehavior.SingleRow); if (rst.Read()) { if (rst.IsDBNull(0)) returnValue = string.Empty ; else if ( rst.GetFieldType(0) == g.GetType() ) returnValue = rst.GetGuid(0).ToString(); else returnValue = GetString(rst, 0); } else returnValue = string.Empty ; } catch( Exception e ) { throw new Exception("SQL: " + sql + "\r\n\r\n" + e ); } finally { rst?.Close(); cmd.Dispose(); conn.Close(); conn.Dispose(); } return returnValue; } /// <summary>Converts a SQL statement into a series of elements via SQLXML. If a "FOR XML" phrase is not found "FOR XML AUTO" is added to the SQL</summary> /// <param name="tagName">The element name to wrap the returned xml element(s). If null or blank, no tag wraps the returned xml string</param> /// <param name="tagAttributes">The attributes to add to the TagName element</param> /// <param name="sql">The SQL to convert to an xml string</param> /// <param name="connectionName">The Connection from Web.config to use</param> /// <returns>The xml string attribute based representation of the SQL statement</returns> public static string ToXml(string tagName, string tagAttributes, string sql, string connectionName = null) { if(sql.IndexOf("FOR XML", StringComparison.Ordinal) == -1) sql += " FOR XML AUTO"; var returnValue = new StringBuilder(); var conn = GetConnection(connectionName); var cmd = new SqlCommand(sql, conn); try { if (tagName != null && tagName.Length > 0) if (tagAttributes != null && tagAttributes.Length > 0) returnValue.AppendLine("<" + tagName + " " + tagAttributes + ">"); else returnValue.AppendLine("<" + tagName + ">"); var xr = cmd.ExecuteXmlReader(); xr.Read(); while (xr.ReadState != ReadState.EndOfFile) returnValue.Append(xr.ReadOuterXml()); xr.Close(); if (tagName != null && tagName.Length > 0) returnValue.AppendLine("</" + tagName + ">"); } catch (Exception e) { throw new Exception("SQL = " + sql + "\r\n\r\n" + e); } finally { cmd.Dispose(); conn.Close(); conn.Dispose(); } return returnValue.ToString(); } /// <summary>Converts a SQL statement into a series of elements via SQLXML. If a "FOR XML" phrase is not found "FOR XML AUTO" is added to the SQL</summary> /// <param name="sql">The SQL to convert to an xml string</param> /// <param name="connectionName">The Connection from Web.config to use</param> /// <returns>The xml string attribute based representation of the SQL statement</returns> public static string ToXml(string sql, string connectionName) { return ToXml(null, null, sql, connectionName); } /// <summary>Converts a SQL statement into a series of elements via SQLXML. If a "FOR XML" phrase is not found "FOR XML AUTO" is added to the SQL</summary> /// <param name="sql">The SQL to convert to an xml string</param> /// <returns>The xml string attribute based representation of the SQL statement</returns> public static string ToXml(string sql) { return ToXml(null, null, sql, null); } /// <summary>Simply runs the SQL statement and returns a DataSet</summary> /// <param name="sql">The SQL to run</param> /// <param name="connectionName">The Connection from Web.config to use</param> /// <returns>A DataSet object with the results</returns> public static DataSet ToDataSet(string sql, string connectionName) { var conn = GetConnection(connectionName); var cmd = new SqlCommand(sql, conn); var returnValue = new DataSet(); try { var ra = new SqlDataAdapter(cmd); ra.Fill(returnValue); } catch (Exception e) { throw new Exception("SQL = " + sql + "\r\n\r\n" + e); } finally { cmd.Dispose(); conn.Close(); conn.Dispose(); } return returnValue; } /// <summary>Simply runs the SQL statement and returns a DataSet</summary> /// <param name="sql">The SQL to run</param> /// <returns>A DataSet object with the results</returns> public static DataSet ToDataSet(string sql) { var conn = DefaultConnection; var cmd = new SqlCommand(sql); var returnValue = new DataSet(); try { cmd.Connection = conn; var ra = new SqlDataAdapter(cmd); ra.Fill(returnValue); } catch (Exception e) { throw new Exception("SQL = " + sql + "\r\n\r\n" + e); } finally { cmd.Dispose(); conn.Close(); conn.Dispose(); } return returnValue; } /// <summary>Returns the first column as a DateTime value of the first row of the passed sql. If DbNull is the value, DateTime.MinValue is returned instead.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one row with one column, it is recommended the SQL be tailored to do so.</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <returns>DateTime value of the first column of the first row</returns> public static DateTime RetrieveSingleDateValue(string sql, string connectionName = null) { var conn = GetConnection(connectionName); var cmd = new SqlCommand(sql, conn); SqlDataReader rst = null; DateTime returnValue; try { rst = cmd.ExecuteReader(CommandBehavior.SingleRow); if (rst.Read()) { returnValue = rst.IsDBNull(0) ? new DateTime(0) : rst.GetDateTime(0); } else returnValue = new DateTime(0); } catch( Exception e) { throw new Exception("SQL = " + sql + "\r\n\r\n" + e); } finally { rst?.Close(); cmd.Dispose(); conn.Close(); conn.Dispose(); } return returnValue; } /// <summary>Returns the first column as an int value of the first row of the passed sql. If DbNull is the value, DefaultReturnValue is returned instead.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one row with one column, it is recommended the SQL be tailored to do so.</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <param name="defaultReturnValue">The value to return if DbNull is encountered</param> /// <returns>int value of the first column of the first row</returns> public static int RetrieveSingleIntegerValue(string sql, string connectionName = null, int defaultReturnValue = 0) { var conn = GetConnection(connectionName); var cmd = new SqlCommand(sql, conn); SqlDataReader rst = null; int returnValue; try { rst = cmd.ExecuteReader(CommandBehavior.SingleRow); if (rst.Read()) { returnValue = rst.IsDBNull(0) ? defaultReturnValue : rst.GetInt32(0); } else returnValue = defaultReturnValue; } catch( Exception e) { throw new Exception("SQL = " + sql + "\r\n\r\n" + e ); } finally { rst?.Close(); cmd.Dispose(); conn.Close(); conn.Dispose(); } return returnValue; } /// <summary>Converts the SQL passed in into a DataSet and returns the DataTable found, otherwise null is returned.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one resultset of values, it is recommended the SQL be tailored to do so.</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <returns>A DataTable object representing the SQL statement or null</returns> public static DataTable ToDataTable(string sql, string connectionName) { var ds = ToDataSet(sql, connectionName); if (ds.Tables.Count < 1) return null; if (ds.Tables[0].Rows.Count < 1) return null; return ds.Tables[0]; } /// <summary>Converts the SQL passed in into a DataSet and returns the DataTable found, otherwise null is returned.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one resultset of values, it is recommended the SQL be tailored to do so.</param> /// <returns>A DataTable object representing the SQL statement or null</returns> public static DataTable ToDataTable(string sql) { var ds = ToDataSet(sql); if (ds.Tables.Count < 1) return null; if (ds.Tables[0].Rows.Count < 1) return null; return ds.Tables[0]; } /// <summary>Converts the SQL passed in into a DataSet and returns the DataTable found, otherwise null is returned.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one resultset of values, it is recommended the SQL be tailored to do so.</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <param name="toFill">The DataTable to fill (could be a strongly typed DataTable)</param> /// <returns>A DataTable object representing the SQL statement or null</returns> public static DataTable ToDataTable(string sql, string connectionName, DataTable toFill) { var conn = GetConnection(connectionName); var cmd = new SqlCommand(sql, conn); toFill ??= new DataTable(); try { var ra = new SqlDataAdapter(cmd); ra.Fill(toFill); } catch (Exception e) { throw new Exception("SQL = " + sql + "\r\n\r\n" + e); } finally { cmd.Dispose(); conn.Close(); conn.Dispose(); } return toFill.Rows.Count < 1 ? null : toFill; } /// <summary>Converts the SQL passed in into a DataSet and returns the DataTable found, otherwise null is returned.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one resultset of values, it is recommended the SQL be tailored to do so.</param> /// <param name="toFill">The DataTable to fill (could be a strongly typed DataTable)</param> /// <returns>A DataTable object representing the SQL statement or null</returns> public static DataTable ToDataTable(string sql, DataTable toFill) { return ToDataTable(sql, null, toFill); } /// <summary>Converts the SQL passed in into a DataSet and returns the DataRowCollection inside the first DataTable found, otherwise null is returned.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one resultset of values, it is recommended the SQL be tailored to do so.</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <returns>A DataRowCollection object representing the SQL statement or null</returns> public static DataRowCollection ToDataRows(string sql, string connectionName) { var ds = ToDataSet(sql, connectionName); if (ds.Tables.Count < 1) return null; if (ds.Tables[0].Rows.Count < 1) return null; return ds.Tables[0].Rows; } /// <summary>Converts the SQL passed in into a DataSet and returns the DataRowCollection inside the first DataTable found, otherwise null is returned.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one resultset of values, it is recommended the SQL be tailored to do so.</param> /// <returns>A DataRowCollection object representing the SQL statement or null</returns> public static DataRowCollection ToDataRows(string sql) { var ds = ToDataSet(sql); if (ds.Tables.Count < 1) return null; if (ds.Tables[0].Rows.Count < 1) return null; return ds.Tables[0].Rows; } /// <summary>Converts the SQL passed in into a DataSet and returns the first DataRow inside the first DataTable found, otherwise null is returned.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one DataRow of values, it is recommended the SQL be tailored to do so.</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <returns>A DataRow object representing the SQL statement or null</returns> public static DataRow ToDataRow(string sql, string connectionName) { var ds = ToDataSet(sql, connectionName); if (ds.Tables.Count < 1) return null; if (ds.Tables[0].Rows.Count < 1) return null; return ds.Tables[0].Rows[0]; } /// <summary>Converts the SQL passed in into a DataSet and returns the first DataRow inside the first DataTable found, otherwise null is returned.</summary> /// <param name="sql">The sql to return. While it doesn't matter if the SQL actually only returns one DataRow of values, it is recommended the SQL be tailored to do so.</param> /// <returns>A DataRow object representing the SQL statement or null</returns> public static DataRow ToDataRow(string sql) { var ds = ToDataSet(sql); if (ds.Tables.Count < 1) return null; if (ds.Tables[0].Rows.Count < 1) return null; return ds.Tables[0].Rows[0]; } /// <summary>Updates a field in the Notification table for a single NotificationID</summary> /// <param name="notificationId">The NotificationID to update</param> /// <param name="fieldName">The field to update</param> /// <param name="newValue">The new value of the field</param> /// <param name="maxLength">If the field has a maximum length, specify it and this function will insure the field does not exceed that length</param> /// <returns>True if the record was updated</returns> public static bool UpdateNotificationField(string notificationId, string fieldName, string newValue, int maxLength) { var conn = DefaultConnection; var cmd = new SqlCommand("SET ARITHABORT ON", conn); cmd.ExecuteNonQuery(); cmd.CommandText = "UPDATE Notification SET " + fieldName + "='" + newValue.Substring(0, maxLength) + "' WHERE NotificationID='" + notificationId + "'"; var recordCount = cmd.ExecuteNonQuery(); cmd.Dispose(); conn.Close(); conn.Dispose(); return recordCount > 0; } /// <summary>Executes a series of SQL statements on the same connection</summary> /// <param name="sqlArray">The list of SQLs to execute</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> public static void Execute(List<string> sqlArray, string connectionName) { if (sqlArray.Count > 0) { var conn = GetConnection(connectionName); var cmd = new SqlCommand(); cmd.Connection = conn; var errorAtSql = - 1; foreach (var sql in sqlArray) { try { errorAtSql = 1; cmd.CommandText = "SET ARITHABORT ON"; cmd.ExecuteNonQuery(); cmd.CommandText = sql; cmd.ExecuteNonQuery(); } catch (Exception e) { conn.Close(); var sb = new StringBuilder(); int currSql; sb.Append("Exception while executing SQL # " + errorAtSql + ": " + sql + "\r\n\r\n" + e + "\r\n"); sb.Append("\r\n------------------------------------------------------------------------\r\n"); for (currSql=0; currSql <= sqlArray.Count - 1; currSql++) sb.Append(currSql + ": " + sqlArray[currSql] + "\r\n\r\n"); cmd.Dispose(); conn.Dispose(); throw new Exception(sb.ToString()); } } cmd.Dispose(); conn.Close(); conn.Dispose(); } } /// <summary>Executes a series of SQL statements on the same Default connection</summary> /// <param name="sqlArray">The list of SQLs to execute</param> public static void Execute(List<string> sqlArray) { Execute(sqlArray, DefaultConnectionString); } /// <summary>Executes a SQL statement</summary> /// <param name="sql">The SQL to execute</param> /// <param name="connectionName">The name of the connection to use. If that connection doesn't exist, the "Default" connection is used.</param> /// <returns>The number of records affected</returns> public static int Execute(string sql, string connectionName) { var recordCount = 0; if (sql != null && sql.Length > 0) { var conn = GetConnection(connectionName); var cmd = new SqlCommand("SET ARITHABORT ON", conn); try { cmd.ExecuteNonQuery(); cmd.CommandText = sql; recordCount = cmd.ExecuteNonQuery(); } catch (Exception e) { throw new Exception("SQL = " + sql + "\r\n\r\n" + e); } finally { cmd.Dispose(); if (conn.State == ConnectionState.Open) conn.Close(); conn.Dispose(); } } return recordCount; } /// <summary>Executes a SQL statement</summary> /// <param name="sql">The SQL to execute</param> /// <returns>The number of records affected</returns> public static int Execute(string sql) { return Execute(sql, DefaultConnectionString); } /// <summary>Returns a SqlConnection object given the connection name from Web.config. If that entry is blank or missing, Default.SqlClient is used.</summary> /// <param name="connectionName">The Web.config key name containing the connection string</param> /// <returns>An open SqlConnection object to the appropriate database (remember to close it)</returns> public static SqlConnection GetConnection(string connectionName) { var ret = new SqlConnection(GetConnectionString(connectionName)); ret.Open(); return ret; } /// <summary>Returns the Web.config connection string named. If that entry is blank or missing, Default.SqlClient is returned.</summary> /// <param name="connectionName">The Web.config key name</param> /// <returns>A connection string</returns> public static string GetConnectionString(string connectionName) { if (connectionName.IsEmpty()) return DefaultConnectionString; var settings = ConfigurationManager.ConnectionStrings[connectionName]; var connectionString = settings?.ConnectionString; if (connectionString.IsEmpty()) return DefaultConnectionString; return connectionString; } /// <summary>Returns the value of the Web.config key "Default.SqlClient"</summary> public static string DefaultConnectionString => ConfigurationManager.ConnectionStrings["Default"].ConnectionString; /// <summary>Returns a SqlClonnetion object using DefaultConnectionString</summary> public static SqlConnection DefaultConnection { get { var ret = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString); ret.Open(); return ret; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace PdfService.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using System.Linq; using Microsoft.Rest.Azure; using Models; /// <summary> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestPagingTestService : Microsoft.Rest.ServiceClient<AutoRestPagingTestService>, IAutoRestPagingTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IPagingOperations. /// </summary> public virtual IPagingOperations Paging { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestPagingTestService(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestPagingTestService(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Paging = new PagingOperations(this); this.BaseUri = new System.Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } } }
// 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 gagr = Google.Api.Gax.ResourceNames; using gcmv = Google.Cloud.Memcache.V1; using sys = System; namespace Google.Cloud.Memcache.V1 { /// <summary>Resource name for the <c>Instance</c> resource.</summary> public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName> { /// <summary>The possible contents of <see cref="InstanceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> ProjectLocationInstance = 1, } private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}"); /// <summary>Creates a <see cref="InstanceName"/> 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="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="InstanceName"/> with the pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns> public static InstanceName FromProjectLocationInstance(string projectId, string locationId, string instanceId) => new InstanceName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </returns> public static string Format(string projectId, string locationId, string instanceId) => FormatProjectLocationInstance(projectId, locationId, instanceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </returns> public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) => s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary>Parses the given resource name string into a new <see cref="InstanceName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName) => Parse(instanceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="InstanceName"/> 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>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">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="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName, bool allowUnparsed) => TryParse(instanceName, allowUnparsed, out InstanceName 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="InstanceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, 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 instanceName, out InstanceName result) => TryParse(instanceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> 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>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">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="InstanceName"/>, 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 instanceName, bool allowUnparsed, out InstanceName result) { gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); gax::TemplatedResourceName resourceName; if (s_projectLocationInstance.TryParseName(instanceName, out resourceName)) { result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; InstanceId = instanceId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> public InstanceName(string projectId, string locationId, string instanceId) : this(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))) { } /// <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>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string InstanceId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { 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.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId); 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 InstanceName); /// <inheritdoc/> public bool Equals(InstanceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(InstanceName a, InstanceName b) => !(a == b); } public partial class Instance { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListInstancesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetInstanceRequest { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateInstanceRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteInstanceRequest { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ApplyParametersRequest { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class UpdateParametersRequest { /// <summary> /// <see cref="gcmv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace MagicPotion.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.Remoting; using Quartz.Core; using Quartz.Impl.Matchers; using Quartz.Simpl; using Quartz.Spi; namespace Quartz.Impl { /// <summary> /// An implementation of the <see cref="IScheduler" /> interface that remotely /// proxies all method calls to the equivalent call on a given <see cref="QuartzScheduler" /> /// instance, via remoting or similar technology. /// </summary> /// <seealso cref="IScheduler" /> /// <seealso cref="QuartzScheduler" /> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> public class RemoteScheduler : IScheduler { private IRemotableQuartzScheduler rsched; private readonly string schedId; private readonly IRemotableSchedulerProxyFactory proxyFactory; /// <summary> /// Construct a <see cref="RemoteScheduler" /> instance to proxy the given /// RemoteableQuartzScheduler instance. /// </summary> public RemoteScheduler(string schedId, IRemotableSchedulerProxyFactory proxyFactory) { this.schedId = schedId; this.proxyFactory = proxyFactory; } /// <summary> /// returns true if the given JobGroup /// is paused /// </summary> /// <param name="groupName"></param> /// <returns></returns> public virtual bool IsJobGroupPaused(string groupName) { return CallInGuard(x => x.IsJobGroupPaused(groupName)); } /// <summary> /// returns true if the given TriggerGroup /// is paused /// </summary> /// <param name="groupName"></param> /// <returns></returns> public virtual bool IsTriggerGroupPaused(string groupName) { return CallInGuard(x => x.IsTriggerGroupPaused(groupName)); } /// <summary> /// Returns the name of the <see cref="IScheduler" />. /// </summary> public virtual string SchedulerName { get { return CallInGuard(x => x.SchedulerName); } } /// <summary> /// Returns the instance Id of the <see cref="IScheduler" />. /// </summary> public virtual string SchedulerInstanceId { get { return CallInGuard(x => x.SchedulerInstanceId); } } /// <summary> /// Get a <see cref="SchedulerMetaData"/> object describing the settings /// and capabilities of the scheduler instance. /// <para> /// Note that the data returned is an 'instantaneous' snap-shot, and that as /// soon as it's returned, the meta data values may be different. /// </para> /// </summary> /// <returns></returns> public virtual SchedulerMetaData GetMetaData() { return CallInGuard(x => new SchedulerMetaData(SchedulerName, SchedulerInstanceId, GetType(), true, IsStarted, InStandbyMode, IsShutdown, x.RunningSince, x.NumJobsExecuted, x.JobStoreClass, x.SupportsPersistence, x.Clustered, x.ThreadPoolClass, x.ThreadPoolSize, x.Version)); } /// <summary> /// Returns the <see cref="SchedulerContext" /> of the <see cref="IScheduler" />. /// </summary> public virtual SchedulerContext Context { get { return CallInGuard(x => x.SchedulerContext); } } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual bool InStandbyMode { get { return CallInGuard(x => x.InStandbyMode); } } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual bool IsShutdown { get { return CallInGuard(x => x.IsShutdown); } } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual IList<IJobExecutionContext> GetCurrentlyExecutingJobs() { return CallInGuard(x => x.CurrentlyExecutingJobs); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual IList<string> GetJobGroupNames() { return CallInGuard(x => x.GetJobGroupNames()); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual IList<string> GetTriggerGroupNames() { return CallInGuard(x => x.GetTriggerGroupNames()); } /// <summary> /// Get the names of all <see cref="ITrigger" /> groups that are paused. /// </summary> /// <value></value> public virtual Collection.ISet<string> GetPausedTriggerGroups() { return CallInGuard(x => x.GetPausedTriggerGroups()); } /// <summary> /// Set the <see cref="JobFactory" /> that will be responsible for producing /// instances of <see cref="IJob" /> classes. /// <para> /// JobFactories may be of use to those wishing to have their application /// produce <see cref="IJob" /> instances via some special mechanism, such as to /// give the opportunity for dependency injection. /// </para> /// </summary> /// <value></value> /// <seealso cref="IJobFactory"/> /// <throws> SchedulerException </throws> public virtual IJobFactory JobFactory { set { throw new SchedulerException("Operation not supported for remote schedulers."); } } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void Start() { CallInGuard(x => x.Start()); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public void StartDelayed(TimeSpan delay) { CallInGuard(x => x.StartDelayed(delay)); } /// <summary> /// Whether the scheduler has been started. /// </summary> /// <value></value> /// <remarks> /// Note: This only reflects whether <see cref="Start"/> has ever /// been called on this Scheduler, so it will return <see langword="true" /> even /// if the <see cref="IScheduler" /> is currently in standby mode or has been /// since shutdown. /// </remarks> /// <seealso cref="Start"/> /// <seealso cref="IsShutdown"/> /// <seealso cref="InStandbyMode"/> public virtual bool IsStarted { get { return CallInGuard(x => x.RunningSince.HasValue); } } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void Standby() { CallInGuard(x => x.Standby()); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void Shutdown() { try { string schedulerName = SchedulerName; GetRemoteScheduler().Shutdown(); SchedulerRepository.Instance.Remove(schedulerName); } catch (RemotingException re) { throw InvalidateHandleCreateException("Error communicating with remote scheduler.", re); } } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void Shutdown(bool waitForJobsToComplete) { CallInGuard(x => x.Shutdown(waitForJobsToComplete)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual DateTimeOffset ScheduleJob(IJobDetail jobDetail, ITrigger trigger) { return CallInGuard(x => x.ScheduleJob(jobDetail, trigger)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual DateTimeOffset ScheduleJob(ITrigger trigger) { return CallInGuard(x => x.ScheduleJob(trigger)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void AddJob(IJobDetail jobDetail, bool replace) { CallInGuard(x => x.AddJob(jobDetail, replace)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void AddJob(IJobDetail jobDetail, bool replace, bool storeNonDurableWhileAwaitingScheduling) { CallInGuard(x => x.AddJob(jobDetail, replace, storeNonDurableWhileAwaitingScheduling)); } public virtual bool DeleteJobs(IList<JobKey> jobKeys) { return CallInGuard(x => x.DeleteJobs(jobKeys)); } public virtual void ScheduleJobs(IDictionary<IJobDetail, Collection.ISet<ITrigger>> triggersAndJobs, bool replace) { CallInGuard(x => x.ScheduleJobs(triggersAndJobs, replace)); } public void ScheduleJob(IJobDetail jobDetail, Collection.ISet<ITrigger> triggersForJob, bool replace) { CallInGuard(x => x.ScheduleJob(jobDetail, triggersForJob, replace)); } public virtual bool UnscheduleJobs(IList<TriggerKey> triggerKeys) { return CallInGuard(x => x.UnscheduleJobs(triggerKeys)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual bool DeleteJob(JobKey jobKey) { return CallInGuard(x => x.DeleteJob(jobKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual bool UnscheduleJob(TriggerKey triggerKey) { return CallInGuard(x => x.UnscheduleJob(triggerKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual DateTimeOffset? RescheduleJob(TriggerKey triggerKey, ITrigger newTrigger) { return CallInGuard(x => x.RescheduleJob(triggerKey, newTrigger)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void TriggerJob(JobKey jobKey) { TriggerJob(jobKey, null); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void TriggerJob(JobKey jobKey, JobDataMap data) { CallInGuard(x => x.TriggerJob(jobKey, data)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void PauseTrigger(TriggerKey triggerKey) { CallInGuard(x => x.PauseTrigger(triggerKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void PauseTriggers(GroupMatcher<TriggerKey> matcher) { CallInGuard(x => x.PauseTriggers(matcher)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void PauseJob(JobKey jobKey) { CallInGuard(x => x.PauseJob(jobKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void PauseJobs(GroupMatcher<JobKey> matcher) { CallInGuard(x => x.PauseJobs(matcher)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void ResumeTrigger(TriggerKey triggerKey) { CallInGuard(x => x.ResumeTrigger(triggerKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void ResumeTriggers(GroupMatcher<TriggerKey> matcher) { CallInGuard(x => x.ResumeTriggers(matcher)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void ResumeJob(JobKey jobKey) { CallInGuard(x => x.ResumeJob(jobKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void ResumeJobs(GroupMatcher<JobKey> matcher) { CallInGuard(x => x.ResumeJobs(matcher)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void PauseAll() { CallInGuard(x => x.PauseAll()); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void ResumeAll() { CallInGuard(x => x.ResumeAll()); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual Collection.ISet<JobKey> GetJobKeys(GroupMatcher<JobKey> matcher) { return CallInGuard(x => x.GetJobKeys(matcher)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual IList<ITrigger> GetTriggersOfJob(JobKey jobKey) { return CallInGuard(x => x.GetTriggersOfJob(jobKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual Collection.ISet<TriggerKey> GetTriggerKeys(GroupMatcher<TriggerKey> matcher) { return CallInGuard(x => x.GetTriggerKeys(matcher)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual IJobDetail GetJobDetail(JobKey jobKey) { return CallInGuard(x => x.GetJobDetail(jobKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual bool CheckExists(JobKey jobKey) { return CallInGuard(x => x.CheckExists(jobKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual bool CheckExists(TriggerKey triggerKey) { return CallInGuard(x => x.CheckExists(triggerKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void Clear() { CallInGuard(x => x.Clear()); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual ITrigger GetTrigger(TriggerKey triggerKey) { return CallInGuard(x => x.GetTrigger(triggerKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual TriggerState GetTriggerState(TriggerKey triggerKey) { return CallInGuard(x => x.GetTriggerState(triggerKey)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void AddCalendar(string calName, ICalendar calendar, bool replace, bool updateTriggers) { CallInGuard(x => x.AddCalendar(calName, calendar, replace, updateTriggers)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual bool DeleteCalendar(string calName) { return CallInGuard(x => x.DeleteCalendar(calName)); } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual ICalendar GetCalendar(string calName) { return CallInGuard(x => x.GetCalendar(calName)); } /// <summary> /// Get the names of all registered <see cref="ICalendar"/>. /// </summary> /// <returns></returns> public IList<string> GetCalendarNames() { return CallInGuard(x => x.GetCalendarNames()); } public IListenerManager ListenerManager { get { throw new SchedulerException("Operation not supported for remote schedulers."); } } /// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual bool Interrupt(JobKey jobKey) { try { return GetRemoteScheduler().Interrupt(jobKey); } catch (RemotingException re) { throw new UnableToInterruptJobException(InvalidateHandleCreateException("Error communicating with remote scheduler.", re)); } catch (SchedulerException se) { throw new UnableToInterruptJobException(se); } } public bool Interrupt(string fireInstanceId) { try { return GetRemoteScheduler().Interrupt(fireInstanceId); } catch (RemotingException re) { throw new UnableToInterruptJobException(InvalidateHandleCreateException("Error communicating with remote scheduler.", re)); } catch (SchedulerException se) { throw new UnableToInterruptJobException(se); } } protected virtual void CallInGuard(Action<IRemotableQuartzScheduler> action) { try { action(GetRemoteScheduler()); } catch (RemotingException re) { throw InvalidateHandleCreateException("Error communicating with remote scheduler.", re); } } protected virtual T CallInGuard<T>(Func<IRemotableQuartzScheduler, T> func) { try { return func(GetRemoteScheduler()); } catch (RemotingException re) { throw InvalidateHandleCreateException("Error communicating with remote scheduler.", re); } } protected virtual IRemotableQuartzScheduler GetRemoteScheduler() { if (rsched != null) { return rsched; } try { rsched = proxyFactory.GetProxy(); } catch (Exception e) { string errorMessage = string.Format(CultureInfo.InvariantCulture, "Could not get handle to remote scheduler: {0}", e.Message); SchedulerException initException = new SchedulerException(errorMessage, e); throw initException; } return rsched; } protected virtual SchedulerException InvalidateHandleCreateException(string msg, Exception cause) { rsched = null; SchedulerException ex = new SchedulerException(msg, cause); return ex; } public void Dispose() { } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Services; using NUnit.Framework; /// <summary> /// Services tests. /// </summary> public class ServicesTest { /** */ private const string SvcName = "Service1"; /** */ private const string CacheName = "cache1"; /** */ private const int AffKey = 25; /** */ protected IIgnite Grid1; /** */ protected IIgnite Grid2; /** */ protected IIgnite Grid3; /** */ protected IIgnite[] Grids; [TestFixtureTearDown] public void FixtureTearDown() { StopGrids(); } /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { StartGrids(); } /// <summary> /// Executes after each test. /// </summary> [TearDown] public void TearDown() { try { Services.CancelAll(); TestUtils.AssertHandleRegistryIsEmpty(1000, Grid1, Grid2, Grid3); } catch (Exception) { // Restart grids to cleanup StopGrids(); throw; } finally { if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes")) StopGrids(); // clean events for other tests } } /// <summary> /// Tests deployment. /// </summary> [Test] public void TestDeploy([Values(true, false)] bool binarizable) { var cfg = new ServiceConfiguration { Name = SvcName, MaxPerNodeCount = 3, TotalCount = 3, NodeFilter = new NodeFilter {NodeId = Grid1.GetCluster().GetLocalNode().Id}, Service = binarizable ? new TestIgniteServiceBinarizable() : new TestIgniteServiceSerializable() }; Services.Deploy(cfg); CheckServiceStarted(Grid1, 3); } /// <summary> /// Tests several services deployment via DeployAll() method. /// </summary> [Test] public void TestDeployAll([Values(true, false)] bool binarizable) { const int num = 10; var cfgs = new List<ServiceConfiguration>(); for (var i = 0; i < num; i++) { cfgs.Add(new ServiceConfiguration { Name = MakeServiceName(i), MaxPerNodeCount = 3, TotalCount = 3, NodeFilter = new NodeFilter {NodeId = Grid1.GetCluster().GetLocalNode().Id}, Service = binarizable ? new TestIgniteServiceBinarizable() : new TestIgniteServiceSerializable() }); } Services.DeployAll(cfgs); for (var i = 0; i < num; i++) { CheckServiceStarted(Grid1, 3, MakeServiceName(i)); } } /// <summary> /// Tests cluster singleton deployment. /// </summary> [Test] public void TestDeployClusterSingleton() { var svc = new TestIgniteServiceSerializable(); Services.DeployClusterSingleton(SvcName, svc); var svc0 = Services.GetServiceProxy<ITestIgniteService>(SvcName); // Check that only one node has the service. foreach (var grid in Grids) { if (grid.GetCluster().GetLocalNode().Id == svc0.NodeId) CheckServiceStarted(grid); else Assert.IsNull(grid.GetServices().GetService<TestIgniteServiceSerializable>(SvcName)); } } /// <summary> /// Tests node singleton deployment. /// </summary> [Test] public void TestDeployNodeSingleton() { var svc = new TestIgniteServiceSerializable(); Services.DeployNodeSingleton(SvcName, svc); Assert.AreEqual(1, Grid1.GetServices().GetServices<ITestIgniteService>(SvcName).Count); Assert.AreEqual(1, Grid2.GetServices().GetServices<ITestIgniteService>(SvcName).Count); Assert.AreEqual(0, Grid3.GetServices().GetServices<ITestIgniteService>(SvcName).Count); } /// <summary> /// Tests key affinity singleton deployment. /// </summary> [Test] public void TestDeployKeyAffinitySingleton() { var svc = new TestIgniteServiceBinarizable(); Services.DeployKeyAffinitySingleton(SvcName, svc, CacheName, AffKey); var affNode = Grid1.GetAffinity(CacheName).MapKeyToNode(AffKey); var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.AreEqual(affNode.Id, prx.NodeId); } /// <summary> /// Tests key affinity singleton deployment. /// </summary> [Test] public void TestDeployKeyAffinitySingletonBinarizable() { var services = Services.WithKeepBinary(); var svc = new TestIgniteServiceBinarizable(); var affKey = new BinarizableObject {Val = AffKey}; services.DeployKeyAffinitySingleton(SvcName, svc, CacheName, affKey); var prx = services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.IsTrue(prx.Initialized); } /// <summary> /// Tests multiple deployment. /// </summary> [Test] public void TestDeployMultiple() { var svc = new TestIgniteServiceSerializable(); Services.DeployMultiple(SvcName, svc, Grids.Length * 5, 5); foreach (var grid in Grids.Where(x => !x.GetConfiguration().ClientMode)) CheckServiceStarted(grid, 5); } /// <summary> /// Tests cancellation. /// </summary> [Test] public void TestCancel() { for (var i = 0; i < 10; i++) { Services.DeployNodeSingleton(SvcName + i, new TestIgniteServiceBinarizable()); Assert.IsNotNull(Services.GetService<ITestIgniteService>(SvcName + i)); } Services.Cancel(SvcName + 0); AssertNoService(SvcName + 0); Services.Cancel(SvcName + 1); AssertNoService(SvcName + 1); for (var i = 2; i < 10; i++) Assert.IsNotNull(Services.GetService<ITestIgniteService>(SvcName + i)); Services.CancelAll(); for (var i = 0; i < 10; i++) AssertNoService(SvcName + i); } /// <summary> /// Tests service proxy. /// </summary> [Test] public void TestGetServiceProxy([Values(true, false)] bool binarizable) { // Test proxy without a service var ex = Assert.Throws<IgniteException>(()=> Services.GetServiceProxy<ITestIgniteService>(SvcName)); Assert.AreEqual("Failed to find deployed service: " + SvcName, ex.Message); // Deploy to grid2 & grid3 var svc = binarizable ? new TestIgniteServiceBinarizable {TestProperty = 17} : new TestIgniteServiceSerializable {TestProperty = 17}; Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id, Grid1.GetCluster().GetLocalNode().Id) .GetServices().DeployNodeSingleton(SvcName, svc); // Make sure there is no local instance on grid3 Assert.IsNull(Grid3.GetServices().GetService<ITestIgniteService>(SvcName)); // Get proxy var prx = Grid3.GetServices().GetServiceProxy<ITestIgniteService>(SvcName); // Check proxy properties Assert.IsNotNull(prx); Assert.AreEqual(prx.ToString(), svc.ToString()); Assert.AreEqual(17, prx.TestProperty); Assert.IsTrue(prx.Initialized); Assert.IsTrue(prx.Executed); Assert.IsFalse(prx.Cancelled); Assert.AreEqual(SvcName, prx.LastCallContextName); // Check err method Assert.Throws<ServiceInvocationException>(() => prx.ErrMethod(123)); // Check local scenario (proxy should not be created for local instance) Assert.IsTrue(ReferenceEquals(Grid2.GetServices().GetService<ITestIgniteService>(SvcName), Grid2.GetServices().GetServiceProxy<ITestIgniteService>(SvcName))); // Check sticky = false: call multiple times, check that different nodes get invoked var invokedIds = Enumerable.Range(1, 100).Select(x => prx.NodeId).Distinct().ToList(); Assert.AreEqual(2, invokedIds.Count); // Check sticky = true: all calls should be to the same node prx = Grid3.GetServices().GetServiceProxy<ITestIgniteService>(SvcName, true); invokedIds = Enumerable.Range(1, 100).Select(x => prx.NodeId).Distinct().ToList(); Assert.AreEqual(1, invokedIds.Count); // Proxy does not work for cancelled service. Services.CancelAll(); Assert.Throws<ServiceInvocationException>(() => { Assert.IsTrue(prx.Cancelled); }); } /// <summary> /// Tests dynamic service proxies. /// </summary> [Test] public void TestGetDynamicServiceProxy() { // Deploy to remotes. var svc = new TestIgniteServiceSerializable { TestProperty = 37 }; Grid1.GetCluster().ForRemotes().GetServices().DeployNodeSingleton(SvcName, svc); // Make sure there is no local instance on grid3 Assert.IsNull(Grid3.GetServices().GetService<ITestIgniteService>(SvcName)); // Get proxy. dynamic prx = Grid3.GetServices().GetDynamicServiceProxy(SvcName, false); // Property getter. Assert.AreEqual(37, prx.TestProperty); Assert.IsTrue(prx.Initialized); Assert.IsTrue(prx.Executed); Assert.IsFalse(prx.Cancelled); Assert.AreEqual(SvcName, prx.LastCallContextName); // Property setter. prx.TestProperty = 42; Assert.AreEqual(42, prx.TestProperty); // Method invoke. Assert.AreEqual(prx.ToString(), svc.ToString()); Assert.AreEqual("baz", prx.Method("baz")); // Non-existent member. var ex = Assert.Throws<ServiceInvocationException>(() => prx.FooBar(1)); Assert.AreEqual( string.Format("Failed to invoke proxy: there is no method 'FooBar' in type '{0}' with 1 arguments", typeof(TestIgniteServiceSerializable)), (ex.InnerException ?? ex).Message); // Exception in service. ex = Assert.Throws<ServiceInvocationException>(() => prx.ErrMethod(123)); Assert.AreEqual("ExpectedException", (ex.InnerException ?? ex).Message.Substring(0, 17)); } /// <summary> /// Tests dynamic service proxies with local service instance. /// </summary> [Test] public void TestGetDynamicServiceProxyLocal() { // Deploy to all nodes. var svc = new TestIgniteServiceSerializable { TestProperty = 37 }; Grid1.GetServices().DeployNodeSingleton(SvcName, svc); // Make sure there is an instance on grid1. var svcInst = Grid1.GetServices().GetService<ITestIgniteService>(SvcName); Assert.IsNotNull(svcInst); // Get dynamic proxy that simply wraps the service instance. var prx = Grid1.GetServices().GetDynamicServiceProxy(SvcName); Assert.AreSame(prx, svcInst); } /// <summary> /// Tests the duck typing: proxy interface can be different from actual service interface, /// only called method signature should be compatible. /// </summary> [Test] public void TestDuckTyping([Values(true, false)] bool local) { var svc = new TestIgniteServiceBinarizable {TestProperty = 33}; // Deploy locally or to the remote node var nodeId = (local ? Grid1 : Grid2).GetCluster().GetLocalNode().Id; var cluster = Grid1.GetCluster().ForNodeIds(nodeId); cluster.GetServices().DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.GetServiceProxy<ITestIgniteServiceProxyInterface>(SvcName); // NodeId signature is the same as in service Assert.AreEqual(nodeId, prx.NodeId); // Method signature is different from service signature (object -> object), but is compatible. Assert.AreEqual(15, prx.Method(15)); // TestProperty is object in proxy and int in service, getter works.. Assert.AreEqual(33, prx.TestProperty); // .. but setter does not var ex = Assert.Throws<ServiceInvocationException>(() => { prx.TestProperty = new object(); }); Assert.IsInstanceOf<InvalidCastException>(ex.InnerException); } /// <summary> /// Tests service descriptors. /// </summary> [Test] public void TestServiceDescriptors() { Services.DeployKeyAffinitySingleton(SvcName, new TestIgniteServiceSerializable(), CacheName, 1); var descriptors = Services.GetServiceDescriptors(); Assert.AreEqual(1, descriptors.Count); var desc = descriptors.Single(); Assert.AreEqual(SvcName, desc.Name); Assert.AreEqual(CacheName, desc.CacheName); Assert.AreEqual(1, desc.AffinityKey); Assert.AreEqual(1, desc.MaxPerNodeCount); Assert.AreEqual(1, desc.TotalCount); Assert.AreEqual(Grid1.GetCluster().GetLocalNode().Id, desc.OriginNodeId); var top = desc.TopologySnapshot; var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.AreEqual(1, top.Count); Assert.AreEqual(prx.NodeId, top.Keys.Single()); Assert.AreEqual(1, top.Values.Single()); } /// <summary> /// Tests the client binary flag. /// </summary> [Test] public void TestWithKeepBinaryClient() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject {Val = 11}; var res = (IBinaryObject) prx.Method(obj); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); res = (IBinaryObject) prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); } /// <summary> /// Tests the server binary flag. /// </summary> [Test] public void TestWithKeepBinaryServer() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithServerKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithServerKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject { Val = 11 }; var res = (BinarizableObject) prx.Method(obj); Assert.AreEqual(11, res.Val); res = (BinarizableObject)prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Val); } /// <summary> /// Tests server and client binary flag. /// </summary> [Test] public void TestWithKeepBinaryBoth() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithKeepBinary().WithServerKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithKeepBinary().WithServerKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject { Val = 11 }; var res = (IBinaryObject)prx.Method(obj); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); res = (IBinaryObject)prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); } /// <summary> /// Tests exception in Initialize. /// </summary> [Test] public void TestDeployMultipleException([Values(true, false)] bool keepBinary) { VerifyDeploymentException((services, svc) => services.DeployMultiple(SvcName, svc, Grids.Length, 1), keepBinary); } /// <summary> /// Tests exception in Initialize. /// </summary> [Test] public void TestDeployException([Values(true, false)] bool keepBinary) { VerifyDeploymentException((services, svc) => services.Deploy(new ServiceConfiguration { Name = SvcName, Service = svc, TotalCount = Grids.Length, MaxPerNodeCount = 1 }), keepBinary); } /// <summary> /// Tests ServiceDeploymentException result via DeployAll() method. /// </summary> [Test] public void TestDeployAllException([Values(true, false)] bool binarizable) { const int num = 10; const int firstFailedIdx = 1; const int secondFailedIdx = 9; var cfgs = new List<ServiceConfiguration>(); for (var i = 0; i < num; i++) { var throwInit = (i == firstFailedIdx || i == secondFailedIdx); cfgs.Add(new ServiceConfiguration { Name = MakeServiceName(i), MaxPerNodeCount = 2, TotalCount = 2, NodeFilter = new NodeFilter { NodeId = Grid1.GetCluster().GetLocalNode().Id }, Service = binarizable ? new TestIgniteServiceBinarizable { TestProperty = i, ThrowInit = throwInit } : new TestIgniteServiceSerializable { TestProperty = i, ThrowInit = throwInit } }); } var deploymentException = Assert.Throws<ServiceDeploymentException>(() => Services.DeployAll(cfgs)); var failedCfgs = deploymentException.FailedConfigurations; Assert.IsNotNull(failedCfgs); Assert.AreEqual(2, failedCfgs.Count); var firstFailedSvc = binarizable ? failedCfgs.ElementAt(0).Service as TestIgniteServiceBinarizable : failedCfgs.ElementAt(0).Service as TestIgniteServiceSerializable; var secondFailedSvc = binarizable ? failedCfgs.ElementAt(1).Service as TestIgniteServiceBinarizable : failedCfgs.ElementAt(1).Service as TestIgniteServiceSerializable; Assert.IsNotNull(firstFailedSvc); Assert.IsNotNull(secondFailedSvc); Assert.AreEqual(firstFailedIdx, firstFailedSvc.TestProperty); Assert.AreEqual(secondFailedIdx, secondFailedSvc.TestProperty); for (var i = 0; i < num; i++) { if (i != firstFailedIdx && i != secondFailedIdx) { CheckServiceStarted(Grid1, 2, MakeServiceName(i)); } } } /// <summary> /// Tests input errors for DeployAll() method. /// </summary> [Test] public void TestDeployAllInputErrors() { var nullException = Assert.Throws<ArgumentNullException>(() => Services.DeployAll(null)); Assert.IsTrue(nullException.Message.Contains("configurations")); var argException = Assert.Throws<ArgumentException>(() => Services.DeployAll(new List<ServiceConfiguration>())); Assert.IsTrue(argException.Message.Contains("empty collection")); nullException = Assert.Throws<ArgumentNullException>(() => Services.DeployAll(new List<ServiceConfiguration> { null })); Assert.IsTrue(nullException.Message.Contains("configurations[0]")); nullException = Assert.Throws<ArgumentNullException>(() => Services.DeployAll(new List<ServiceConfiguration> { new ServiceConfiguration { Name = SvcName } })); Assert.IsTrue(nullException.Message.Contains("configurations[0].Service")); argException = Assert.Throws<ArgumentException>(() => Services.DeployAll(new List<ServiceConfiguration> { new ServiceConfiguration { Service = new TestIgniteServiceSerializable() } })); Assert.IsTrue(argException.Message.Contains("configurations[0].Name")); argException = Assert.Throws<ArgumentException>(() => Services.DeployAll(new List<ServiceConfiguration> { new ServiceConfiguration { Service = new TestIgniteServiceSerializable(), Name = string.Empty } })); Assert.IsTrue(argException.Message.Contains("configurations[0].Name")); } /// <summary> /// Tests [Serializable] usage of ServiceDeploymentException. /// </summary> [Test] public void TestDeploymentExceptionSerializable() { var cfg = new ServiceConfiguration { Name = "foo", CacheName = "cacheName", AffinityKey = 1, MaxPerNodeCount = 2, Service = new TestIgniteServiceSerializable(), NodeFilter = new NodeFilter(), TotalCount = 3 }; var ex = new ServiceDeploymentException("msg", new Exception("in"), new[] {cfg}); var formatter = new BinaryFormatter(); var stream = new MemoryStream(); formatter.Serialize(stream, ex); stream.Seek(0, SeekOrigin.Begin); var res = (ServiceDeploymentException) formatter.Deserialize(stream); Assert.AreEqual(ex.Message, res.Message); Assert.IsNotNull(res.InnerException); Assert.AreEqual("in", res.InnerException.Message); var resCfg = res.FailedConfigurations.Single(); Assert.AreEqual(cfg.Name, resCfg.Name); Assert.AreEqual(cfg.CacheName, resCfg.CacheName); Assert.AreEqual(cfg.AffinityKey, resCfg.AffinityKey); Assert.AreEqual(cfg.MaxPerNodeCount, resCfg.MaxPerNodeCount); Assert.AreEqual(cfg.TotalCount, resCfg.TotalCount); Assert.IsInstanceOf<TestIgniteServiceSerializable>(cfg.Service); Assert.IsInstanceOf<NodeFilter>(cfg.NodeFilter); } /// <summary> /// Verifies the deployment exception. /// </summary> private void VerifyDeploymentException(Action<IServices, IService> deploy, bool keepBinary) { var svc = new TestIgniteServiceSerializable { ThrowInit = true }; var services = Services; if (keepBinary) { services = services.WithKeepBinary(); } var deploymentException = Assert.Throws<ServiceDeploymentException>(() => deploy(services, svc)); var text = keepBinary ? "Service deployment failed with a binary error. Examine BinaryCause for details." : "Service deployment failed with an exception. Examine InnerException for details."; Assert.AreEqual(text, deploymentException.Message); Exception ex; if (keepBinary) { Assert.IsNull(deploymentException.InnerException); ex = deploymentException.BinaryCause.Deserialize<Exception>(); } else { Assert.IsNull(deploymentException.BinaryCause); ex = deploymentException.InnerException; } Assert.IsNotNull(ex); Assert.AreEqual("Expected exception", ex.Message); Assert.IsTrue(ex.StackTrace.Trim().StartsWith( "at Apache.Ignite.Core.Tests.Services.ServicesTest.TestIgniteServiceSerializable.Init")); var failedCfgs = deploymentException.FailedConfigurations; Assert.IsNotNull(failedCfgs); Assert.AreEqual(1, failedCfgs.Count); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Tests exception in Execute. /// </summary> [Test] public void TestExecuteException() { var svc = new TestIgniteServiceSerializable { ThrowExecute = true }; Services.DeployMultiple(SvcName, svc, Grids.Length, 1); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); // Execution failed, but service exists. Assert.IsNotNull(svc0); Assert.IsFalse(svc0.Executed); } /// <summary> /// Tests exception in Cancel. /// </summary> [Test] public void TestCancelException() { var svc = new TestIgniteServiceSerializable { ThrowCancel = true }; Services.DeployMultiple(SvcName, svc, 2, 1); CheckServiceStarted(Grid1); Services.CancelAll(); // Cancellation failed, but service is removed. AssertNoService(); } /// <summary> /// Tests exception in binarizable implementation. /// </summary> [Test] public void TestMarshalExceptionOnRead() { var svc = new TestIgniteServiceBinarizableErr(); var ex = Assert.Throws<ServiceDeploymentException>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.IsNotNull(ex.InnerException); Assert.AreEqual("Expected exception", ex.InnerException.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Tests exception in binarizable implementation. /// </summary> [Test] public void TestMarshalExceptionOnWrite() { var svc = new TestIgniteServiceBinarizableErr {ThrowOnWrite = true}; var ex = Assert.Throws<Exception>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.AreEqual("Expected exception", ex.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Tests Java service invocation. /// </summary> [Test] public void TestCallJavaService() { // Deploy Java service const string javaSvcName = "javaService"; DeployJavaService(javaSvcName); // Verify decriptor var descriptor = Services.GetServiceDescriptors().Single(x => x.Name == javaSvcName); Assert.AreEqual(javaSvcName, descriptor.Name); var svc = Services.GetServiceProxy<IJavaService>(javaSvcName, false); var binSvc = Services.WithKeepBinary().WithServerKeepBinary() .GetServiceProxy<IJavaService>(javaSvcName, false); // Basics Assert.IsTrue(svc.isInitialized()); Assert.IsTrue(TestUtils.WaitForCondition(() => svc.isExecuted(), 500)); Assert.IsFalse(svc.isCancelled()); // Primitives Assert.AreEqual(4, svc.test((byte) 3)); Assert.AreEqual(5, svc.test((short) 4)); Assert.AreEqual(6, svc.test(5)); Assert.AreEqual(6, svc.test((long) 5)); Assert.AreEqual(3.8f, svc.test(2.3f)); Assert.AreEqual(5.8, svc.test(3.3)); Assert.IsFalse(svc.test(true)); Assert.AreEqual('b', svc.test('a')); Assert.AreEqual("Foo!", svc.test("Foo")); // Nullables (Java wrapper types) Assert.AreEqual(4, svc.testWrapper(3)); Assert.AreEqual(5, svc.testWrapper((short?) 4)); Assert.AreEqual(6, svc.testWrapper((int?)5)); Assert.AreEqual(6, svc.testWrapper((long?) 5)); Assert.AreEqual(3.8f, svc.testWrapper(2.3f)); Assert.AreEqual(5.8, svc.testWrapper(3.3)); Assert.AreEqual(false, svc.testWrapper(true)); Assert.AreEqual('b', svc.testWrapper('a')); // Arrays Assert.AreEqual(new byte[] {2, 3, 4}, svc.testArray(new byte[] {1, 2, 3})); Assert.AreEqual(new short[] {2, 3, 4}, svc.testArray(new short[] {1, 2, 3})); Assert.AreEqual(new[] {2, 3, 4}, svc.testArray(new[] {1, 2, 3})); Assert.AreEqual(new long[] {2, 3, 4}, svc.testArray(new long[] {1, 2, 3})); Assert.AreEqual(new float[] {2, 3, 4}, svc.testArray(new float[] {1, 2, 3})); Assert.AreEqual(new double[] {2, 3, 4}, svc.testArray(new double[] {1, 2, 3})); Assert.AreEqual(new[] {"a1", "b1"}, svc.testArray(new [] {"a", "b"})); Assert.AreEqual(new[] {'c', 'd'}, svc.testArray(new[] {'b', 'c'})); Assert.AreEqual(new[] {false, true, false}, svc.testArray(new[] {true, false, true})); // Nulls Assert.AreEqual(9, svc.testNull(8)); Assert.IsNull(svc.testNull(null)); // params / varargs Assert.AreEqual(5, svc.testParams(1, 2, 3, 4, "5")); Assert.AreEqual(0, svc.testParams()); // Overloads Assert.AreEqual(3, svc.test(2, "1")); Assert.AreEqual(3, svc.test("1", 2)); // Binary Assert.AreEqual(7, svc.testBinarizable(new PlatformComputeBinarizable {Field = 6}).Field); // Binary collections var arr = new [] {10, 11, 12}.Select(x => new PlatformComputeBinarizable {Field = x}).ToArray<object>(); Assert.AreEqual(new[] {11, 12, 13}, svc.testBinarizableCollection(arr) .OfType<PlatformComputeBinarizable>().Select(x => x.Field).ToArray()); Assert.AreEqual(new[] {11, 12, 13}, svc.testBinarizableArray(arr).OfType<PlatformComputeBinarizable>().Select(x => x.Field).ToArray()); // Binary object Assert.AreEqual(15, binSvc.testBinaryObject( Grid1.GetBinary().ToBinary<IBinaryObject>(new PlatformComputeBinarizable {Field = 6})) .GetField<int>("Field")); Services.Cancel(javaSvcName); } /// <summary> /// Tests Java service invocation with dynamic proxy. /// </summary> [Test] public void TestCallJavaServiceDynamicProxy() { const string javaSvcName = "javaService"; DeployJavaService(javaSvcName); var svc = Grid1.GetServices().GetDynamicServiceProxy(javaSvcName, true); // Basics Assert.IsTrue(svc.isInitialized()); Assert.IsTrue(TestUtils.WaitForCondition(() => svc.isExecuted(), 500)); Assert.IsFalse(svc.isCancelled()); // Primitives Assert.AreEqual(4, svc.test((byte)3)); Assert.AreEqual(5, svc.test((short)4)); Assert.AreEqual(6, svc.test(5)); Assert.AreEqual(6, svc.test((long)5)); Assert.AreEqual(3.8f, svc.test(2.3f)); Assert.AreEqual(5.8, svc.test(3.3)); Assert.IsFalse(svc.test(true)); Assert.AreEqual('b', svc.test('a')); Assert.AreEqual("Foo!", svc.test("Foo")); // Nullables (Java wrapper types) Assert.AreEqual(4, svc.testWrapper(3)); Assert.AreEqual(5, svc.testWrapper((short?)4)); Assert.AreEqual(6, svc.testWrapper((int?)5)); Assert.AreEqual(6, svc.testWrapper((long?)5)); Assert.AreEqual(3.8f, svc.testWrapper(2.3f)); Assert.AreEqual(5.8, svc.testWrapper(3.3)); Assert.AreEqual(false, svc.testWrapper(true)); Assert.AreEqual('b', svc.testWrapper('a')); // Arrays Assert.AreEqual(new byte[] { 2, 3, 4 }, svc.testArray(new byte[] { 1, 2, 3 })); Assert.AreEqual(new short[] { 2, 3, 4 }, svc.testArray(new short[] { 1, 2, 3 })); Assert.AreEqual(new[] { 2, 3, 4 }, svc.testArray(new[] { 1, 2, 3 })); Assert.AreEqual(new long[] { 2, 3, 4 }, svc.testArray(new long[] { 1, 2, 3 })); Assert.AreEqual(new float[] { 2, 3, 4 }, svc.testArray(new float[] { 1, 2, 3 })); Assert.AreEqual(new double[] { 2, 3, 4 }, svc.testArray(new double[] { 1, 2, 3 })); Assert.AreEqual(new[] { "a1", "b1" }, svc.testArray(new[] { "a", "b" })); Assert.AreEqual(new[] { 'c', 'd' }, svc.testArray(new[] { 'b', 'c' })); Assert.AreEqual(new[] { false, true, false }, svc.testArray(new[] { true, false, true })); // Nulls Assert.AreEqual(9, svc.testNull(8)); Assert.IsNull(svc.testNull(null)); // Overloads Assert.AreEqual(3, svc.test(2, "1")); Assert.AreEqual(3, svc.test("1", 2)); // Binary Assert.AreEqual(7, svc.testBinarizable(new PlatformComputeBinarizable { Field = 6 }).Field); // Binary object var binSvc = Services.WithKeepBinary().WithServerKeepBinary().GetDynamicServiceProxy(javaSvcName); Assert.AreEqual(15, binSvc.testBinaryObject( Grid1.GetBinary().ToBinary<IBinaryObject>(new PlatformComputeBinarizable { Field = 6 })) .GetField<int>("Field")); } /// <summary> /// Deploys the java service. /// </summary> private void DeployJavaService(string javaSvcName) { Grid1.GetCompute() .ExecuteJavaTask<object>("org.apache.ignite.platform.PlatformDeployServiceTask", javaSvcName); TestUtils.WaitForCondition(() => Services.GetServiceDescriptors().Any(x => x.Name == javaSvcName), 1000); } /// <summary> /// Tests the footer setting. /// </summary> [Test] public void TestFooterSetting() { foreach (var grid in Grids) { Assert.AreEqual(CompactFooter, ((Impl.Ignite) grid).Marshaller.CompactFooter); Assert.AreEqual(CompactFooter, grid.GetConfiguration().BinaryConfiguration.CompactFooter); } } /// <summary> /// Starts the grids. /// </summary> private void StartGrids() { if (Grid1 != null) return; Grid1 = Ignition.Start(GetConfiguration("Config\\Compute\\compute-grid1.xml")); Grid2 = Ignition.Start(GetConfiguration("Config\\Compute\\compute-grid2.xml")); Grid3 = Ignition.Start(GetConfiguration("Config\\Compute\\compute-grid3.xml")); Grids = new[] { Grid1, Grid2, Grid3 }; } /// <summary> /// Stops the grids. /// </summary> private void StopGrids() { Grid1 = Grid2 = Grid3 = null; Grids = null; Ignition.StopAll(true); } /// <summary> /// Checks that service has started on specified grid. /// </summary> private static void CheckServiceStarted(IIgnite grid, int count = 1, string svcName = SvcName) { Func<ICollection<TestIgniteServiceSerializable>> getServices = () => grid.GetServices().GetServices<TestIgniteServiceSerializable>(svcName); Assert.IsTrue(TestUtils.WaitForCondition(() => count == getServices().Count, 5000)); var svc = getServices().First(); Assert.IsNotNull(svc); Assert.IsTrue(svc.Initialized); Thread.Sleep(100); // Service runs in a separate thread, wait for it to execute. Assert.IsTrue(svc.Executed); Assert.IsFalse(svc.Cancelled); Assert.AreEqual(grid.GetCluster().GetLocalNode().Id, svc.NodeId); } /// <summary> /// Gets the Ignite configuration. /// </summary> private IgniteConfiguration GetConfiguration(string springConfigUrl) { #if !NETCOREAPP2_0 if (!CompactFooter) { springConfigUrl = Compute.ComputeApiTestFullFooter.ReplaceFooterSetting(springConfigUrl); } #endif return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = springConfigUrl, BinaryConfiguration = new BinaryConfiguration( typeof (TestIgniteServiceBinarizable), typeof (TestIgniteServiceBinarizableErr), typeof (PlatformComputeBinarizable), typeof (BinarizableObject)) { NameMapper = BinaryBasicNameMapper.SimpleNameInstance } }; } /// <summary> /// Asserts that there is no service on any grid with given name. /// </summary> /// <param name="name">The name.</param> private void AssertNoService(string name = SvcName) { foreach (var grid in Grids) Assert.IsTrue( // ReSharper disable once AccessToForEachVariableInClosure TestUtils.WaitForCondition(() => grid.GetServices() .GetService<ITestIgniteService>(name) == null, 5000)); } /// <summary> /// Gets the services. /// </summary> protected virtual IServices Services { get { return Grid1.GetServices(); } } /// <summary> /// Gets a value indicating whether compact footers should be used. /// </summary> protected virtual bool CompactFooter { get { return true; } } /// <summary> /// Makes Service1-{i} names for services. /// </summary> private static string MakeServiceName(int i) { // Please note that CheckContext() validates Name.StartsWith(SvcName). return string.Format("{0}-{1}", SvcName, i); } /// <summary> /// Test service interface for proxying. /// </summary> public interface ITestIgniteService { int TestProperty { get; set; } /** */ bool Initialized { get; } /** */ bool Cancelled { get; } /** */ bool Executed { get; } /** */ Guid NodeId { get; } /** */ string LastCallContextName { get; } /** */ object Method(object arg); /** */ object ErrMethod(object arg); } /// <summary> /// Test service interface for proxy usage. /// Has some of the original interface members with different signatures. /// </summary> public interface ITestIgniteServiceProxyInterface { /** */ Guid NodeId { get; } /** */ object TestProperty { get; set; } /** */ int Method(int arg); } #pragma warning disable 649 /// <summary> /// Test serializable service. /// </summary> [Serializable] private class TestIgniteServiceSerializable : IService, ITestIgniteService { /** */ [InstanceResource] private IIgnite _grid; /** <inheritdoc /> */ public int TestProperty { get; set; } /** <inheritdoc /> */ public bool Initialized { get; private set; } /** <inheritdoc /> */ public bool Cancelled { get; private set; } /** <inheritdoc /> */ public bool Executed { get; private set; } /** <inheritdoc /> */ public Guid NodeId { // ReSharper disable once InconsistentlySynchronizedField get { return _grid.GetCluster().GetLocalNode().Id; } } /** <inheritdoc /> */ public string LastCallContextName { get; private set; } /** */ public bool ThrowInit { get; set; } /** */ public bool ThrowExecute { get; set; } /** */ public bool ThrowCancel { get; set; } /** */ public object Method(object arg) { return arg; } /** */ public object ErrMethod(object arg) { throw new ArgumentNullException("arg", "ExpectedException"); } /** <inheritdoc /> */ public void Init(IServiceContext context) { lock (this) { if (ThrowInit) throw new Exception("Expected exception"); CheckContext(context); Assert.IsFalse(context.IsCancelled); Initialized = true; } } /** <inheritdoc /> */ public void Execute(IServiceContext context) { lock (this) { if (ThrowExecute) throw new Exception("Expected exception"); CheckContext(context); Assert.IsFalse(context.IsCancelled); Assert.IsTrue(Initialized); Assert.IsFalse(Cancelled); Executed = true; } } /** <inheritdoc /> */ public void Cancel(IServiceContext context) { lock (this) { if (ThrowCancel) throw new Exception("Expected exception"); CheckContext(context); Assert.IsTrue(context.IsCancelled); Cancelled = true; } } /// <summary> /// Checks the service context. /// </summary> private void CheckContext(IServiceContext context) { LastCallContextName = context.Name; if (context.AffinityKey != null && !(context.AffinityKey is int)) { var binaryObj = context.AffinityKey as IBinaryObject; var key = binaryObj != null ? binaryObj.Deserialize<BinarizableObject>() : (BinarizableObject) context.AffinityKey; Assert.AreEqual(AffKey, key.Val); } Assert.IsNotNull(_grid); Assert.IsTrue(context.Name.StartsWith(SvcName)); Assert.AreNotEqual(Guid.Empty, context.ExecutionId); } } /// <summary> /// Test binary service. /// </summary> private class TestIgniteServiceBinarizable : TestIgniteServiceSerializable, IBinarizable { /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.WriteInt("TestProp", TestProperty); writer.WriteBoolean("ThrowInit", ThrowInit); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { ThrowInit = reader.ReadBoolean("ThrowInit"); TestProperty = reader.ReadInt("TestProp"); } } /// <summary> /// Test binary service with exceptions in marshalling. /// </summary> private class TestIgniteServiceBinarizableErr : TestIgniteServiceSerializable, IBinarizable { /** */ public bool ThrowOnWrite { get; set; } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.WriteInt("TestProp", TestProperty); if (ThrowOnWrite) throw new Exception("Expected exception"); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { TestProperty = reader.ReadInt("TestProp"); throw new Exception("Expected exception"); } } /// <summary> /// Test node filter. /// </summary> [Serializable] private class NodeFilter : IClusterNodeFilter { /// <summary> /// Gets or sets the node identifier. /// </summary> public Guid NodeId { get; set; } /** <inheritdoc /> */ public bool Invoke(IClusterNode node) { return node.Id == NodeId; } } /// <summary> /// Binary object. /// </summary> private class BinarizableObject { public int Val { get; set; } } /// <summary> /// Java service proxy interface. /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] public interface IJavaService { /** */ bool isCancelled(); /** */ bool isInitialized(); /** */ bool isExecuted(); /** */ byte test(byte x); /** */ short test(short x); /** */ int test(int x); /** */ long test(long x); /** */ float test(float x); /** */ double test(double x); /** */ char test(char x); /** */ string test(string x); /** */ bool test(bool x); /** */ byte? testWrapper(byte? x); /** */ short? testWrapper(short? x); /** */ int? testWrapper(int? x); /** */ long? testWrapper(long? x); /** */ float? testWrapper(float? x); /** */ double? testWrapper(double? x); /** */ char? testWrapper(char? x); /** */ bool? testWrapper(bool? x); /** */ byte[] testArray(byte[] x); /** */ short[] testArray(short[] x); /** */ int[] testArray(int[] x); /** */ long[] testArray(long[] x); /** */ float[] testArray(float[] x); /** */ double[] testArray(double[] x); /** */ char[] testArray(char[] x); /** */ string[] testArray(string[] x); /** */ bool[] testArray(bool[] x); /** */ int test(int x, string y); /** */ int test(string x, int y); /** */ int? testNull(int? x); /** */ int testParams(params object[] args); /** */ PlatformComputeBinarizable testBinarizable(PlatformComputeBinarizable x); /** */ object[] testBinarizableArray(object[] x); /** */ ICollection testBinarizableCollection(ICollection x); /** */ IBinaryObject testBinaryObject(IBinaryObject x); } /// <summary> /// Interop class. /// </summary> public class PlatformComputeBinarizable { /** */ public int Field { get; set; } } } }
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here * xxxx-xx-xx, author, fix bug about xxx */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using rDSN.Tron.Contract; using rDSN.Tron.LanguageProvider; using rDSN.Tron.Utility; namespace rDSN.Tron.Compiler { // // build compilable query // all external values must be converted into constant // all external functions and types must be referenced with full namespace // // public class CodeGenerator { private CodeBuilder _builder = new CodeBuilder(); private QueryContext[] _contexts; private string _appClassName; private Dictionary<Type, string> _rewrittenTypes = new Dictionary<Type, string>(); public ulong AppId { get; } = RandomGenerator.Random64(); public string BuildRdsn(Type service, QueryContext[] contexts) { //_stages = stages; _contexts = contexts; _appClassName = service.Name; //BuildInputOutputValueTypes(); BuildHeaderRdsn(service.Namespace); BuildRewrittenTypes(); _builder.AppendLine("public class " + _appClassName + "Server_impl :" + _appClassName + "Server"); _builder.BeginBlock(); BuildServiceClientsRdsn(); //thrift or protobuf BuildServiceCallsRdsn(_appClassName); foreach (var c in contexts) //never change BuildQueryRdsn(c); //always thrift BuildServer(_appClassName, ServiceContract.GetServiceCalls(service)); _builder.EndBlock(); BuildMain(); BuildFooter(); return _builder.ToString(); } public void BuildMain() { _builder.AppendLine("class Program"); _builder.BeginBlock(); _builder.AppendLine("static void Main(string[] args)"); _builder.BeginBlock(); _builder.AppendLine(_appClassName + "Helper.InitCodes();"); _builder.AppendLine("ServiceApp.RegisterApp<" + _appClassName + "ServerApp>(\"server\");"); _builder.AppendLine("ServiceApp.RegisterApp<" + _appClassName + "ClientApp>(\"client\");"); _builder.AppendLine("string[] args2 = (new string[] { \"" + _appClassName + "\" }).Union(args).ToArray();"); _builder.AppendLine("Native.dsn_run(args2.Length, args2, true);"); _builder.EndBlock(); _builder.EndBlock(); } public string Build(string className, QueryContext[] contexts) { //_stages = stages; _contexts = contexts; _appClassName = className; //BuildInputOutputValueTypes(); BuildRewrittenTypes(); BuildHeader(); _builder.AppendLine("public class " + _appClassName + " : ServiceMesh"); _builder.BeginBlock(); //BuildConstructor(); BuildServiceClients(); BuildServiceCalls(); foreach (var c in contexts) BuildQuery(c); _builder.EndBlock(); BuildFooter(); return _builder.ToString(); } private void BuildConstructor() { _builder.AppendLine("public " + _appClassName + "()"); _builder.BeginBlock(); _builder.EndBlock(); _builder.AppendLine(); } //private void BuildInputOutputValueTypes() //{ // if (_primaryContext.OutputType.IsSymbols()) // { // throw new Exception("we are not support ISymbolCollection<> output right now, you can use an Gather method to merge it into a single ISymbol<>"); // } // Trace.Assert(_primaryContext.InputType.IsSymbol() && _primaryContext.InputType.IsGenericType); // Trace.Assert(_primaryContext.OutputType.IsSymbol() && _primaryContext.OutputType.IsGenericType); // _inputValueType = _primaryContext.InputType.GetGenericArguments()[0]; // _outputValueType = _primaryContext.OutputType.GetGenericArguments()[0]; //} private void BuildServiceClientsRdsn() { foreach (var s in _contexts.SelectMany(c => c.Services).DistinctBy(s => s.Key.Member.Name)) { SpecProviderManager.Instance().GetProvider(s.Value.Spec.SType).GenerateClientDeclaration(_builder, s.Key, s.Value); } } private void BuildServiceClients() { } private void BuildServiceCallsRdsn(string serviceName) { var calls = new HashSet<string>(); foreach (var s in _contexts.SelectMany(c => c.ServiceCalls)) { Trace.Assert(s.Key.Object != null && s.Key.Object.NodeType == ExpressionType.MemberAccess); var callName = s.Key.Method.Name; var respTypeName = s.Key.Type.GetCompilableTypeName(_rewrittenTypes); var reqTypeName = s.Key.Arguments[0].Type.GetCompilableTypeName(_rewrittenTypes); var call = "Call_" + s.Value.PlainTypeName() + "_" + callName; if (!calls.Add(call + ":" + reqTypeName)) continue; _builder.AppendLine("private " + respTypeName + " " + call + "( " + reqTypeName + " req)"); _builder.BeginBlock(); var provider = SpecProviderManager.Instance().GetProvider(s.Value.Spec.SType); provider.GenerateClientCall(_builder, s.Key, s.Value, _rewrittenTypes); _builder.EndBlock(); _builder.AppendLine(); } } private void BuildServiceCalls() { } private void BuildQueryRdsn(QueryContext c) { _builder.AppendLine("public " + c.OutputType.GetCompilableTypeName(_rewrittenTypes) + " " + c.Name + "(" + c.InputType.GetCompilableTypeName(_rewrittenTypes) + " request)"); _builder.AppendLine("{"); _builder++; _builder.AppendLine("Console.Write(\".\");"); // local vars foreach (var s in c.TempSymbolsByAlias) { _builder.AppendLine(s.Value.Type.GetCompilableTypeName(_rewrittenTypes) + " " + s.Key + ";"); } if (c.TempSymbolsByAlias.Count > 0) _builder.AppendLine(); // final query var codeBuilder = new ExpressionToCode(c.RootExpression, c); var code = codeBuilder.GenCode(_builder.Indent); _builder.AppendLine(code + ";"); _builder--; _builder.AppendLine("}"); _builder.AppendLine(); } private void BuildServer(string serviceName, IEnumerable<MethodInfo> methods) { foreach (var m in methods) { var respType = m.ReturnType.GetGenericArguments()[0].FullName.GetCompilableTypeName(); _builder.AppendLine("protected override void On" + m.Name + "(" + m.GetParameters()[0].ParameterType.GetGenericArguments()[0].FullName.GetCompilableTypeName() + " request, RpcReplier<" + respType + "> replier)"); _builder.BeginBlock(); _builder.AppendLine("replier.Reply(" + m.Name + "(new IValue<" + m.GetParameters()[0].ParameterType.GetGenericArguments()[0].FullName.GetCompilableTypeName() + ">(request)).Value());"); _builder.EndBlock(); _builder.AppendLine(); } } private void BuildQuery(QueryContext c) { _builder.AppendLine("public " + c.OutputType.GetCompilableTypeName(_rewrittenTypes) + " " + c.Name + "(" + c.InputType.GetCompilableTypeName(_rewrittenTypes) + " request)"); _builder.AppendLine("{"); _builder++; _builder.AppendLine("Console.Write(\".\");"); // local vars foreach (var s in c.TempSymbolsByAlias) { _builder.AppendLine(s.Value.Type.GetCompilableTypeName(_rewrittenTypes) + " " + s.Key + ";"); } if (c.TempSymbolsByAlias.Count > 0) _builder.AppendLine(); // final query var codeBuilder = new ExpressionToCode(c.RootExpression, c); var code = codeBuilder.GenCode(_builder.Indent); _builder.AppendLine(code + ";"); _builder--; _builder.AppendLine("}"); _builder.AppendLine(); } private string VerboseStringArray(IEnumerable<string> parameters) { var ps = parameters.Aggregate("", (current, s) => current + ("@\"" + s + "\",")); if (ps.Length > 0) { ps = ps.Substring(0, ps.Length - 1); } return ps; } private void BuildRewrittenTypes() { /* foreach (var t in _contexts.Select(c => c.OutputType.GetGenericArguments()[0]).Where(t => !_rewrittenTypes.ContainsKey(t))) { _rewrittenTypes.Add(t, t.Name); } */ foreach (var t in _contexts.SelectMany(c => c.RewrittenTypes.Where(t => !_rewrittenTypes.ContainsKey(t.Key)))) { _rewrittenTypes.Add(t.Key, t.Value); } foreach (var c in _contexts) { c.RewrittenTypes = _rewrittenTypes; } foreach (var typeMap in _rewrittenTypes) { _builder.AppendLine("public class " + typeMap.Value); _builder.AppendLine("{"); _builder++; foreach (var property in typeMap.Key.GetProperties()) { _builder.AppendLine("public " + property.PropertyType.GetCompilableTypeName(_rewrittenTypes) + " " + property.Name + " { get; set; }"); } _builder.AppendLine("public " + typeMap.Value + " () {}"); _builder--; _builder.AppendLine("}"); _builder.AppendLine(); } } private void BuildHeaderRdsn(string serviceNamespce) { _builder.AppendLine("/* AUTO GENERATED BY Tron AT " + DateTime.Now.ToLocalTime() + " */"); var namespaces = new HashSet<string> { "System", "System.IO", "dsn.dev.csharp", serviceNamespce, "System.Linq", "System.Text", "System.Linq.Expressions", "System.Reflection", "System.Diagnostics", "System.Net", "System.Threading", "rDSN.Tron.Contract", "rDSN.Tron.Runtime", "rDSN.Tron.App", "BondNetlibTransport", "BondTransport" }; //namespaces.Add("rDSN.Tron.Utility"); //namespaces.Add("rDSN.Tron.Compiler"); foreach (var nm in _contexts.SelectMany(c => c.Methods).Select(mi => mi.DeclaringType.Namespace).Distinct().Except(namespaces)) { namespaces.Add(nm); } foreach (var np in namespaces) { _builder.AppendLine("using " + np + ";"); } _builder.AppendLine(); _builder.AppendLine("namespace rDSN.Tron.App"); _builder.AppendLine("{"); _builder++; } private void BuildHeader() { _builder.AppendLine("/* AUTO GENERATED BY Tron AT " + DateTime.Now.ToLocalTime() + " */"); var namespaces = new HashSet<string> { "System", "System.IO", "System.Collections.Generic", "System.Linq", "System.Text", "System.Linq.Expressions", "System.Reflection", "System.Diagnostics", "System.Net", "System.Threading", "rDSN.Tron.Utility", "rDSN.Tron.Contract", "rDSN.Tron.Runtime" }; //namespaces.Add("rDSN.Tron.Compiler"); foreach (var nm in _contexts.SelectMany(c => c.Methods).Select(mi => mi.DeclaringType.Namespace).Distinct().Except(namespaces)) { namespaces.Add(nm); } foreach (var np in namespaces) { _builder.AppendLine("using " + np + ";"); } _builder.AppendLine(); _builder.AppendLine("namespace rDSN.Tron.App"); _builder.AppendLine("{"); _builder++; } private void BuildFooter() { _builder--; _builder.AppendLine("} // end namespace"); _builder.AppendLine(); } } }
#if FEATURE_CONCURRENTMERGESCHEDULER using System; using System.Diagnostics; using System.Threading; using Lucene.Net.Documents; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index { using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using NUnit.Framework; using System.IO; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using Lucene41PostingsFormat = Lucene.Net.Codecs.Lucene41.Lucene41PostingsFormat; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using StringField = StringField; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; using Attributes; [TestFixture] public class TestConcurrentMergeScheduler : LuceneTestCase { private class FailOnlyOnFlush : MockDirectoryWrapper.Failure { private readonly TestConcurrentMergeScheduler OuterInstance; public FailOnlyOnFlush(TestConcurrentMergeScheduler outerInstance) { this.OuterInstance = outerInstance; } new internal bool DoFail; internal bool HitExc; public override void SetDoFail() { this.DoFail = true; HitExc = false; } public override void ClearDoFail() { this.DoFail = false; } public override void Eval(MockDirectoryWrapper dir) { if (DoFail && TestThread()) { // LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)] // to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods. bool isDoFlush = Util.StackTraceHelper.DoesStackTraceContainMethod("Flush"); bool isClose = Util.StackTraceHelper.DoesStackTraceContainMethod("Close") || Util.StackTraceHelper.DoesStackTraceContainMethod("Dispose"); if (isDoFlush && !isClose && Random().NextBoolean()) { HitExc = true; throw new IOException(Thread.CurrentThread.Name + ": now failing during flush"); } } } } // Make sure running BG merges still work fine even when // we are hitting exceptions during flushing. [Test] public virtual void TestFlushExceptions() { MockDirectoryWrapper directory = NewMockDirectory(); FailOnlyOnFlush failure = new FailOnlyOnFlush(this); directory.FailOn(failure); IndexWriter writer = new IndexWriter(directory, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2)); Document doc = new Document(); Field idField = NewStringField("id", "", Field.Store.YES); doc.Add(idField); int extraCount = 0; for (int i = 0; i < 10; i++) { if (VERBOSE) { Console.WriteLine("TEST: iter=" + i); } for (int j = 0; j < 20; j++) { idField.SetStringValue(Convert.ToString(i * 20 + j)); writer.AddDocument(doc); } // must cycle here because sometimes the merge flushes // the doc we just added and so there's nothing to // flush, and we don't hit the exception while (true) { writer.AddDocument(doc); failure.SetDoFail(); try { writer.Flush(true, true); if (failure.HitExc) { Assert.Fail("failed to hit IOException"); } extraCount++; } catch (IOException ioe) { if (VERBOSE) { Console.WriteLine(ioe.StackTrace); } failure.ClearDoFail(); break; } } Assert.AreEqual(20 * (i + 1) + extraCount, writer.NumDocs); } writer.Dispose(); IndexReader reader = DirectoryReader.Open(directory); Assert.AreEqual(200 + extraCount, reader.NumDocs); reader.Dispose(); directory.Dispose(); } // Test that deletes committed after a merge started and // before it finishes, are correctly merged back: [Test] public virtual void TestDeleteMerging() { Directory directory = NewDirectory(); LogDocMergePolicy mp = new LogDocMergePolicy(); // Force degenerate merging so we can get a mix of // merging of segments with and without deletes at the // start: mp.MinMergeDocs = 1000; IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(mp)); Document doc = new Document(); Field idField = NewStringField("id", "", Field.Store.YES); doc.Add(idField); for (int i = 0; i < 10; i++) { if (VERBOSE) { Console.WriteLine("\nTEST: cycle"); } for (int j = 0; j < 100; j++) { idField.SetStringValue(Convert.ToString(i * 100 + j)); writer.AddDocument(doc); } int delID = i; while (delID < 100 * (1 + i)) { if (VERBOSE) { Console.WriteLine("TEST: del " + delID); } writer.DeleteDocuments(new Term("id", "" + delID)); delID += 10; } writer.Commit(); } writer.Dispose(); IndexReader reader = DirectoryReader.Open(directory); // Verify that we did not lose any deletes... Assert.AreEqual(450, reader.NumDocs); reader.Dispose(); directory.Dispose(); } [Test, LongRunningTest] public virtual void TestNoExtraFiles() { Directory directory = NewDirectory(); IndexWriter writer = new IndexWriter(directory, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2)); for (int iter = 0; iter < 7; iter++) { if (VERBOSE) { Console.WriteLine("TEST: iter=" + iter); } for (int j = 0; j < 21; j++) { Document doc = new Document(); doc.Add(NewTextField("content", "a b c", Field.Store.NO)); writer.AddDocument(doc); } writer.Dispose(); TestIndexWriter.AssertNoUnreferencedFiles(directory, "testNoExtraFiles"); // Reopen writer = new IndexWriter(directory, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.APPEND).SetMaxBufferedDocs(2)); } writer.Dispose(); directory.Dispose(); } [Test, LongRunningTest] public virtual void TestNoWaitClose() { Directory directory = NewDirectory(); Document doc = new Document(); Field idField = NewStringField("id", "", Field.Store.YES); doc.Add(idField); IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetMergePolicy(NewLogMergePolicy(100))); for (int iter = 0; iter < 10; iter++) { for (int j = 0; j < 201; j++) { idField.SetStringValue(Convert.ToString(iter * 201 + j)); writer.AddDocument(doc); } int delID = iter * 201; for (int j = 0; j < 20; j++) { writer.DeleteDocuments(new Term("id", Convert.ToString(delID))); delID += 5; } // Force a bunch of merge threads to kick off so we // stress out aborting them on close: ((LogMergePolicy)writer.Config.MergePolicy).MergeFactor = 3; writer.AddDocument(doc); writer.Commit(); writer.Dispose(false); IndexReader reader = DirectoryReader.Open(directory); Assert.AreEqual((1 + iter) * 182, reader.NumDocs); reader.Dispose(); // Reopen writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.APPEND).SetMergePolicy(NewLogMergePolicy(100))); } writer.Dispose(); directory.Dispose(); } // LUCENE-4544 [Test] public virtual void TestMaxMergeCount() { Directory dir = NewDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); int maxMergeCount = TestUtil.NextInt(Random(), 1, 5); int maxMergeThreads = TestUtil.NextInt(Random(), 1, maxMergeCount); CountdownEvent enoughMergesWaiting = new CountdownEvent(maxMergeCount); AtomicInt32 runningMergeCount = new AtomicInt32(0); AtomicBoolean failed = new AtomicBoolean(); if (VERBOSE) { Console.WriteLine("TEST: maxMergeCount=" + maxMergeCount + " maxMergeThreads=" + maxMergeThreads); } ConcurrentMergeScheduler cms = new ConcurrentMergeSchedulerAnonymousInnerClassHelper(this, maxMergeCount, enoughMergesWaiting, runningMergeCount, failed); cms.SetMaxMergesAndThreads(maxMergeCount, maxMergeThreads); iwc.SetMergeScheduler(cms); iwc.SetMaxBufferedDocs(2); TieredMergePolicy tmp = new TieredMergePolicy(); iwc.SetMergePolicy(tmp); tmp.MaxMergeAtOnce = 2; tmp.SegmentsPerTier = 2; IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.Add(NewField("field", "field", TextField.TYPE_NOT_STORED)); while (enoughMergesWaiting.CurrentCount != 0 && !failed.Get()) { for (int i = 0; i < 10; i++) { w.AddDocument(doc); } } w.Dispose(false); dir.Dispose(); } private class ConcurrentMergeSchedulerAnonymousInnerClassHelper : ConcurrentMergeScheduler { private readonly TestConcurrentMergeScheduler OuterInstance; private int maxMergeCount; private CountdownEvent EnoughMergesWaiting; private AtomicInt32 RunningMergeCount; private AtomicBoolean Failed; public ConcurrentMergeSchedulerAnonymousInnerClassHelper(TestConcurrentMergeScheduler outerInstance, int maxMergeCount, CountdownEvent enoughMergesWaiting, AtomicInt32 runningMergeCount, AtomicBoolean failed) { this.OuterInstance = outerInstance; this.maxMergeCount = maxMergeCount; this.EnoughMergesWaiting = enoughMergesWaiting; this.RunningMergeCount = runningMergeCount; this.Failed = failed; } protected override void DoMerge(MergePolicy.OneMerge merge) { try { // Stall all incoming merges until we see // maxMergeCount: int count = RunningMergeCount.IncrementAndGet(); try { Assert.IsTrue(count <= maxMergeCount, "count=" + count + " vs maxMergeCount=" + maxMergeCount); EnoughMergesWaiting.Signal(); // Stall this merge until we see exactly // maxMergeCount merges waiting while (true) { // wait for 10 milliseconds if (EnoughMergesWaiting.Wait(new TimeSpan(0, 0, 0, 0, 10)) || Failed.Get()) { break; } } // Then sleep a bit to give a chance for the bug // (too many pending merges) to appear: Thread.Sleep(20); base.DoMerge(merge); } finally { RunningMergeCount.DecrementAndGet(); } } catch (Exception /*t*/) { Failed.Set(true); m_writer.MergeFinish(merge); // LUCENENET specific - throwing an exception on a background thread causes the test // runner to crash on .NET Core 2.0. //throw new Exception(t.ToString(), t); } } } private class TrackingCMS : ConcurrentMergeScheduler { internal long TotMergedBytes; public TrackingCMS() { SetMaxMergesAndThreads(5, 5); } protected override void DoMerge(MergePolicy.OneMerge merge) { TotMergedBytes += merge.TotalBytesSize; base.DoMerge(merge); } } [Test, LongRunningTest] public virtual void TestTotalBytesSize() { Directory d = NewDirectory(); if (d is MockDirectoryWrapper) { ((MockDirectoryWrapper)d).Throttling = MockDirectoryWrapper.Throttling_e.NEVER; } IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); iwc.SetMaxBufferedDocs(5); iwc.SetMergeScheduler(new TrackingCMS()); if (TestUtil.GetPostingsFormat("id").Equals("SimpleText")) { // no iwc.SetCodec(TestUtil.AlwaysPostingsFormat(new Lucene41PostingsFormat())); } RandomIndexWriter w = new RandomIndexWriter(Random(), d, iwc); for (int i = 0; i < 1000; i++) { Document doc = new Document(); doc.Add(new StringField("id", "" + i, Field.Store.NO)); w.AddDocument(doc); if (Random().NextBoolean()) { w.DeleteDocuments(new Term("id", "" + Random().Next(i + 1))); } } Assert.IsTrue(((TrackingCMS)w.w.Config.MergeScheduler).TotMergedBytes != 0); w.Dispose(); d.Dispose(); } } } #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 System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Runtime.CompilerServices; using AstUtils = System.Linq.Expressions.Utils; namespace System.Dynamic { /// <summary> /// Represents a set of binding restrictions on the <see cref="DynamicMetaObject"/> under which the dynamic binding is valid. /// </summary> [DebuggerTypeProxy(typeof(BindingRestrictionsProxy)), DebuggerDisplay("{DebugView}")] public abstract class BindingRestrictions { /// <summary> /// Represents an empty set of binding restrictions. This field is read-only. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly BindingRestrictions Empty = new CustomRestriction(AstUtils.Constant(true)); private const int TypeRestrictionHash = 0b_0100_1001_0010_0100_1001_0010_0100_1001; private const int InstanceRestrictionHash = unchecked((int)0b_1001_0010_0100_1001_0010_0100_1001_0010); private const int CustomRestrictionHash = 0b_0010_0100_1001_0010_0100_1001_0010_0100; private BindingRestrictions() { } // Overridden by specialized subclasses internal abstract Expression GetExpression(); /// <summary> /// Merges the set of binding restrictions with the current binding restrictions. /// </summary> /// <param name="restrictions">The set of restrictions with which to merge the current binding restrictions.</param> /// <returns>The new set of binding restrictions.</returns> public BindingRestrictions Merge(BindingRestrictions restrictions) { ContractUtils.RequiresNotNull(restrictions, nameof(restrictions)); if (this == Empty) { return restrictions; } if (restrictions == Empty) { return this; } return new MergedRestriction(this, restrictions); } /// <summary> /// Creates the binding restriction that check the expression for runtime type identity. /// </summary> /// <param name="expression">The expression to test.</param> /// <param name="type">The exact type to test.</param> /// <returns>The new binding restrictions.</returns> public static BindingRestrictions GetTypeRestriction(Expression expression, Type type) { ContractUtils.RequiresNotNull(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); return new TypeRestriction(expression, type); } /// <summary> /// The method takes a DynamicMetaObject, and returns an instance restriction for testing null if the object /// holds a null value, otherwise returns a type restriction. /// </summary> internal static BindingRestrictions GetTypeRestriction(DynamicMetaObject obj) { Debug.Assert(obj != null); if (obj.Value == null && obj.HasValue) { return GetInstanceRestriction(obj.Expression, null); } else { return GetTypeRestriction(obj.Expression, obj.LimitType); } } /// <summary> /// Creates the binding restriction that checks the expression for object instance identity. /// </summary> /// <param name="expression">The expression to test.</param> /// <param name="instance">The exact object instance to test.</param> /// <returns>The new binding restrictions.</returns> public static BindingRestrictions GetInstanceRestriction(Expression expression, object instance) { ContractUtils.RequiresNotNull(expression, nameof(expression)); return new InstanceRestriction(expression, instance); } /// <summary> /// Creates the binding restriction that checks the expression for arbitrary immutable properties. /// </summary> /// <param name="expression">The expression expressing the restrictions.</param> /// <returns>The new binding restrictions.</returns> /// <remarks> /// By convention, the general restrictions created by this method must only test /// immutable object properties. /// </remarks> public static BindingRestrictions GetExpressionRestriction(Expression expression) { ContractUtils.RequiresNotNull(expression, nameof(expression)); ContractUtils.Requires(expression.Type == typeof(bool), nameof(expression)); return new CustomRestriction(expression); } /// <summary> /// Combines binding restrictions from the list of <see cref="DynamicMetaObject"/> instances into one set of restrictions. /// </summary> /// <param name="contributingObjects">The list of <see cref="DynamicMetaObject"/> instances from which to combine restrictions.</param> /// <returns>The new set of binding restrictions.</returns> public static BindingRestrictions Combine(IList<DynamicMetaObject> contributingObjects) { BindingRestrictions res = Empty; if (contributingObjects != null) { foreach (DynamicMetaObject mo in contributingObjects) { if (mo != null) { res = res.Merge(mo.Restrictions); } } } return res; } /// <summary> /// Builds a balanced tree of AndAlso nodes. /// We do this so the compiler won't stack overflow if we have many /// restrictions. /// </summary> private sealed class TestBuilder { private readonly HashSet<BindingRestrictions> _unique = new HashSet<BindingRestrictions>(); private readonly Stack<AndNode> _tests = new Stack<AndNode>(); private struct AndNode { internal int Depth; internal Expression Node; } internal void Append(BindingRestrictions restrictions) { if (_unique.Add(restrictions)) { Push(restrictions.GetExpression(), 0); } } internal Expression ToExpression() { Expression result = _tests.Pop().Node; while (_tests.Count > 0) { result = Expression.AndAlso(_tests.Pop().Node, result); } return result; } private void Push(Expression node, int depth) { while (_tests.Count > 0 && _tests.Peek().Depth == depth) { node = Expression.AndAlso(_tests.Pop().Node, node); depth++; } _tests.Push(new AndNode { Node = node, Depth = depth }); } } /// <summary> /// Creates the <see cref="Expression"/> representing the binding restrictions. /// </summary> /// <returns>The expression tree representing the restrictions.</returns> public Expression ToExpression() => GetExpression(); private sealed class MergedRestriction : BindingRestrictions { internal readonly BindingRestrictions Left; internal readonly BindingRestrictions Right; internal MergedRestriction(BindingRestrictions left, BindingRestrictions right) { Left = left; Right = right; } internal override Expression GetExpression() { // We could optimize this better, e.g. common subexpression elimination // But for now, it's good enough. var testBuilder = new TestBuilder(); // Visit the tree, left to right. // Use an explicit stack so we don't stack overflow. // // Left-most node is on top of the stack, so we always expand the // left most node each iteration. var stack = new Stack<BindingRestrictions>(); BindingRestrictions top = this; while (true) { var m = top as MergedRestriction; if (m != null) { stack.Push(m.Right); top = m.Left; } else { testBuilder.Append(top); if (stack.Count == 0) { return testBuilder.ToExpression(); } top = stack.Pop(); } } } } private sealed class CustomRestriction : BindingRestrictions { private readonly Expression _expression; internal CustomRestriction(Expression expression) { Debug.Assert(expression != null); _expression = expression; } public override bool Equals(object obj) { var other = obj as CustomRestriction; return other?._expression == _expression; } public override int GetHashCode() => CustomRestrictionHash ^ _expression.GetHashCode(); internal override Expression GetExpression() => _expression; } private sealed class TypeRestriction : BindingRestrictions { private readonly Expression _expression; private readonly Type _type; internal TypeRestriction(Expression parameter, Type type) { Debug.Assert(parameter != null); Debug.Assert(type != null); _expression = parameter; _type = type; } public override bool Equals(object obj) { var other = obj as TypeRestriction; return other?._expression == _expression && TypeUtils.AreEquivalent(other._type, _type); } public override int GetHashCode() => TypeRestrictionHash ^ _expression.GetHashCode() ^ _type.GetHashCode(); internal override Expression GetExpression() => Expression.TypeEqual(_expression, _type); } private sealed class InstanceRestriction : BindingRestrictions { private readonly Expression _expression; private readonly object _instance; internal InstanceRestriction(Expression parameter, object instance) { Debug.Assert(parameter != null); _expression = parameter; _instance = instance; } public override bool Equals(object obj) { var other = obj as InstanceRestriction; return other?._expression == _expression && other._instance == _instance; } public override int GetHashCode() => InstanceRestrictionHash ^ RuntimeHelpers.GetHashCode(_instance) ^ _expression.GetHashCode(); internal override Expression GetExpression() { if (_instance == null) { return Expression.Equal( Expression.Convert(_expression, typeof(object)), AstUtils.Null ); } ParameterExpression temp = Expression.Parameter(typeof(object), null); return Expression.Block( new TrueReadOnlyCollection<ParameterExpression>(temp), new TrueReadOnlyCollection<Expression>( #if ENABLEDYNAMICPROGRAMMING Expression.Assign( temp, Expression.Property( Expression.Constant(new WeakReference(_instance)), typeof(WeakReference).GetProperty("Target") ) ), #else Expression.Assign( temp, Expression.Constant(_instance, typeof(object)) ), #endif Expression.AndAlso( //check that WeakReference was not collected. Expression.NotEqual(temp, AstUtils.Null), Expression.Equal( Expression.Convert(_expression, typeof(object)), temp ) ) ) ); } } private string DebugView => ToExpression().ToString(); private sealed class BindingRestrictionsProxy { private readonly BindingRestrictions _node; public BindingRestrictionsProxy(BindingRestrictions node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool IsEmpty => _node == Empty; public Expression Test => _node.ToExpression(); public BindingRestrictions[] Restrictions { get { var restrictions = new List<BindingRestrictions>(); // Visit the tree, left to right // // Left-most node is on top of the stack, so we always expand the // left most node each iteration. var stack = new Stack<BindingRestrictions>(); BindingRestrictions top = _node; while (true) { var m = top as MergedRestriction; if (m != null) { stack.Push(m.Right); top = m.Left; } else { restrictions.Add(top); if (stack.Count == 0) { return restrictions.ToArray(); } top = stack.Pop(); } } } } // To prevent fxcop warning about this field public override string ToString() => _node.DebugView; } } }
/* * Copyright (c) 2020, Norsk Helsenett SF and contributors * See the file CONTRIBUTORS for details. * * This file is licensed under the MIT license * available at https://raw.githubusercontent.com/helsenorge/Helsenorge.Messaging/master/LICENSE */ using Helsenorge.Messaging.Abstractions; using Helsenorge.Messaging.Tests.Mocks; using Helsenorge.Registries; using Helsenorge.Registries.Configuration; using Helsenorge.Registries.Mocks; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using System.Xml.Linq; namespace Helsenorge.Messaging.Tests { [TestClass] public class BaseTest { //public const int MyHerId = 93238; ///public const int OhterHerId = 93252; public Guid CpaId = new Guid("49391409-e528-4919-b4a3-9ccdab72c8c1"); public const int DefaultOtherHerId = 93252; protected AddressRegistryMock AddressRegistry { get; private set; } protected CollaborationProtocolRegistryMock CollaborationRegistry { get; private set; } protected ILoggerFactory LoggerFactory { get; private set; } internal ILogger Logger { get; private set; } protected MessagingClient Client { get; set; } protected MockMessagingServer Server { get; set; } protected MessagingSettings Settings { get; set; } internal MockFactory MockFactory { get; set; } internal MockLoggerProvider MockLoggerProvider { get; set; } internal MockCertificateValidator CertificateValidator { get; set; } internal MockCertificateStore CertificateStore { get; set; } internal MockMessageProtection MessageProtection { get; set; } protected XDocument GenericMessage => new XDocument(new XElement("SomeDummyXmlUsedForTesting")); protected XDocument GenericResponse => new XDocument(new XElement("SomeDummyXmlResponseUsedForTesting")); protected XDocument SoapFault => XDocument.Load(File.OpenRead(TestFileUtility.GetFullPathToFile($"Files{Path.DirectorySeparatorChar}SoapFault.xml"))); [TestInitialize] public virtual void Setup() { SetupInternal(DefaultOtherHerId); } internal void SetupInternal(int otherHerId) { var addressRegistrySettings = new AddressRegistrySettings() { WcfConfiguration = new WcfConfiguration { UserName = "username", Password = "password", }, CachingInterval = TimeSpan.FromSeconds(5) }; var collaborationRegistrySettings = new CollaborationProtocolRegistrySettings() { WcfConfiguration = new WcfConfiguration { UserName = "username", Password = "password", }, CachingInterval = TimeSpan.FromSeconds(5) }; LoggerFactory = new LoggerFactory(); MockLoggerProvider = new MockLoggerProvider(null); LoggerFactory.AddProvider(MockLoggerProvider); Logger = LoggerFactory.CreateLogger<BaseTest>(); var distributedCache = DistributedCacheFactory.Create(); AddressRegistry = new AddressRegistryMock(addressRegistrySettings, distributedCache); AddressRegistry.SetupFindCommunicationPartyDetails(i => { var file = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"CommunicationDetails_{i}.xml")); return File.Exists(file) == false ? null : XElement.Load(file); }); AddressRegistry.SetupGetCertificateDetailsForEncryption(i => { var path = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"GetCertificateDetailsForEncryption_{i}.xml")); return File.Exists(path) == false ? null : XElement.Load(path); }); AddressRegistry.SetupGetCertificateDetailsForValidatingSignature(i => { var path = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"GetCertificateDetailsForValidatingSignature_{i}.xml")); return File.Exists(path) == false ? null : XElement.Load(path); }); CollaborationRegistry = new CollaborationProtocolRegistryMock(collaborationRegistrySettings, distributedCache, AddressRegistry); CollaborationRegistry.SetupFindProtocolForCounterparty(i => { var file = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"CPP_{i}.xml")); return File.Exists(file) == false ? null : File.ReadAllText(file); }); CollaborationRegistry.SetupFindAgreementForCounterparty(i => { var file = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"CPA_{i}.xml")); return File.Exists(file) == false ? null : File.ReadAllText(file); }); CollaborationRegistry.SetupFindAgreementById(i => { var file = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"CPA_{i:D}.xml")); return File.Exists(file) == false ? null : File.ReadAllText(file); }); Settings = new MessagingSettings() { MyHerId = MockFactory.HelsenorgeHerId, SigningCertificate = new CertificateSettings() { StoreName = StoreName.My, StoreLocation = StoreLocation.LocalMachine, Thumbprint = TestCertificates.HelsenorgeSigntatureThumbprint }, DecryptionCertificate = new CertificateSettings() { StoreName = StoreName.My, StoreLocation = StoreLocation.LocalMachine, Thumbprint = TestCertificates.HelsenorgeEncryptionThumbprint } }; Settings.ServiceBus.ConnectionString = "connection string"; Settings.ServiceBus.Synchronous.ReplyQueueMapping.Add(Environment.MachineName.ToLower(), "RepliesGoHere"); // make things easier by only having one processing task per queue Settings.ServiceBus.Asynchronous.ProcessingTasks = 1; Settings.ServiceBus.Synchronous.ProcessingTasks = 1; Settings.ServiceBus.Error.ProcessingTasks = 1; MockFactory = new MockFactory(otherHerId); CertificateValidator = new MockCertificateValidator(); CertificateStore = new MockCertificateStore(); var signingCertificate = CertificateStore.GetCertificate(TestCertificates.HelsenorgeSigntatureThumbprint); var encryptionCertificate = CertificateStore.GetCertificate(TestCertificates.HelsenorgeEncryptionThumbprint); MessageProtection = new MockMessageProtection(signingCertificate, encryptionCertificate); Client = new MessagingClient( Settings, LoggerFactory, CollaborationRegistry, AddressRegistry, CertificateStore, CertificateValidator, MessageProtection ); ; Client.ServiceBus.RegisterAlternateMessagingFactory(MockFactory); Server = new MockMessagingServer( Settings, LoggerFactory, CollaborationRegistry, AddressRegistry, CertificateStore, CertificateValidator, MessageProtection ); Server.ServiceBus.RegisterAlternateMessagingFactory(MockFactory); } internal MockMessage CreateMockMessage(OutgoingMessage message) { return new MockMessage(GenericResponse) { MessageFunction = message.MessageFunction, ApplicationTimestamp = DateTime.Now, ContentType = ContentType.SignedAndEnveloped, MessageId = Guid.NewGuid().ToString("D"), CorrelationId = message.MessageId, FromHerId = MockFactory.OtherHerId, ToHerId = MockFactory.HelsenorgeHerId, ScheduledEnqueueTimeUtc = DateTime.UtcNow, TimeToLive = TimeSpan.FromSeconds(15), }; } protected void RunAndHandleException(Task task) { try { Task.WaitAll(task); } catch (AggregateException ex) { throw ex.InnerException; } } protected void RunAndHandleMessagingException(Task task, EventId id) { try { Task.WaitAll(task); } catch (AggregateException ex) { if ((ex.InnerException is MessagingException messagingException) && (messagingException.EventId.Id == id.Id)) { throw ex.InnerException; } throw new InvalidOperationException("Expected a messaging exception"); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider { internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { return text[characterPosition] == '<'; } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync( Document document, int position, CompletionTrigger trigger, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>(); if (parentTrivia == null) { return null; } var items = new List<CompletionItem>(); var attachedToken = parentTrivia.ParentTrivia.Token; if (attachedToken.Kind() == SyntaxKind.None) { return null; } var semanticModel = await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false); ISymbol declaredSymbol = null; var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken); } else { var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); } } // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } if (parentElementName == ParamRefTagName) { return GetParamNameItems(declaredSymbol); } else if (parentElementName == TypeParamRefTagName) { return GetTypeParamNameItems(declaredSymbol); } } if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText || (token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) || (token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement))) { // The user is typing inside an XmlElement if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement || token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement)) { items.AddRange(GetNestedTags(declaredSymbol)); } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems()); } if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) && token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement)) { var element = (XmlElementSyntax)token.Parent.Parent.Parent; if (element.StartTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems()); } } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListHeaderTagName) { items.AddRange(GetListHeaderItems()); } if (token.Parent.Parent is DocumentationCommentTriviaSyntax || (token.Parent.Parent.IsKind(SyntaxKind.XmlEmptyElement) && token.Parent.Parent.Parent is DocumentationCommentTriviaSyntax)) { items.AddRange(GetTopLevelSingleUseNames(parentTrivia)); items.AddRange(GetTopLevelRepeatableItems()); items.AddRange(GetTagsForSymbol(declaredSymbol, parentTrivia)); } } if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag) { var startTag = (XmlElementStartTagSyntax)token.Parent; if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems()); } if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListHeaderTagName) { items.AddRange(GetListHeaderItems()); } } items.AddRange(GetAlwaysVisibleItems()); return items; } private IEnumerable<CompletionItem> GetTopLevelSingleUseNames(DocumentationCommentTriviaSyntax parentTrivia) { var names = new HashSet<string>(new[] { SummaryTagName, RemarksTagName, ExampleTagName, CompletionListTagName }); RemoveExistingTags(parentTrivia, names, (x) => x.StartTag.Name.LocalName.ValueText); return names.Select(GetItem); } private void RemoveExistingTags(DocumentationCommentTriviaSyntax parentTrivia, ISet<string> names, Func<XmlElementSyntax, string> selector) { if (parentTrivia != null) { foreach (var node in parentTrivia.Content) { var element = node as XmlElementSyntax; if (element != null) { names.Remove(selector(element)); } } } } private IEnumerable<CompletionItem> GetTagsForSymbol(ISymbol symbol, DocumentationCommentTriviaSyntax trivia) { if (symbol is IMethodSymbol method) { return GetTagsForMethod(method, trivia); } if (symbol is IPropertySymbol property) { return GetTagsForProperty(property, trivia); } if (symbol is INamedTypeSymbol namedType) { return GetTagsForType(namedType, trivia); } return SpecializedCollections.EmptyEnumerable<CompletionItem>(); } private IEnumerable<CompletionItem> GetTagsForType(INamedTypeSymbol symbol, DocumentationCommentTriviaSyntax trivia) { var items = new List<CompletionItem>(); var typeParameters = symbol.TypeParameters.Select(p => p.Name).ToSet(); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName)); items.AddRange(typeParameters.Select(t => CreateCompletionItem(FormatParameter(TypeParamTagName, t)))); return items; } private string AttributeSelector(XmlElementSyntax element, string attribute) { if (!element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; var nameAttribute = startTag.Attributes.OfType<XmlNameAttributeSyntax>().FirstOrDefault(a => a.Name.LocalName.ValueText == NameAttributeName); if (nameAttribute != null) { if (startTag.Name.LocalName.ValueText == attribute) { return nameAttribute.Identifier.Identifier.ValueText; } } } return null; } private IEnumerable<CompletionItem> GetTagsForProperty(IPropertySymbol symbol, DocumentationCommentTriviaSyntax trivia) { var items = new List<CompletionItem>(); if (symbol.IsIndexer) { var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName)); items.AddRange(parameters.Select(p => CreateCompletionItem(FormatParameter(ParamTagName, p)))); } var typeParameters = symbol.GetTypeArguments().Select(p => p.Name).ToSet(); items.AddRange(typeParameters.Select(t => CreateCompletionItem(TypeParamTagName, NameAttributeName, t))); items.Add(CreateCompletionItem("value")); return items; } private IEnumerable<CompletionItem> GetTagsForMethod(IMethodSymbol symbol, DocumentationCommentTriviaSyntax trivia) { var items = new List<CompletionItem>(); var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); var typeParameters = symbol.TypeParameters.Select(t => t.Name).ToSet(); RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName)); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName)); items.AddRange(parameters.Select(p => CreateCompletionItem(FormatParameter(ParamTagName, p)))); items.AddRange(typeParameters.Select(t => CreateCompletionItem(FormatParameter(TypeParamTagName, t)))); // Provide a return completion item in case the function returns something var returns = true; foreach (var node in trivia.Content) { var element = node as XmlElementSyntax; if (element != null && !element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; if (startTag.Name.LocalName.ValueText == ReturnsTagName) { returns = false; break; } } } if (returns && !symbol.ReturnsVoid) { items.Add(CreateCompletionItem(ReturnsTagName)); } return items; } protected IEnumerable<CompletionItem> GetParamNameItems(ISymbol declaredSymbol) { var items = declaredSymbol?.GetParameters() .Select(parameter => CreateCompletionItem(parameter.Name)); return items ?? SpecializedCollections.EmptyEnumerable<CompletionItem>(); } protected IEnumerable<CompletionItem> GetTypeParamNameItems(ISymbol declaredSymbol) { var items = declaredSymbol?.GetTypeParameters() .Select(typeParameter => CreateCompletionItem(typeParameter.Name)); return items ?? SpecializedCollections.EmptyEnumerable<CompletionItem>(); } private static CompletionItemRules s_defaultRules = CompletionItemRules.Create( filterCharacterRules: FilterRules, commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, '>', '\t')), enterKeyRule: EnterKeyRule.Never); protected override CompletionItemRules GetCompletionItemRules(string displayText) { var commitRules = s_defaultRules.CommitCharacterRules; if (displayText.Contains("\"")) { commitRules = commitRules.Add(WithoutQuoteRule); } if (displayText.Contains(" ")) { commitRules = commitRules.Add(WithoutSpaceRule); } return s_defaultRules.WithCommitCharacterRules(commitRules); } } }
using System; using System.ComponentModel; using System.Linq; using Android.App; using Android.OS; using Android.Views; using Android.Widget; using System.Collections.Specialized; using System.Collections.Generic; using Android.Content; using Android.Graphics; namespace Microsoft.WindowsAzure.Mobile.Android.Test { [Activity] public class HarnessActivity : Activity { private ExpandableListView list; private TextView runStatus; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); Title = "C# Client Library Tests"; RequestWindowFeature (WindowFeatures.Progress); SetContentView (Resource.Layout.Harness); this.runStatus = FindViewById<TextView> (Resource.Id.RunStatus); this.list = FindViewById<ExpandableListView> (Resource.Id.List); this.list.SetAdapter (new TestListAdapter (this, App.Listener)); this.list.ChildClick += (sender, e) => { Intent testIntent = new Intent (this, typeof(TestActivity)); GroupDescription groupDesc = (GroupDescription)this.list.GetItemAtPosition (e.GroupPosition); TestDescription desc = groupDesc.Tests.ElementAt (e.ChildPosition); testIntent.PutExtra ("name", desc.Test.Name); testIntent.PutExtra ("desc", desc.Test.Description); testIntent.PutExtra ("log", desc.Log); StartActivity (testIntent); }; SetProgressBarVisibility (true); } protected override void OnStart() { base.OnStart(); App.Listener.PropertyChanged += OnListenerPropertyChanged; SetProgress (App.Listener.Progress); ShowStatus(); } protected override void OnStop() { base.OnStop(); App.Listener.PropertyChanged -= OnListenerPropertyChanged; } private void ShowStatus() { RunOnUiThread (() => { if (String.IsNullOrWhiteSpace (App.Listener.Status)) return; Toast.MakeText (this, App.Listener.Status, ToastLength.Long) .Show (); }); } private void UpdateProgress() { RunOnUiThread (() => { SetProgress (App.Listener.Progress); this.runStatus.Text = String.Format ("Passed: {0} Failed: {1}", App.Harness.Progress - App.Harness.Failures, App.Harness.Failures); }); } private void OnListenerPropertyChanged (object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "Progress": UpdateProgress(); break; case "Status": ShowStatus(); break; } } class TestListAdapter : BaseExpandableListAdapter { public TestListAdapter (Activity activity, TestListener listener) { this.activity = activity; this.listener = listener; INotifyCollectionChanged changed = listener.Groups as INotifyCollectionChanged; if (changed != null) changed.CollectionChanged += OnGroupsCollectionChanged; this.groups = new List<GroupDescription> (listener.Groups); } public override Java.Lang.Object GetChild (int groupPosition, int childPosition) { GroupDescription group = this.groups [groupPosition]; return group.Tests.ElementAt (childPosition); } public override long GetChildId (int groupPosition, int childPosition) { return groupPosition * (childPosition * 2); } public override int GetChildrenCount (int groupPosition) { GroupDescription group = this.groups [groupPosition]; return group.Tests.Count; } public override View GetChildView (int groupPosition, int childPosition, bool isLastChild, View convertView, ViewGroup parent) { GroupDescription group = this.groups [groupPosition]; TestDescription test = group.Tests.ElementAt (childPosition); View view = convertView; if (view == null) view = this.activity.LayoutInflater.Inflate (Resource.Layout.ListedTest, null); TextView text = view.FindViewById<TextView> (Resource.Id.TestName); text.Text = test.Test.Name; if (!test.Test.Passed) text.SetTextColor (Color.Red); else text.SetTextColor (Color.White); return view; } public override Java.Lang.Object GetGroup (int groupPosition) { return this.groups [groupPosition]; } public override long GetGroupId (int groupPosition) { return groupPosition; } public override View GetGroupView (int groupPosition, bool isExpanded, View convertView, ViewGroup parent) { GroupDescription group = this.groups [groupPosition]; View view = convertView; if (view == null) view = this.activity.LayoutInflater.Inflate (Resource.Layout.ListedGroup, null); TextView text = view.FindViewById<TextView> (Resource.Id.TestName); text.Text = group.Group.Name; if (group.HasFailures) text.SetTextColor (Color.Red); else text.SetTextColor (Color.White); return view; } public override bool IsChildSelectable (int groupPosition, int childPosition) { return true; } public override int GroupCount { get { return this.groups.Count; } } public override bool HasStableIds { get { return false; } } private List<GroupDescription> groups; private Activity activity; private TestListener listener; void OnTestsCollectionChanged (object sender, NotifyCollectionChangedEventArgs e) { this.activity.RunOnUiThread (() => { NotifyDataSetChanged (); }); } void OnGroupsCollectionChanged (object sender, NotifyCollectionChangedEventArgs e) { this.activity.RunOnUiThread (() => { foreach (INotifyCollectionChanged notify in this.groups.Select (g => g.Tests).OfType<INotifyCollectionChanged>()) notify.CollectionChanged -= OnTestsCollectionChanged; this.groups = new List<GroupDescription> (this.listener.Groups); foreach (INotifyCollectionChanged notify in this.groups.Select (g => g.Tests).OfType<INotifyCollectionChanged>()) notify.CollectionChanged += OnTestsCollectionChanged; NotifyDataSetChanged (); }); } } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Collections.Specialized; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using Voyage.Terraingine.DataInterfacing; using Voyage.Terraingine.DXViewport; using Voyage.LuaNetInterface; namespace Voyage.Terraingine { /// <summary> /// A user control for manipulating terrain textures. /// </summary> public class TextureManipulation : System.Windows.Forms.UserControl { #region Data Members private DataInterfacing.ViewportInterface _viewport; private DataInterfacing.DataManipulation _terrainData; private NameValueCollection _textureAlgorithms; private TerrainViewport _owner; private DXViewport.Viewport _dx; private bool _updateData; private System.Windows.Forms.GroupBox grpTextures_Operation; private System.Windows.Forms.ComboBox cmbTextures_Operation; private System.Windows.Forms.GroupBox grpTextures_Name; private System.Windows.Forms.Button btnTextures_Name; private System.Windows.Forms.TextBox txtTextures_Name; private System.Windows.Forms.GroupBox grpTextures_Sizing; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label8; private System.Windows.Forms.NumericUpDown numTextures_vScale; private System.Windows.Forms.NumericUpDown numTextures_uScale; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.NumericUpDown numTextures_vShift; private System.Windows.Forms.NumericUpDown numTextures_uShift; private System.Windows.Forms.GroupBox grpTextures_Textures; private System.Windows.Forms.Button btnTextures_DisableAll; private System.Windows.Forms.Button btnTextures_Disable; private System.Windows.Forms.Button btnTextures_MoveDown; private System.Windows.Forms.Button btnTextures_MoveUp; private System.Windows.Forms.Button btnTextures_RemoveTex; private System.Windows.Forms.TreeView treeTextures; private System.Windows.Forms.Button btnTextures_AddTex; private System.Windows.Forms.GroupBox grpTextureAlgorithms; private System.Windows.Forms.Button btnLoadAlgorithm; private System.Windows.Forms.Button btnRunAlgorithm; private System.Windows.Forms.ListBox lstAlgorithms; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; #endregion #region Properties /// <summary> /// Gets or sets whether the control allows data updates. /// </summary> public bool EnableDataUpdates { get { return _updateData; } set { _updateData = value; } } #endregion #region Basic Form Methods /// <summary> /// Creates a texture manipulation user control. /// </summary> public TextureManipulation() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// Initializes the control's data members. /// </summary> /// <param name="owner">The TerrainViewport that contains the control.</param> public void Initialize( TerrainViewport owner ) { // Shortcut variables for the DirectX viewport and the terrain data _owner = owner; _viewport = owner.MainViewport; _terrainData = owner.MainViewport.TerrainData; _dx = owner.MainViewport.DXViewport; // Initialize the control-specific data _textureAlgorithms = new NameValueCollection(); _updateData = true; // Register tooltips ToolTip t = new ToolTip(); // Textures group tooltips t.SetToolTip( btnTextures_AddTex, "Add a texture to the terrain" ); t.SetToolTip( btnTextures_RemoveTex, "Remove the selected texture from the terrain" ); t.SetToolTip( btnTextures_MoveUp, "Move the selected texture up one level" ); t.SetToolTip( btnTextures_MoveDown, "Move the selected texture down one level" ); t.SetToolTip( btnTextures_Disable, "Disable the selected texture" ); t.SetToolTip( btnTextures_DisableAll, "Disable all textures" ); // Texture Name group tooltips t.SetToolTip( btnTextures_Name, "Change the name of the selected texture" ); } #endregion #region Event Methods /// <summary> /// Displays notification that a drag-and-drop action is occurring. /// </summary> private void treeTextures_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) { if ( e.Data.GetDataPresent( DataFormats.FileDrop, false ) == true ) e.Effect = DragDropEffects.All; } /// <summary> /// Opens a drag-and-dropped texture. /// </summary> private void treeTextures_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { string[] files = (string[]) e.Data.GetData( DataFormats.FileDrop ); DialogResult result = DialogResult.OK; if ( _terrainData.TerrainPage.TerrainPatch.NumTextures >= _viewport.DXViewport.Device.DeviceCaps.MaxSimultaneousTextures ) { result = MessageBox.Show( "The maximum number of textures for your video card have " + "been loaded. Additional textures will not be rendered.\n\nDo you wish to proceed?", "Maximum Textures Loaded", MessageBoxButtons.OKCancel ); if ( result == DialogResult.OK ) { foreach ( string s in files ) LoadTexture( s ); } } } /// <summary> /// Changes the selection of the current texture. /// </summary> private void treeTextures_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { treeTextures_AfterSelect(); } /// <summary> /// Adds a texture to the TerrainPage. /// Supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, .tga /// </summary> private void btnTextures_AddTex_Click(object sender, System.EventArgs e) { btnTextures_AddTex_Click(); } /// <summary> /// Removes a texture from the TerrainPage. /// </summary> private void btnTextures_RemoveTex_Click(object sender, System.EventArgs e) { btnTextures_RemoveTex_Click(); } /// <summary> /// Moves the selected texture up one layer on the TerrainPatch. /// </summary> private void btnTextures_MoveUp_Click(object sender, System.EventArgs e) { btnTextures_MoveUp_Click(); } /// <summary> /// Moves the selected texture down one layer on the TerrainPatch. /// </summary> private void btnTextures_MoveDown_Click(object sender, System.EventArgs e) { btnTextures_MoveDown_Click(); } /// <summary> /// Disables the rendering of the selected texture. /// </summary> private void btnTextures_Disable_Click(object sender, System.EventArgs e) { btnTextures_Disable_Click(); } /// <summary> /// Disables the rendering of all textures. /// </summary> private void btnTextures_DisableAll_Click(object sender, System.EventArgs e) { btnTextures_DisableAll_Click(); } /// <summary> /// Renames the currently selected texture. /// </summary> private void txtTextures_Name_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if ( e.KeyCode == Keys.Enter ) btnTextures_Name_Click(); } /// <summary> /// Renames the currently selected texture. /// </summary> private void btnTextures_Name_Click(object sender, System.EventArgs e) { btnTextures_Name_Click(); } /// <summary> /// Changes the texture blending operation for the selected texture when rendering. /// </summary> private void cmbTextures_Operation_SelectedIndexChanged(object sender, System.EventArgs e) { cmbTextures_Operation_SelectedIndexChanged(); } /// <summary> /// Shifts the U-coordinates of the current texture. /// </summary> private void numTextures_uShift_ValueChanged(object sender, System.EventArgs e) { ShiftValuesChanged( false ); } /// <summary> /// Shifts the U-coordinates of the current texture. /// </summary> private void numTextures_uShift_Leave(object sender, System.EventArgs e) { ShiftValuesChanged( true ); } /// <summary> /// Shifts the V-coordinates of the current texture. /// </summary> private void numTextures_vShift_ValueChanged(object sender, System.EventArgs e) { ShiftValuesChanged( false ); } /// <summary> /// Shifts the V-coordinates of the current texture. /// </summary> private void numTextures_vShift_Leave(object sender, System.EventArgs e) { ShiftValuesChanged( true ); } /// <summary> /// Scales the U-coordinates of the current texture. /// </summary> private void numTextures_uScale_ValueChanged(object sender, System.EventArgs e) { ScaleValuesChanged( false ); } /// <summary> /// Scales the U-coordinates of the current texture. /// </summary> private void numTextures_uScale_Leave(object sender, System.EventArgs e) { ScaleValuesChanged( true ); } /// <summary> /// Scales the V-coordinates of the current texture. /// </summary> private void numTextures_vScale_ValueChanged(object sender, System.EventArgs e) { ScaleValuesChanged( false ); } /// <summary> /// Scales the V-coordinates of the current texture. /// </summary> private void numTextures_vScale_Leave(object sender, System.EventArgs e) { ScaleValuesChanged( true ); } /// <summary> /// Enables the texture manipulation "Run Algorithm" button if an item is selected. /// </summary> private void lstAlgorithms_SelectedIndexChanged(object sender, System.EventArgs e) { lstAlgorithms_SelectedIndexChanged(); } /// <summary> /// Runs the texture manipulation "Run Algorithm" button if an item is being clicked. /// </summary> private void lstAlgorithms_DoubleClick(object sender, System.EventArgs e) { lstAlgorithms_DoubleClick(); } /// <summary> /// Runs the selected texture manipulation algorithm. /// </summary> private void btnRunAlgorithm_Click(object sender, System.EventArgs e) { btnRunAlgorithm_Click(); } /// <summary> /// Loads a new texture manipulation plug-in. /// </summary> private void btnLoadAlgorithm_Click(object sender, System.EventArgs e) { btnLoadAlgorithm_Click(); } #endregion #region Textures /// <summary> /// Changes the selection of the current texture. /// </summary> public void treeTextures_AfterSelect() { if ( treeTextures.SelectedNode != null ) SetTextureSelectedState( treeTextures.Nodes.Count - treeTextures.SelectedNode.Index - 1 ); else SetTextureSelectedState( -1 ); } /// <summary> /// Adds a texture to the TerrainPage. /// Supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, .tga /// </summary> public void btnTextures_AddTex_Click() { if ( _terrainData.TerrainPage != null ) { OpenFileDialog dlg = new OpenFileDialog(); DialogResult result = DialogResult.OK; if ( _terrainData.TerrainPage.TerrainPatch.NumTextures >= _viewport.DXViewport.Device.DeviceCaps.MaxSimultaneousTextures ) { result = MessageBox.Show( "The maximum number of textures for your video card have " + "been loaded. Additional textures will not be rendered.\n\nDo you wish to proceed?", "Maximum Textures Loaded", MessageBoxButtons.OKCancel ); } if ( result == DialogResult.OK ) { dlg.InitialDirectory = Application.ExecutablePath.Substring( 0, Application.ExecutablePath.LastIndexOf( "\\" ) ) + "\\Images"; result = dlg.ShowDialog( this ); if ( result == DialogResult.OK && dlg.FileName != null ) LoadTexture( dlg.FileName ); } } else MessageBox.Show( "Must have terrain to load texture onto!", "Cannot Load Texture", MessageBoxButtons.OK, MessageBoxIcon.Exclamation ); } /// <summary> /// Removes a texture from the TerrainPage. /// </summary> public void btnTextures_RemoveTex_Click() { if ( _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex > -1 ) { _terrainData.StoreCurrentPage( "Remove Texture" ); _terrainData.TerrainPage.TerrainPatch.RemoveTexture(); treeTextures.Nodes.Remove( treeTextures.SelectedNode ); if ( treeTextures.Nodes.Count == 0 ) treeTextures_AfterSelect( this, new TreeViewEventArgs( null ) ); } } /// <summary> /// Moves the selected texture up one layer on the TerrainPatch. /// </summary> public void btnTextures_MoveUp_Click() { if ( treeTextures.SelectedNode.Index > 0 ) { TreeNode node = treeTextures.SelectedNode; int index = treeTextures.SelectedNode.Index; int startIndex = treeTextures.SelectedNode.Index; object tex; treeTextures.Nodes.RemoveAt( treeTextures.SelectedNode.Index ); treeTextures.Nodes.Insert( index - 1, node ); _terrainData.StoreCurrentPage( "Change Texture Layer" ); index = treeTextures.Nodes.Count - index - 1; tex = _terrainData.TerrainPage.TerrainPatch.Textures[index]; _terrainData.TerrainPage.TerrainPatch.Textures[index] = _terrainData.TerrainPage.TerrainPatch.Textures[index + 1]; _terrainData.TerrainPage.TerrainPatch.Textures[index + 1] = tex; treeTextures.SelectedNode = treeTextures.Nodes[startIndex - 1]; } } /// <summary> /// Moves the selected texture down one layer on the TerrainPatch. /// </summary> public void btnTextures_MoveDown_Click() { if ( treeTextures.SelectedNode.Index < treeTextures.Nodes.Count - 1 ) { TreeNode node = treeTextures.SelectedNode; int index = treeTextures.SelectedNode.Index; int startIndex = treeTextures.SelectedNode.Index; object tex; treeTextures.Nodes.RemoveAt( treeTextures.SelectedNode.Index ); treeTextures.Nodes.Insert( index + 1, node ); _terrainData.StoreCurrentPage( "Change Texture Layer" ); index = treeTextures.Nodes.Count - index - 1; tex = _terrainData.TerrainPage.TerrainPatch.Textures[index]; _terrainData.TerrainPage.TerrainPatch.Textures[index] = _terrainData.TerrainPage.TerrainPatch.Textures[index - 1]; _terrainData.TerrainPage.TerrainPatch.Textures[index - 1] = tex; treeTextures.SelectedNode = treeTextures.Nodes[startIndex + 1]; } } /// <summary> /// Disables the rendering of the selected texture. /// </summary> public void btnTextures_Disable_Click() { if ( _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex > -1 ) { DataCore.Texture texture = _terrainData.TerrainPage.TerrainPatch.GetTexture(); texture.Render = !texture.Render; if ( btnTextures_Disable.Text == "Disable Texture" ) btnTextures_Disable.Text = "Enable Texture"; else btnTextures_Disable.Text = "Disable Texture"; } } /// <summary> /// Disables the rendering of all textures. /// </summary> public void btnTextures_DisableAll_Click() { EnableAllTextures( _terrainData.RenderTextures ); } /// <summary> /// Loads a texture file into the TerrainPage. /// </summary> /// <param name="filename">Filename of the texture to load.</param> [LuaFunctionAttribute( "LoadTexture", "Loads a texture file into the TerrainPage.", "The filename of the texture to load." )] public void LoadTexture( string filename ) { if ( _terrainData.TerrainPage != null ) { try { TreeNode node = new TreeNode( filename ); int index = _terrainData.TerrainPage.TerrainPatch.Textures.Count; _terrainData.StoreCurrentPage( "Add Texture" ); _terrainData.TerrainPage.TerrainPatch.AddTexture( new DataCore.Texture( TextureLoader.FromFile( _dx.Device, filename ), filename ) ); _terrainData.TerrainPage.TerrainPatch.RefreshBuffers = true; ( (DataCore.Texture) _terrainData.TerrainPage.TerrainPatch.Textures[index] ).Name = filename; treeTextures.Nodes.Insert( 0, node ); treeTextures.SelectedNode = treeTextures.Nodes[0]; txtTextures_Name.Focus(); txtTextures_Name.SelectAll(); // Selects all text in the textbox for easy renaming. } catch { MessageBox.Show( "The texture could not be loaded.", "Error Loading Texture", MessageBoxButtons.OK ); } finally { } } else { MessageBox.Show( "The terrain must be created before textures can be loaded.", "Error Loading Texture", MessageBoxButtons.OK ); } } /// <summary> /// Removes the current texture from the TerrainPage. /// </summary> [LuaFunctionAttribute( "RemoveTexture", "Removes the current texture from the TerrainPage." )] public void RemoveTexture() { if ( treeTextures.SelectedNode.Index > -1 ) btnTextures_RemoveTex_Click(); } /// <summary> /// Moves the current texture up one layer on the TerrainPatch. /// </summary> [LuaFunctionAttribute( "MoveTextureUp", "Moves the current texture up one layer on the TerrainPatch." )] public void MoveTextureUp() { if ( treeTextures.SelectedNode.Index > -1 ) btnTextures_MoveUp_Click(); } /// <summary> /// Moves the current texture down one layer on the TerrainPatch. /// </summary> [LuaFunctionAttribute( "MoveTextureDown", "Moves the current texture down one layer on the TerrainPatch." )] public void MoveTextureDown() { if ( treeTextures.SelectedNode.Index > -1 ) btnTextures_MoveDown_Click(); } /// <summary> /// Disables the current texture in the TerrainPatch. /// </summary> [LuaFunctionAttribute( "DisableTexture", "Disables the current texture in the TerrainPatch." )] public void DisableTexture() { if ( treeTextures.SelectedNode.Index > -1 ) btnTextures_Disable_Click(); } /// <summary> /// Enables or disables the rendering of all textures. /// </summary> /// <param name="enable">Whether to enable or disable texture rendering.</param> [LuaFunctionAttribute( "EnableAllTextures", "Enables or disables the rendering of all textures.", "Whether to enable or disable texture rendering." )] public void EnableAllTextures( bool enable ) { if ( enable ) { _terrainData.RenderTextures = false; btnTextures_DisableAll.Text = "Enable All Textures"; btnTextures_DisableAll.BackColor = Color.FromKnownColor( KnownColor.ControlLight ); } else { _terrainData.RenderTextures = true; btnTextures_DisableAll.Text = "Disable All Textures"; btnTextures_DisableAll.BackColor = Color.FromKnownColor( KnownColor.Control ); } } #endregion #region Texture Name /// <summary> /// Renames the currently selected texture. /// </summary> public void btnTextures_Name_Click() { SetTextureName( txtTextures_Name.Text ); } /// <summary> /// Renames the specified texture. /// </summary> /// <param name="name">The new name of the texture.</param> [LuaFunctionAttribute( "SetTextureName", "Renames the specified texture.", "The new name of the texture." )] public void SetTextureName( string name ) { if ( _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex > -1 ) { DataCore.Texture texture = _terrainData.TerrainPage.TerrainPatch.GetTexture(); texture.Name = txtTextures_Name.Text; treeTextures.SelectedNode.Text = name; } } #endregion #region Texture Operation /// <summary> /// Changes the texture blending operation for the selected texture when rendering. /// </summary> public void cmbTextures_Operation_SelectedIndexChanged() { if ( _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex > -1 ) SetTextureOperation( cmbTextures_Operation.Items[cmbTextures_Operation.SelectedIndex].ToString() ); } /// <summary> /// Changes the texture blending operation for the specified texture when rendering. /// </summary> /// <param name="operation">The name of the operation to set.</param> [LuaFunctionAttribute( "SetTextureOperation", "Changes the texture blending operation for the specified texture when rendering.", "The name of the operation to set." )] public void SetTextureOperation( string operation ) { if ( _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex > -1 ) { DataCore.Texture texture = _terrainData.TerrainPage.TerrainPatch.GetTexture(); if ( HasOperation( operation ) ) { _terrainData.StoreCurrentPage( "Change Texture Blending" ); texture.Operation = _terrainData.GetTextureOperation( operation ); texture.OperationText = operation; _terrainData.TerrainPage.TerrainPatch.RefreshBuffers = true; } } } /// <summary> /// Checks if the list of operations contains the specified operation. /// </summary> /// <param name="name">The name of the operation to search for.</param> /// <returns>Whether the operation was found.</returns> private bool HasOperation( string name ) { bool found = false; int count = 0; while ( !found && count < cmbTextures_Operation.Items.Count ) { if ( cmbTextures_Operation.Items[count].ToString() == name ) found = true; else count++; } return found; } #endregion #region Adjust Texture Size /// <summary> /// Shifts the selected texture by the amount indicated by the numeric spinners. /// </summary> /// <param name="endTextureMovement">Whether to end texture movement.</param> public void ShiftValuesChanged( bool endTextureMovement ) { if ( _updateData ) { ShiftValuesChanged(); if ( endTextureMovement ) _terrainData.EndTextureMovement(); } } /// <summary> /// Scales the selected texture by the amount indicated by the numeric spinners. /// </summary> /// <param name="endTextureMovement">Whether to end texture movement.</param> public void ScaleValuesChanged( bool endTextureMovement ) { if ( _updateData ) { ScaleValuesChanged(); if ( endTextureMovement ) _terrainData.EndTextureMovement(); } } /// <summary> /// Shifts the selected texture by the amount indicated by the numeric spinners. /// </summary> private void ShiftValuesChanged() { if ( _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex > -1 ) { DataCore.Texture tex = _terrainData.TerrainPage.TerrainPatch.GetTexture(); Vector2 shift = tex.Shift; shift.X = ( float ) -numTextures_uShift.Value; shift.Y =( float ) -numTextures_vShift.Value; tex.Shift = shift; _terrainData.ShiftTexture(); _terrainData.TerrainPage.TerrainPatch.RefreshBuffers = true; } } /// <summary> /// Scales the selected texture by the amount indicated by the numeric spinners. /// </summary> private void ScaleValuesChanged() { if ( _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex > -1 ) { DataCore.Texture tex = _terrainData.TerrainPage.TerrainPatch.GetTexture(); Vector2 scale = tex.Scale; scale.X = ( float ) numTextures_uScale.Value; scale.Y = ( float ) numTextures_vScale.Value; tex.Scale = scale; _terrainData.ScaleTexture(); _terrainData.TerrainPage.TerrainPatch.RefreshBuffers = true; } } /// <summary> /// Sets the scaling values for the current texture. /// </summary> /// <param name="uScale">The new U-scale for the texture.</param> /// <param name="vScale">The new V-scale for the texture.</param> [LuaFunctionAttribute( "SetTextureScale", "Sets the scaling values for the current texture.", "The new U-scale for the texture.", "The new V-scale for the texture." )] public void SetTextureScale( float uScale, float vScale ) { _updateData = false; numTextures_uScale.Value = Convert.ToDecimal( uScale ); numTextures_vScale.Value = Convert.ToDecimal( vScale ); _updateData = true; ScaleValuesChanged(); } /// <summary> /// Sets the shift values for the current texture. /// </summary> /// <param name="uShift">The new U-shift for the texture.</param> /// <param name="vShift">The new V-shift for the texture.</param> [LuaFunctionAttribute( "SetTextureShift", "Sets the shift values for the current texture.", "The new U-shift for the texture.", "The new V-shift for the texture." )] public void SetTextureShift( float uShift, float vShift ) { _updateData = false; numTextures_uShift.Value = Convert.ToDecimal( uShift ); numTextures_vShift.Value = Convert.ToDecimal( vShift ); _updateData = true; ShiftValuesChanged(); } #endregion #region Algorithms /// <summary> /// Enables the texture manipulation "Run Algorithm" button if an item is selected. /// </summary> public void lstAlgorithms_SelectedIndexChanged() { if ( lstAlgorithms.SelectedIndex > -1 ) btnRunAlgorithm.Enabled = true; else btnRunAlgorithm.Enabled = false; } /// <summary> /// Runs the texture manipulation "Run Algorithm" button if an item is being clicked. /// </summary> public void lstAlgorithms_DoubleClick() { if ( lstAlgorithms.SelectedIndex > -1 ) { btnRunAlgorithm.Enabled = true; btnRunAlgorithm_Click(); } else btnRunAlgorithm.Enabled = false; } /// <summary> /// Runs the selected texture manipulation algorithm. /// </summary> public void btnRunAlgorithm_Click() { if ( lstAlgorithms.SelectedIndex > -1 ) { _terrainData.RunPlugIn( lstAlgorithms.SelectedIndex, DataInterfacing.PlugIns.PlugInTypes.Textures, _owner ); LoadTextures(); } } /// <summary> /// Loads a new texture manipulation plug-in. /// </summary> public void btnLoadAlgorithm_Click() { _terrainData.LoadPlugIn( DataInterfacing.PlugIns.PlugInTypes.Textures ); LoadAlgorithms(); } /// <summary> /// Loads the list of texture manipulation algorithms. /// </summary> public void LoadAlgorithms() { _textureAlgorithms.Clear(); lstAlgorithms.Items.Clear(); for ( int i = 0; i < _terrainData.PlugIns.TexturePlugIns.Count; i++ ) _textureAlgorithms.Add( i.ToString(), ( (PlugIn) _terrainData.PlugIns.TexturePlugIns[i] ).GetName() ); foreach ( string key in _textureAlgorithms.Keys ) lstAlgorithms.Items.Add( _textureAlgorithms.GetValues( key )[0] ); lstAlgorithms.SelectedIndex = -1; } /// <summary> /// Runs the texture manipulation plug-in specified. /// </summary> /// <param name="name">The name of the plug-in to run.</param> [LuaFunctionAttribute( "RunPlugIn", "Runs the texture manipulation plug-in specified.", "The name of the plug-in to run." )] public void RunAlgorithm( string name ) { bool found = false; int count = 0; while ( !found && lstAlgorithms.Items[count].ToString() != name ) count++; if ( found ) _terrainData.RunPlugIn( count, DataInterfacing.PlugIns.PlugInTypes.Textures, _owner ); else MessageBox.Show( "Texture manipulation plug-in " + name + " could not be found! " ); } /// <summary> /// Runs the texture manipulation plug-in specified in automatic mode. /// </summary> /// <param name="name">The name of the plug-in to run.</param> /// <param name="filename">The name of the file to load into the plug-in.</param> [LuaFunctionAttribute( "RunAutoPlugIn", "Runs the texture manipulation plug-in specified in automatic mode.", "The name of the plug-in to run.", "The name of the file to load into the plug-in." )] public void RunAutoAlgorithm( string name, string filename ) { bool found = false; int count = 0; while ( !found && lstAlgorithms.Items[count].ToString() != name ) count++; if ( found ) _terrainData.RunPlugInAuto( count, DataInterfacing.PlugIns.PlugInTypes.Textures, _owner, filename ); else MessageBox.Show( "Texture manipulation plug-in " + name + " could not be found! " ); } /// <summary> /// Loads a new texture manipulation plug-in. /// </summary> [LuaFunctionAttribute( "LoadPlugIn", "Loads a new texture manipulation plug-in." )] public void LoadAlgorithm() { _terrainData.LoadPlugIn( DataInterfacing.PlugIns.PlugInTypes.Textures ); LoadAlgorithms(); } #endregion #region Other Terrain Functions /// <summary> /// Loads the textures of the TerrainPage into the Textures tab control. /// </summary> public void LoadTextures() { TreeNode node; DataCore.Texture tex; treeTextures.Nodes.Clear(); if ( _terrainData.TerrainPage != null ) { for ( int i = 0; i < _terrainData.TerrainPage.TerrainPatch.Textures.Count; i++ ) { tex = ( (DataCore.Texture) _terrainData.TerrainPage.TerrainPatch.Textures[i] ); node = new TreeNode( tex.Name ); treeTextures.Nodes.Insert( 0, node ); } if ( treeTextures.Nodes.Count > 0 ) treeTextures.SelectedNode = treeTextures.Nodes[0]; treeTextures_AfterSelect(); } } /// <summary> /// Sets window states for selecting a new texture. /// </summary> /// <param name="index">The texture being selected.</param> private void SetTextureSelectedState( int index ) { if ( index > -1 && index < _terrainData.TerrainPage.TerrainPatch.Textures.Count ) { DataCore.Texture tex; _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex = index; tex = _terrainData.TerrainPage.TerrainPatch.GetTexture(); btnTextures_RemoveTex.Enabled = true; btnTextures_MoveUp.Enabled = true; btnTextures_MoveDown.Enabled = true; btnTextures_Disable.Enabled = true; if ( tex.Render ) btnTextures_Disable.Text = "Disable Texture"; else btnTextures_Disable.Text = "Enable Texture"; txtTextures_Name.Text = tex.Name; grpTextures_Name.Enabled = true; grpTextures_Operation.Enabled = true; grpTextures_Sizing.Enabled = true; grpTextureAlgorithms.Enabled = true; if ( tex.OperationText != null && tex.OperationText.Length > 0 ) { cmbTextures_Operation.SelectAll(); cmbTextures_Operation.SelectedText = tex.OperationText; cmbTextures_Operation.SelectedValue = tex.OperationText; } else { cmbTextures_Operation.SelectAll(); cmbTextures_Operation.SelectedText = ""; cmbTextures_Operation.SelectedValue = null; } _updateData = false; numTextures_uShift.Value = Convert.ToDecimal( tex.Shift.X ); numTextures_vShift.Value = Convert.ToDecimal( tex.Shift.Y ); numTextures_uScale.Value = Convert.ToDecimal( tex.Scale.X ); numTextures_vScale.Value = Convert.ToDecimal( tex.Scale.Y ); _updateData = true; _terrainData.TerrainPage.TerrainPatch.SetTexture( index ); } else { _terrainData.TerrainPage.TerrainPatch.SelectedTextureIndex = -1; btnTextures_RemoveTex.Enabled = false; btnTextures_MoveUp.Enabled = false; btnTextures_MoveDown.Enabled = false; btnTextures_Disable.Enabled = false; txtTextures_Name.Text = null; cmbTextures_Operation.SelectedIndex = -1; grpTextures_Name.Enabled = false; grpTextures_Operation.Enabled = false; grpTextures_Sizing.Enabled = false; grpTextureAlgorithms.Enabled = false; } } /// <summary> /// Selects a texture from the TerrainPage. /// </summary> /// <param name="index">The index of the texture to select.</param> [LuaFunctionAttribute( "SelectTexture", "Selects a texture from the TerrainPage.", "The name of the texture to select." )] public void SelectTexture( int index ) { if ( index > -1 && index < _terrainData.TerrainPage.TerrainPatch.Textures.Count ) treeTextures.SelectedNode = treeTextures.Nodes[ treeTextures.Nodes.Count - index - 1]; } /// <summary> /// Selects a texture from the TerrainPage. /// </summary> /// <param name="name">The name of the texture to select.</param> [LuaFunctionAttribute( "SelectTexture", "Selects a texture from the TerrainPage.", "The name of the texture to select." )] public void SelectTexture( string name ) { bool found = false; int count = 0; while ( !found && count < treeTextures.Nodes.Count ) { if ( treeTextures.Nodes[count].Text == name ) found = true; else count++; } if ( found ) SelectTexture( treeTextures.Nodes.Count - count - 1 ); } #endregion #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(TextureManipulation)); this.grpTextures_Operation = new System.Windows.Forms.GroupBox(); this.cmbTextures_Operation = new System.Windows.Forms.ComboBox(); this.grpTextures_Name = new System.Windows.Forms.GroupBox(); this.btnTextures_Name = new System.Windows.Forms.Button(); this.txtTextures_Name = new System.Windows.Forms.TextBox(); this.grpTextures_Sizing = new System.Windows.Forms.GroupBox(); this.label9 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.numTextures_vScale = new System.Windows.Forms.NumericUpDown(); this.numTextures_uScale = new System.Windows.Forms.NumericUpDown(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.numTextures_vShift = new System.Windows.Forms.NumericUpDown(); this.numTextures_uShift = new System.Windows.Forms.NumericUpDown(); this.grpTextures_Textures = new System.Windows.Forms.GroupBox(); this.btnTextures_DisableAll = new System.Windows.Forms.Button(); this.btnTextures_Disable = new System.Windows.Forms.Button(); this.btnTextures_MoveDown = new System.Windows.Forms.Button(); this.btnTextures_MoveUp = new System.Windows.Forms.Button(); this.btnTextures_RemoveTex = new System.Windows.Forms.Button(); this.treeTextures = new System.Windows.Forms.TreeView(); this.btnTextures_AddTex = new System.Windows.Forms.Button(); this.grpTextureAlgorithms = new System.Windows.Forms.GroupBox(); this.btnLoadAlgorithm = new System.Windows.Forms.Button(); this.btnRunAlgorithm = new System.Windows.Forms.Button(); this.lstAlgorithms = new System.Windows.Forms.ListBox(); this.grpTextures_Operation.SuspendLayout(); this.grpTextures_Name.SuspendLayout(); this.grpTextures_Sizing.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numTextures_vScale)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numTextures_uScale)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numTextures_vShift)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numTextures_uShift)).BeginInit(); this.grpTextures_Textures.SuspendLayout(); this.grpTextureAlgorithms.SuspendLayout(); this.SuspendLayout(); // // grpTextures_Operation // this.grpTextures_Operation.Controls.Add(this.cmbTextures_Operation); this.grpTextures_Operation.Enabled = false; this.grpTextures_Operation.Location = new System.Drawing.Point(8, 352); this.grpTextures_Operation.Name = "grpTextures_Operation"; this.grpTextures_Operation.Size = new System.Drawing.Size(160, 48); this.grpTextures_Operation.TabIndex = 23; this.grpTextures_Operation.TabStop = false; this.grpTextures_Operation.Text = "Texture Operation"; // // cmbTextures_Operation // this.cmbTextures_Operation.Items.AddRange(new object[] { "Add Color", "AddSigned", "AddSmooth", "Blend Alpha", "DotProduct3", "Modulate", "Modulate2X", "Normal (Default)", "Subtract Color", "Use Texture Alpha"}); this.cmbTextures_Operation.Location = new System.Drawing.Point(8, 16); this.cmbTextures_Operation.MaxDropDownItems = 30; this.cmbTextures_Operation.Name = "cmbTextures_Operation"; this.cmbTextures_Operation.Size = new System.Drawing.Size(144, 21); this.cmbTextures_Operation.Sorted = true; this.cmbTextures_Operation.TabIndex = 0; this.cmbTextures_Operation.SelectedIndexChanged += new System.EventHandler(this.cmbTextures_Operation_SelectedIndexChanged); // // grpTextures_Name // this.grpTextures_Name.Controls.Add(this.btnTextures_Name); this.grpTextures_Name.Controls.Add(this.txtTextures_Name); this.grpTextures_Name.Enabled = false; this.grpTextures_Name.Location = new System.Drawing.Point(8, 272); this.grpTextures_Name.Name = "grpTextures_Name"; this.grpTextures_Name.Size = new System.Drawing.Size(160, 72); this.grpTextures_Name.TabIndex = 22; this.grpTextures_Name.TabStop = false; this.grpTextures_Name.Text = "Texture Name"; // // btnTextures_Name // this.btnTextures_Name.Location = new System.Drawing.Point(8, 40); this.btnTextures_Name.Name = "btnTextures_Name"; this.btnTextures_Name.Size = new System.Drawing.Size(144, 23); this.btnTextures_Name.TabIndex = 1; this.btnTextures_Name.Text = "Rename Texture"; this.btnTextures_Name.Click += new System.EventHandler(this.btnTextures_Name_Click); // // txtTextures_Name // this.txtTextures_Name.Location = new System.Drawing.Point(8, 16); this.txtTextures_Name.Name = "txtTextures_Name"; this.txtTextures_Name.Size = new System.Drawing.Size(144, 20); this.txtTextures_Name.TabIndex = 0; this.txtTextures_Name.Text = ""; this.txtTextures_Name.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtTextures_Name_KeyUp); // // grpTextures_Sizing // this.grpTextures_Sizing.Controls.Add(this.label9); this.grpTextures_Sizing.Controls.Add(this.label8); this.grpTextures_Sizing.Controls.Add(this.numTextures_vScale); this.grpTextures_Sizing.Controls.Add(this.numTextures_uScale); this.grpTextures_Sizing.Controls.Add(this.label7); this.grpTextures_Sizing.Controls.Add(this.label6); this.grpTextures_Sizing.Controls.Add(this.numTextures_vShift); this.grpTextures_Sizing.Controls.Add(this.numTextures_uShift); this.grpTextures_Sizing.Enabled = false; this.grpTextures_Sizing.Location = new System.Drawing.Point(8, 408); this.grpTextures_Sizing.Name = "grpTextures_Sizing"; this.grpTextures_Sizing.Size = new System.Drawing.Size(160, 128); this.grpTextures_Sizing.TabIndex = 21; this.grpTextures_Sizing.TabStop = false; this.grpTextures_Sizing.Text = "Adjust Texture Size"; // // label9 // this.label9.Location = new System.Drawing.Point(16, 96); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(48, 16); this.label9.TabIndex = 23; this.label9.Text = "V Scale:"; // // label8 // this.label8.Location = new System.Drawing.Point(16, 72); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(48, 16); this.label8.TabIndex = 22; this.label8.Text = "U Scale:"; // // numTextures_vScale // this.numTextures_vScale.DecimalPlaces = 3; this.numTextures_vScale.Increment = new System.Decimal(new int[] { 1, 0, 0, 196608}); this.numTextures_vScale.Location = new System.Drawing.Point(88, 96); this.numTextures_vScale.Minimum = new System.Decimal(new int[] { 1, 0, 0, 196608}); this.numTextures_vScale.Name = "numTextures_vScale"; this.numTextures_vScale.Size = new System.Drawing.Size(56, 20); this.numTextures_vScale.TabIndex = 21; this.numTextures_vScale.Value = new System.Decimal(new int[] { 1, 0, 0, 0}); this.numTextures_vScale.ValueChanged += new System.EventHandler(this.numTextures_vScale_ValueChanged); this.numTextures_vScale.Leave += new System.EventHandler(this.numTextures_vScale_Leave); // // numTextures_uScale // this.numTextures_uScale.DecimalPlaces = 3; this.numTextures_uScale.Increment = new System.Decimal(new int[] { 1, 0, 0, 196608}); this.numTextures_uScale.Location = new System.Drawing.Point(88, 72); this.numTextures_uScale.Minimum = new System.Decimal(new int[] { 1, 0, 0, 196608}); this.numTextures_uScale.Name = "numTextures_uScale"; this.numTextures_uScale.Size = new System.Drawing.Size(56, 20); this.numTextures_uScale.TabIndex = 20; this.numTextures_uScale.Value = new System.Decimal(new int[] { 10, 0, 0, 65536}); this.numTextures_uScale.ValueChanged += new System.EventHandler(this.numTextures_uScale_ValueChanged); this.numTextures_uScale.Leave += new System.EventHandler(this.numTextures_uScale_Leave); // // label7 // this.label7.Location = new System.Drawing.Point(16, 40); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(48, 16); this.label7.TabIndex = 19; this.label7.Text = "V Shift:"; // // label6 // this.label6.Location = new System.Drawing.Point(16, 16); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(48, 16); this.label6.TabIndex = 18; this.label6.Text = "U Shift:"; // // numTextures_vShift // this.numTextures_vShift.DecimalPlaces = 3; this.numTextures_vShift.Increment = new System.Decimal(new int[] { 1, 0, 0, 196608}); this.numTextures_vShift.Location = new System.Drawing.Point(88, 40); this.numTextures_vShift.Maximum = new System.Decimal(new int[] { 10, 0, 0, 0}); this.numTextures_vShift.Minimum = new System.Decimal(new int[] { 10, 0, 0, -2147483648}); this.numTextures_vShift.Name = "numTextures_vShift"; this.numTextures_vShift.Size = new System.Drawing.Size(56, 20); this.numTextures_vShift.TabIndex = 17; this.numTextures_vShift.ValueChanged += new System.EventHandler(this.numTextures_vShift_ValueChanged); this.numTextures_vShift.Leave += new System.EventHandler(this.numTextures_vShift_Leave); // // numTextures_uShift // this.numTextures_uShift.DecimalPlaces = 3; this.numTextures_uShift.Increment = new System.Decimal(new int[] { 1, 0, 0, 196608}); this.numTextures_uShift.Location = new System.Drawing.Point(88, 16); this.numTextures_uShift.Maximum = new System.Decimal(new int[] { 10, 0, 0, 0}); this.numTextures_uShift.Minimum = new System.Decimal(new int[] { 10, 0, 0, -2147483648}); this.numTextures_uShift.Name = "numTextures_uShift"; this.numTextures_uShift.Size = new System.Drawing.Size(56, 20); this.numTextures_uShift.TabIndex = 16; this.numTextures_uShift.ValueChanged += new System.EventHandler(this.numTextures_uShift_ValueChanged); this.numTextures_uShift.Leave += new System.EventHandler(this.numTextures_uShift_Leave); // // grpTextures_Textures // this.grpTextures_Textures.Controls.Add(this.btnTextures_DisableAll); this.grpTextures_Textures.Controls.Add(this.btnTextures_Disable); this.grpTextures_Textures.Controls.Add(this.btnTextures_MoveDown); this.grpTextures_Textures.Controls.Add(this.btnTextures_MoveUp); this.grpTextures_Textures.Controls.Add(this.btnTextures_RemoveTex); this.grpTextures_Textures.Controls.Add(this.treeTextures); this.grpTextures_Textures.Controls.Add(this.btnTextures_AddTex); this.grpTextures_Textures.Location = new System.Drawing.Point(8, 8); this.grpTextures_Textures.Name = "grpTextures_Textures"; this.grpTextures_Textures.Size = new System.Drawing.Size(160, 256); this.grpTextures_Textures.TabIndex = 20; this.grpTextures_Textures.TabStop = false; this.grpTextures_Textures.Text = "Textures"; // // btnTextures_DisableAll // this.btnTextures_DisableAll.Location = new System.Drawing.Point(8, 224); this.btnTextures_DisableAll.Name = "btnTextures_DisableAll"; this.btnTextures_DisableAll.Size = new System.Drawing.Size(144, 23); this.btnTextures_DisableAll.TabIndex = 22; this.btnTextures_DisableAll.Text = "Disable All Textures"; this.btnTextures_DisableAll.Click += new System.EventHandler(this.btnTextures_DisableAll_Click); // // btnTextures_Disable // this.btnTextures_Disable.Enabled = false; this.btnTextures_Disable.Location = new System.Drawing.Point(8, 192); this.btnTextures_Disable.Name = "btnTextures_Disable"; this.btnTextures_Disable.Size = new System.Drawing.Size(144, 23); this.btnTextures_Disable.TabIndex = 21; this.btnTextures_Disable.Text = "Disable Texture"; this.btnTextures_Disable.Click += new System.EventHandler(this.btnTextures_Disable_Click); // // btnTextures_MoveDown // this.btnTextures_MoveDown.Enabled = false; this.btnTextures_MoveDown.Image = ((System.Drawing.Image)(resources.GetObject("btnTextures_MoveDown.Image"))); this.btnTextures_MoveDown.Location = new System.Drawing.Point(136, 160); this.btnTextures_MoveDown.Name = "btnTextures_MoveDown"; this.btnTextures_MoveDown.Size = new System.Drawing.Size(16, 16); this.btnTextures_MoveDown.TabIndex = 20; this.btnTextures_MoveDown.Click += new System.EventHandler(this.btnTextures_MoveDown_Click); // // btnTextures_MoveUp // this.btnTextures_MoveUp.Enabled = false; this.btnTextures_MoveUp.Image = ((System.Drawing.Image)(resources.GetObject("btnTextures_MoveUp.Image"))); this.btnTextures_MoveUp.Location = new System.Drawing.Point(112, 160); this.btnTextures_MoveUp.Name = "btnTextures_MoveUp"; this.btnTextures_MoveUp.Size = new System.Drawing.Size(16, 16); this.btnTextures_MoveUp.TabIndex = 19; this.btnTextures_MoveUp.Click += new System.EventHandler(this.btnTextures_MoveUp_Click); // // btnTextures_RemoveTex // this.btnTextures_RemoveTex.Enabled = false; this.btnTextures_RemoveTex.Image = ((System.Drawing.Image)(resources.GetObject("btnTextures_RemoveTex.Image"))); this.btnTextures_RemoveTex.Location = new System.Drawing.Point(32, 160); this.btnTextures_RemoveTex.Name = "btnTextures_RemoveTex"; this.btnTextures_RemoveTex.Size = new System.Drawing.Size(16, 16); this.btnTextures_RemoveTex.TabIndex = 17; this.btnTextures_RemoveTex.Click += new System.EventHandler(this.btnTextures_RemoveTex_Click); // // treeTextures // this.treeTextures.AllowDrop = true; this.treeTextures.FullRowSelect = true; this.treeTextures.HideSelection = false; this.treeTextures.ImageIndex = -1; this.treeTextures.Indent = 15; this.treeTextures.Location = new System.Drawing.Point(8, 16); this.treeTextures.Name = "treeTextures"; this.treeTextures.SelectedImageIndex = -1; this.treeTextures.Size = new System.Drawing.Size(144, 136); this.treeTextures.TabIndex = 0; this.treeTextures.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeTextures_AfterSelect); this.treeTextures.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeTextures_DragEnter); this.treeTextures.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeTextures_DragDrop); // // btnTextures_AddTex // this.btnTextures_AddTex.Image = ((System.Drawing.Image)(resources.GetObject("btnTextures_AddTex.Image"))); this.btnTextures_AddTex.Location = new System.Drawing.Point(8, 160); this.btnTextures_AddTex.Name = "btnTextures_AddTex"; this.btnTextures_AddTex.Size = new System.Drawing.Size(16, 16); this.btnTextures_AddTex.TabIndex = 16; this.btnTextures_AddTex.Click += new System.EventHandler(this.btnTextures_AddTex_Click); // // grpTextureAlgorithms // this.grpTextureAlgorithms.Controls.Add(this.btnLoadAlgorithm); this.grpTextureAlgorithms.Controls.Add(this.btnRunAlgorithm); this.grpTextureAlgorithms.Controls.Add(this.lstAlgorithms); this.grpTextureAlgorithms.Enabled = false; this.grpTextureAlgorithms.Location = new System.Drawing.Point(8, 544); this.grpTextureAlgorithms.Name = "grpTextureAlgorithms"; this.grpTextureAlgorithms.Size = new System.Drawing.Size(160, 160); this.grpTextureAlgorithms.TabIndex = 24; this.grpTextureAlgorithms.TabStop = false; this.grpTextureAlgorithms.Text = "Algorithms"; // // btnLoadAlgorithm // this.btnLoadAlgorithm.Location = new System.Drawing.Point(8, 128); this.btnLoadAlgorithm.Name = "btnLoadAlgorithm"; this.btnLoadAlgorithm.Size = new System.Drawing.Size(144, 23); this.btnLoadAlgorithm.TabIndex = 2; this.btnLoadAlgorithm.Text = "Load New Algorithm"; this.btnLoadAlgorithm.Click += new System.EventHandler(this.btnLoadAlgorithm_Click); // // btnRunAlgorithm // this.btnRunAlgorithm.Enabled = false; this.btnRunAlgorithm.Location = new System.Drawing.Point(8, 96); this.btnRunAlgorithm.Name = "btnRunAlgorithm"; this.btnRunAlgorithm.Size = new System.Drawing.Size(144, 23); this.btnRunAlgorithm.TabIndex = 1; this.btnRunAlgorithm.Text = "Run Algorithm"; this.btnRunAlgorithm.Click += new System.EventHandler(this.btnRunAlgorithm_Click); // // lstAlgorithms // this.lstAlgorithms.Location = new System.Drawing.Point(8, 16); this.lstAlgorithms.Name = "lstAlgorithms"; this.lstAlgorithms.Size = new System.Drawing.Size(144, 69); this.lstAlgorithms.TabIndex = 0; this.lstAlgorithms.DoubleClick += new System.EventHandler(this.lstAlgorithms_DoubleClick); this.lstAlgorithms.SelectedIndexChanged += new System.EventHandler(this.lstAlgorithms_SelectedIndexChanged); // // TextureManipulation // this.Controls.Add(this.grpTextureAlgorithms); this.Controls.Add(this.grpTextures_Operation); this.Controls.Add(this.grpTextures_Name); this.Controls.Add(this.grpTextures_Sizing); this.Controls.Add(this.grpTextures_Textures); this.Name = "TextureManipulation"; this.Size = new System.Drawing.Size(176, 712); this.grpTextures_Operation.ResumeLayout(false); this.grpTextures_Name.ResumeLayout(false); this.grpTextures_Sizing.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.numTextures_vScale)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numTextures_uScale)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numTextures_vShift)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numTextures_uShift)).EndInit(); this.grpTextures_Textures.ResumeLayout(false); this.grpTextureAlgorithms.ResumeLayout(false); this.ResumeLayout(false); } #endregion } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System.Collections.Generic; using Scientia.HtmlRenderer.Core.Utils; namespace Scientia.HtmlRenderer.Core.Entities { /// <summary> /// Represents a block of CSS property values.<br/> /// Contains collection of key-value pairs that are CSS properties for specific css class.<br/> /// Css class can be either custom or html tag name. /// </summary> /// <remarks> /// To learn more about CSS blocks visit CSS spec: http://www.w3.org/TR/CSS21/syndata.html#block /// </remarks> public sealed class CssBlock { #region Fields and Consts /// <summary> /// the name of the css class of the block /// </summary> private readonly string _Class; /// <summary> /// the CSS block properties and values /// </summary> private readonly Dictionary<string, string> _Properties; /// <summary> /// additional selectors to used in hierarchy (p className1 > className2) /// </summary> private readonly List<CssBlockSelectorItem> _Selectors; /// <summary> /// is the css block has :hover pseudo-class /// </summary> private readonly bool _Hover; #endregion /// <summary> /// Creates a new block from the block's source /// </summary> /// <param name="class">the name of the css class of the block</param> /// <param name="properties">the CSS block properties and values</param> /// <param name="selectors">optional: additional selectors to used in hierarchy</param> /// <param name="hover">optional: is the css block has :hover pseudo-class</param> public CssBlock(string @class, Dictionary<string, string> properties, List<CssBlockSelectorItem> selectors = null, bool hover = false) { ArgChecker.AssertArgNotNullOrEmpty(@class, "@class"); ArgChecker.AssertArgNotNull(properties, "properties"); this._Class = @class; this._Selectors = selectors; this._Properties = properties; this._Hover = hover; } /// <summary> /// the name of the css class of the block /// </summary> public string Class { get { return this._Class; } } /// <summary> /// additional selectors to used in hierarchy (p className1 > className2) /// </summary> public List<CssBlockSelectorItem> Selectors { get { return this._Selectors; } } /// <summary> /// Gets the CSS block properties and its values /// </summary> public IDictionary<string, string> Properties { get { return this._Properties; } } /// <summary> /// is the css block has :hover pseudo-class /// </summary> public bool Hover { get { return this._Hover; } } /// <summary> /// Merge the other block properties into this css block.<br/> /// Other block properties can overwrite this block properties. /// </summary> /// <param name="other">the css block to merge with</param> public void Merge(CssBlock other) { ArgChecker.AssertArgNotNull(other, "other"); foreach (var prop in other._Properties.Keys) { this._Properties[prop] = other._Properties[prop]; } } /// <summary> /// Create deep copy of the CssBlock. /// </summary> /// <returns>new CssBlock with same data</returns> public CssBlock Clone() { return new CssBlock(this._Class, new Dictionary<string, string>(this._Properties), this._Selectors != null ? new List<CssBlockSelectorItem>(this._Selectors) : null); } /// <summary> /// Check if the two css blocks are the same (same class, selectors and properties). /// </summary> /// <param name="other">the other block to compare to</param> /// <returns>true - the two blocks are the same, false - otherwise</returns> public bool Equals(CssBlock other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!Equals(other._Class, this._Class)) return false; if (!Equals(other._Properties.Count, this._Properties.Count)) return false; foreach (var property in this._Properties) { if (!other._Properties.ContainsKey(property.Key)) return false; if (!Equals(other._Properties[property.Key], property.Value)) return false; } if (!this.EqualsSelector(other)) return false; return true; } /// <summary> /// Check if the selectors of the css blocks is the same. /// </summary> /// <param name="other">the other block to compare to</param> /// <returns>true - the selectors on blocks are the same, false - otherwise</returns> public bool EqualsSelector(CssBlock other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (other.Hover != this.Hover) return false; if (other._Selectors == null && this._Selectors != null) return false; if (other._Selectors != null && this._Selectors == null) return false; if (other._Selectors != null && this._Selectors != null) { if (!Equals(other._Selectors.Count, this._Selectors.Count)) return false; for (int i = 0; i < this._Selectors.Count; i++) { if (!Equals(other._Selectors[i].Class, this._Selectors[i].Class)) return false; if (!Equals(other._Selectors[i].DirectParent, this._Selectors[i].DirectParent)) return false; } } return true; } /// <summary> /// Check if the two css blocks are the same (same class, selectors and properties). /// </summary> /// <param name="obj">the other block to compare to</param> /// <returns>true - the two blocks are the same, false - otherwise</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(CssBlock)) return false; return this.Equals((CssBlock)obj); } /// <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() { unchecked { return ((this._Class != null ? this._Class.GetHashCode() : 0) * 397) ^ (this._Properties != null ? this._Properties.GetHashCode() : 0); } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> public override string ToString() { var str = this._Class + " { "; foreach (var property in this._Properties) { str += string.Format("{0}={1}; ", property.Key, property.Value); } return str + " }"; } } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Zenject.ReflectionBaking.Mono.Cecil.PE; using Zenject.ReflectionBaking.Mono.Collections.Generic; using RVA = System.UInt32; namespace Zenject.ReflectionBaking.Mono.Cecil.Cil { sealed class CodeReader : ByteBuffer { readonly internal MetadataReader reader; int start; Section code_section; MethodDefinition method; MethodBody body; int Offset { get { return base.position - start; } } public CodeReader (Section section, MetadataReader reader) : base (section.Data) { this.code_section = section; this.reader = reader; } public MethodBody ReadMethodBody (MethodDefinition method) { this.method = method; this.body = new MethodBody (method); reader.context = method; ReadMethodBody (); return this.body; } public void MoveTo (int rva) { if (!IsInSection (rva)) { code_section = reader.image.GetSectionAtVirtualAddress ((uint) rva); Reset (code_section.Data); } base.position = rva - (int) code_section.VirtualAddress; } bool IsInSection (int rva) { return code_section.VirtualAddress <= rva && rva < code_section.VirtualAddress + code_section.SizeOfRawData; } void ReadMethodBody () { MoveTo (method.RVA); var flags = ReadByte (); switch (flags & 0x3) { case 0x2: // tiny body.code_size = flags >> 2; body.MaxStackSize = 8; ReadCode (); break; case 0x3: // fat base.position--; ReadFatMethod (); break; default: throw new InvalidOperationException (); } var symbol_reader = reader.module.symbol_reader; if (symbol_reader != null) { var instructions = body.Instructions; symbol_reader.Read (body, offset => GetInstruction (instructions, offset)); } } void ReadFatMethod () { var flags = ReadUInt16 (); body.max_stack_size = ReadUInt16 (); body.code_size = (int) ReadUInt32 (); body.local_var_token = new MetadataToken (ReadUInt32 ()); body.init_locals = (flags & 0x10) != 0; if (body.local_var_token.RID != 0) body.variables = ReadVariables (body.local_var_token); ReadCode (); if ((flags & 0x8) != 0) ReadSection (); } public VariableDefinitionCollection ReadVariables (MetadataToken local_var_token) { var position = reader.position; var variables = reader.ReadVariables (local_var_token); reader.position = position; return variables; } void ReadCode () { start = position; var code_size = body.code_size; if (code_size < 0 || buffer.Length <= (uint) (code_size + position)) code_size = 0; var end = start + code_size; var instructions = body.instructions = new InstructionCollection ((code_size + 1) / 2); while (position < end) { var offset = base.position - start; var opcode = ReadOpCode (); var current = new Instruction (offset, opcode); if (opcode.OperandType != OperandType.InlineNone) current.operand = ReadOperand (current); instructions.Add (current); } ResolveBranches (instructions); } OpCode ReadOpCode () { var il_opcode = ReadByte (); return il_opcode != 0xfe ? OpCodes.OneByteOpCode [il_opcode] : OpCodes.TwoBytesOpCode [ReadByte ()]; } object ReadOperand (Instruction instruction) { switch (instruction.opcode.OperandType) { case OperandType.InlineSwitch: var length = ReadInt32 (); var base_offset = Offset + (4 * length); var branches = new int [length]; for (int i = 0; i < length; i++) branches [i] = base_offset + ReadInt32 (); return branches; case OperandType.ShortInlineBrTarget: return ReadSByte () + Offset; case OperandType.InlineBrTarget: return ReadInt32 () + Offset; case OperandType.ShortInlineI: if (instruction.opcode == OpCodes.Ldc_I4_S) return ReadSByte (); return ReadByte (); case OperandType.InlineI: return ReadInt32 (); case OperandType.ShortInlineR: return ReadSingle (); case OperandType.InlineR: return ReadDouble (); case OperandType.InlineI8: return ReadInt64 (); case OperandType.ShortInlineVar: return GetVariable (ReadByte ()); case OperandType.InlineVar: return GetVariable (ReadUInt16 ()); case OperandType.ShortInlineArg: return GetParameter (ReadByte ()); case OperandType.InlineArg: return GetParameter (ReadUInt16 ()); case OperandType.InlineSig: return GetCallSite (ReadToken ()); case OperandType.InlineString: return GetString (ReadToken ()); case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineMethod: case OperandType.InlineField: return reader.LookupToken (ReadToken ()); default: throw new NotSupportedException (); } } public string GetString (MetadataToken token) { return reader.image.UserStringHeap.Read (token.RID); } public ParameterDefinition GetParameter (int index) { return body.GetParameter (index); } public VariableDefinition GetVariable (int index) { return body.GetVariable (index); } public CallSite GetCallSite (MetadataToken token) { return reader.ReadCallSite (token); } void ResolveBranches (Collection<Instruction> instructions) { var items = instructions.items; var size = instructions.size; for (int i = 0; i < size; i++) { var instruction = items [i]; switch (instruction.opcode.OperandType) { case OperandType.ShortInlineBrTarget: case OperandType.InlineBrTarget: instruction.operand = GetInstruction ((int) instruction.operand); break; case OperandType.InlineSwitch: var offsets = (int []) instruction.operand; var branches = new Instruction [offsets.Length]; for (int j = 0; j < offsets.Length; j++) branches [j] = GetInstruction (offsets [j]); instruction.operand = branches; break; } } } Instruction GetInstruction (int offset) { return GetInstruction (body.Instructions, offset); } static Instruction GetInstruction (Collection<Instruction> instructions, int offset) { var size = instructions.size; var items = instructions.items; if (offset < 0 || offset > items [size - 1].offset) return null; int min = 0; int max = size - 1; while (min <= max) { int mid = min + ((max - min) / 2); var instruction = items [mid]; var instruction_offset = instruction.offset; if (offset == instruction_offset) return instruction; if (offset < instruction_offset) max = mid - 1; else min = mid + 1; } return null; } void ReadSection () { Align (4); const byte fat_format = 0x40; const byte more_sects = 0x80; var flags = ReadByte (); if ((flags & fat_format) == 0) ReadSmallSection (); else ReadFatSection (); if ((flags & more_sects) != 0) ReadSection (); } void ReadSmallSection () { var count = ReadByte () / 12; Advance (2); ReadExceptionHandlers ( count, () => (int) ReadUInt16 (), () => (int) ReadByte ()); } void ReadFatSection () { position--; var count = (ReadInt32 () >> 8) / 24; ReadExceptionHandlers ( count, ReadInt32, ReadInt32); } // inline ? void ReadExceptionHandlers (int count, Func<int> read_entry, Func<int> read_length) { for (int i = 0; i < count; i++) { var handler = new ExceptionHandler ( (ExceptionHandlerType) (read_entry () & 0x7)); handler.TryStart = GetInstruction (read_entry ()); handler.TryEnd = GetInstruction (handler.TryStart.Offset + read_length ()); handler.HandlerStart = GetInstruction (read_entry ()); handler.HandlerEnd = GetInstruction (handler.HandlerStart.Offset + read_length ()); ReadExceptionHandlerSpecific (handler); this.body.ExceptionHandlers.Add (handler); } } void ReadExceptionHandlerSpecific (ExceptionHandler handler) { switch (handler.HandlerType) { case ExceptionHandlerType.Catch: handler.CatchType = (TypeReference) reader.LookupToken (ReadToken ()); break; case ExceptionHandlerType.Filter: handler.FilterStart = GetInstruction (ReadInt32 ()); break; default: Advance (4); break; } } void Align (int align) { align--; Advance (((position + align) & ~align) - position); } public MetadataToken ReadToken () { return new MetadataToken (ReadUInt32 ()); } #if !READ_ONLY public ByteBuffer PatchRawMethodBody (MethodDefinition method, CodeWriter writer, out MethodSymbols symbols) { var buffer = new ByteBuffer (); symbols = new MethodSymbols (method.Name); this.method = method; reader.context = method; MoveTo (method.RVA); var flags = ReadByte (); MetadataToken local_var_token; switch (flags & 0x3) { case 0x2: // tiny buffer.WriteByte (flags); local_var_token = MetadataToken.Zero; symbols.code_size = flags >> 2; PatchRawCode (buffer, symbols.code_size, writer); break; case 0x3: // fat base.position--; PatchRawFatMethod (buffer, symbols, writer, out local_var_token); break; default: throw new NotSupportedException (); } var symbol_reader = reader.module.symbol_reader; if (symbol_reader != null && writer.metadata.write_symbols) { symbols.method_token = GetOriginalToken (writer.metadata, method); symbols.local_var_token = local_var_token; symbol_reader.Read (symbols); } return buffer; } void PatchRawFatMethod (ByteBuffer buffer, MethodSymbols symbols, CodeWriter writer, out MetadataToken local_var_token) { var flags = ReadUInt16 (); buffer.WriteUInt16 (flags); buffer.WriteUInt16 (ReadUInt16 ()); symbols.code_size = ReadInt32 (); buffer.WriteInt32 (symbols.code_size); local_var_token = ReadToken (); if (local_var_token.RID > 0) { var variables = symbols.variables = ReadVariables (local_var_token); buffer.WriteUInt32 (variables != null ? writer.GetStandAloneSignature (symbols.variables).ToUInt32 () : 0); } else buffer.WriteUInt32 (0); PatchRawCode (buffer, symbols.code_size, writer); if ((flags & 0x8) != 0) PatchRawSection (buffer, writer.metadata); } static MetadataToken GetOriginalToken (MetadataBuilder metadata, MethodDefinition method) { MetadataToken original; if (metadata.TryGetOriginalMethodToken (method.token, out original)) return original; return MetadataToken.Zero; } void PatchRawCode (ByteBuffer buffer, int code_size, CodeWriter writer) { var metadata = writer.metadata; buffer.WriteBytes (ReadBytes (code_size)); var end = buffer.position; buffer.position -= code_size; while (buffer.position < end) { OpCode opcode; var il_opcode = buffer.ReadByte (); if (il_opcode != 0xfe) { opcode = OpCodes.OneByteOpCode [il_opcode]; } else { var il_opcode2 = buffer.ReadByte (); opcode = OpCodes.TwoBytesOpCode [il_opcode2]; } switch (opcode.OperandType) { case OperandType.ShortInlineI: case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineVar: case OperandType.ShortInlineArg: buffer.position += 1; break; case OperandType.InlineVar: case OperandType.InlineArg: buffer.position += 2; break; case OperandType.InlineBrTarget: case OperandType.ShortInlineR: case OperandType.InlineI: buffer.position += 4; break; case OperandType.InlineI8: case OperandType.InlineR: buffer.position += 8; break; case OperandType.InlineSwitch: var length = buffer.ReadInt32 (); buffer.position += length * 4; break; case OperandType.InlineString: var @string = GetString (new MetadataToken (buffer.ReadUInt32 ())); buffer.position -= 4; buffer.WriteUInt32 ( new MetadataToken ( TokenType.String, metadata.user_string_heap.GetStringIndex (@string)).ToUInt32 ()); break; case OperandType.InlineSig: var call_site = GetCallSite (new MetadataToken (buffer.ReadUInt32 ())); buffer.position -= 4; buffer.WriteUInt32 (writer.GetStandAloneSignature (call_site).ToUInt32 ()); break; case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineMethod: case OperandType.InlineField: var provider = reader.LookupToken (new MetadataToken (buffer.ReadUInt32 ())); buffer.position -= 4; buffer.WriteUInt32 (metadata.LookupToken (provider).ToUInt32 ()); break; } } } void PatchRawSection (ByteBuffer buffer, MetadataBuilder metadata) { var position = base.position; Align (4); buffer.WriteBytes (base.position - position); const byte fat_format = 0x40; const byte more_sects = 0x80; var flags = ReadByte (); if ((flags & fat_format) == 0) { buffer.WriteByte (flags); PatchRawSmallSection (buffer, metadata); } else PatchRawFatSection (buffer, metadata); if ((flags & more_sects) != 0) PatchRawSection (buffer, metadata); } void PatchRawSmallSection (ByteBuffer buffer, MetadataBuilder metadata) { var length = ReadByte (); buffer.WriteByte (length); Advance (2); buffer.WriteUInt16 (0); var count = length / 12; PatchRawExceptionHandlers (buffer, metadata, count, false); } void PatchRawFatSection (ByteBuffer buffer, MetadataBuilder metadata) { position--; var length = ReadInt32 (); buffer.WriteInt32 (length); var count = (length >> 8) / 24; PatchRawExceptionHandlers (buffer, metadata, count, true); } void PatchRawExceptionHandlers (ByteBuffer buffer, MetadataBuilder metadata, int count, bool fat_entry) { const int fat_entry_size = 16; const int small_entry_size = 6; for (int i = 0; i < count; i++) { ExceptionHandlerType handler_type; if (fat_entry) { var type = ReadUInt32 (); handler_type = (ExceptionHandlerType) (type & 0x7); buffer.WriteUInt32 (type); } else { var type = ReadUInt16 (); handler_type = (ExceptionHandlerType) (type & 0x7); buffer.WriteUInt16 (type); } buffer.WriteBytes (ReadBytes (fat_entry ? fat_entry_size : small_entry_size)); switch (handler_type) { case ExceptionHandlerType.Catch: var exception = reader.LookupToken (ReadToken ()); buffer.WriteUInt32 (metadata.LookupToken (exception).ToUInt32 ()); break; default: buffer.WriteUInt32 (ReadUInt32 ()); break; } } } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; using Internal.NativeCrypto; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Internal.Cryptography.Pal { /// <summary> /// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it /// easier to split the class into abstract and implementation classes if desired.) /// </summary> internal sealed partial class X509Pal : IX509Pal { public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages) { unsafe { ushort keyUsagesAsShort = (ushort)keyUsages; CRYPT_BIT_BLOB blob = new CRYPT_BIT_BLOB() { cbData = 2, pbData = (byte*)&keyUsagesAsShort, cUnusedBits = 0, }; return Interop.crypt32.EncodeObject(CryptDecodeObjectStructType.X509_KEY_USAGE, &blob); } } public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages) { unsafe { uint keyUsagesAsUint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_KEY_USAGE, delegate (void* pvDecoded) { CRYPT_BIT_BLOB* pBlob = (CRYPT_BIT_BLOB*)pvDecoded; keyUsagesAsUint = 0; if (pBlob->pbData != null) { keyUsagesAsUint = *(uint*)(pBlob->pbData); } } ); keyUsages = (X509KeyUsageFlags)keyUsagesAsUint; } } public bool SupportsLegacyBasicConstraintsExtension { get { return true; } } public byte[] EncodeX509BasicConstraints2Extension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { unsafe { CERT_BASIC_CONSTRAINTS2_INFO constraintsInfo = new CERT_BASIC_CONSTRAINTS2_INFO() { fCA = certificateAuthority ? 1 : 0, fPathLenConstraint = hasPathLengthConstraint ? 1 : 0, dwPathLenConstraint = pathLengthConstraint, }; return Interop.crypt32.EncodeObject(Oids.BasicConstraints2, &constraintsInfo); } } public void DecodeX509BasicConstraintsExtension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { unsafe { bool localCertificateAuthority = false; bool localHasPathLengthConstraint = false; int localPathLengthConstraint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS, delegate (void* pvDecoded) { CERT_BASIC_CONSTRAINTS_INFO* pBasicConstraints = (CERT_BASIC_CONSTRAINTS_INFO*)pvDecoded; localCertificateAuthority = (pBasicConstraints->SubjectType.pbData[0] & CERT_BASIC_CONSTRAINTS_INFO.CERT_CA_SUBJECT_FLAG) != 0; localHasPathLengthConstraint = pBasicConstraints->fPathLenConstraint != 0; localPathLengthConstraint = pBasicConstraints->dwPathLenConstraint; } ); certificateAuthority = localCertificateAuthority; hasPathLengthConstraint = localHasPathLengthConstraint; pathLengthConstraint = localPathLengthConstraint; } } public void DecodeX509BasicConstraints2Extension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { unsafe { bool localCertificateAuthority = false; bool localHasPathLengthConstraint = false; int localPathLengthConstraint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS2, delegate (void* pvDecoded) { CERT_BASIC_CONSTRAINTS2_INFO* pBasicConstraints2 = (CERT_BASIC_CONSTRAINTS2_INFO*)pvDecoded; localCertificateAuthority = pBasicConstraints2->fCA != 0; localHasPathLengthConstraint = pBasicConstraints2->fPathLenConstraint != 0; localPathLengthConstraint = pBasicConstraints2->dwPathLenConstraint; } ); certificateAuthority = localCertificateAuthority; hasPathLengthConstraint = localHasPathLengthConstraint; pathLengthConstraint = localPathLengthConstraint; } } public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages) { int numUsages; using (SafeHandle usagesSafeHandle = usages.ToLpstrArray(out numUsages)) { unsafe { CERT_ENHKEY_USAGE enhKeyUsage = new CERT_ENHKEY_USAGE() { cUsageIdentifier = numUsages, rgpszUsageIdentifier = (IntPtr*)(usagesSafeHandle.DangerousGetHandle()), }; return Interop.crypt32.EncodeObject(Oids.EnhancedKeyUsage, &enhKeyUsage); } } } public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection localUsages = new OidCollection(); unsafe { encoded.DecodeObject( CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE, delegate (void* pvDecoded) { CERT_ENHKEY_USAGE* pEnhKeyUsage = (CERT_ENHKEY_USAGE*)pvDecoded; int count = pEnhKeyUsage->cUsageIdentifier; for (int i = 0; i < count; i++) { IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i]; String oidValue = Marshal.PtrToStringAnsi(oidValuePointer); Oid oid = new Oid(oidValue); localUsages.Add(oid); } } ); } usages = localUsages; return; } public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier) { unsafe { fixed (byte* pSubkectKeyIdentifier = subjectKeyIdentifier) { CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(subjectKeyIdentifier.Length, pSubkectKeyIdentifier); return Interop.crypt32.EncodeObject(Oids.SubjectKeyIdentifier, &blob); } } } public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier) { unsafe { byte[] localSubjectKeyIdentifier = null; encoded.DecodeObject( Oids.SubjectKeyIdentifier, delegate (void* pvDecoded) { CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded; localSubjectKeyIdentifier = pBlob->ToByteArray(); } ); subjectKeyIdentifier = localSubjectKeyIdentifier; } } public byte[] ComputeCapiSha1OfPublicKey(PublicKey key) { unsafe { fixed (byte* pszOidValue = key.Oid.ValueAsAscii()) { byte[] encodedParameters = key.EncodedParameters.RawData; fixed (byte* pEncodedParameters = encodedParameters) { byte[] encodedKeyValue = key.EncodedKeyValue.RawData; fixed (byte* pEncodedKeyValue = encodedKeyValue) { CERT_PUBLIC_KEY_INFO publicKeyInfo = new CERT_PUBLIC_KEY_INFO() { Algorithm = new CRYPT_ALGORITHM_IDENTIFIER() { pszObjId = new IntPtr(pszOidValue), Parameters = new CRYPTOAPI_BLOB(encodedParameters.Length, pEncodedParameters), }, PublicKey = new CRYPT_BIT_BLOB() { cbData = encodedKeyValue.Length, pbData = pEncodedKeyValue, cUnusedBits = 0, }, }; int cb = 20; byte[] buffer = new byte[cb]; if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (cb < buffer.Length) { byte[] newBuffer = new byte[cb]; Array.Copy(buffer, 0, newBuffer, 0, cb); buffer = newBuffer; } return buffer; } } } } } } }