context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedBillingSetupServiceClientTest { [Category("Autogenerated")][Test] public void GetBillingSetupRequestObject() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup response = client.GetBillingSetup(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBillingSetupRequestObjectAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BillingSetup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup responseCallSettings = await client.GetBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BillingSetup responseCancellationToken = await client.GetBillingSetupAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetBillingSetup() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup response = client.GetBillingSetup(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBillingSetupAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BillingSetup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup responseCallSettings = await client.GetBillingSetupAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BillingSetup responseCancellationToken = await client.GetBillingSetupAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetBillingSetupResourceNames() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup response = client.GetBillingSetup(request.ResourceNameAsBillingSetupName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetBillingSetupResourceNamesAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); GetBillingSetupRequest request = new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), }; gagvr::BillingSetup expectedResponse = new gagvr::BillingSetup { ResourceNameAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), Status = gagve::BillingSetupStatusEnum.Types.BillingSetupStatus.Pending, StartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, PaymentsAccountInfo = new gagvr::BillingSetup.Types.PaymentsAccountInfo(), EndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, Id = -6774108720365892680L, StartDateTime = "start_date_timeea924cb1", EndDateTime = "end_date_timea95363f3", PaymentsAccountAsPaymentsAccountName = gagvr::PaymentsAccountName.FromCustomerPaymentsAccount("[CUSTOMER_ID]", "[PAYMENTS_ACCOUNT_ID]"), }; mockGrpcClient.Setup(x => x.GetBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BillingSetup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); gagvr::BillingSetup responseCallSettings = await client.GetBillingSetupAsync(request.ResourceNameAsBillingSetupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::BillingSetup responseCancellationToken = await client.GetBillingSetupAsync(request.ResourceNameAsBillingSetupName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateBillingSetupRequestObject() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); MutateBillingSetupRequest request = new MutateBillingSetupRequest { CustomerId = "customer_id3b3724cb", Operation = new BillingSetupOperation(), }; MutateBillingSetupResponse expectedResponse = new MutateBillingSetupResponse { Result = new MutateBillingSetupResult(), }; mockGrpcClient.Setup(x => x.MutateBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); MutateBillingSetupResponse response = client.MutateBillingSetup(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateBillingSetupRequestObjectAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); MutateBillingSetupRequest request = new MutateBillingSetupRequest { CustomerId = "customer_id3b3724cb", Operation = new BillingSetupOperation(), }; MutateBillingSetupResponse expectedResponse = new MutateBillingSetupResponse { Result = new MutateBillingSetupResult(), }; mockGrpcClient.Setup(x => x.MutateBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateBillingSetupResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); MutateBillingSetupResponse responseCallSettings = await client.MutateBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateBillingSetupResponse responseCancellationToken = await client.MutateBillingSetupAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateBillingSetup() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); MutateBillingSetupRequest request = new MutateBillingSetupRequest { CustomerId = "customer_id3b3724cb", Operation = new BillingSetupOperation(), }; MutateBillingSetupResponse expectedResponse = new MutateBillingSetupResponse { Result = new MutateBillingSetupResult(), }; mockGrpcClient.Setup(x => x.MutateBillingSetup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); MutateBillingSetupResponse response = client.MutateBillingSetup(request.CustomerId, request.Operation); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateBillingSetupAsync() { moq::Mock<BillingSetupService.BillingSetupServiceClient> mockGrpcClient = new moq::Mock<BillingSetupService.BillingSetupServiceClient>(moq::MockBehavior.Strict); MutateBillingSetupRequest request = new MutateBillingSetupRequest { CustomerId = "customer_id3b3724cb", Operation = new BillingSetupOperation(), }; MutateBillingSetupResponse expectedResponse = new MutateBillingSetupResponse { Result = new MutateBillingSetupResult(), }; mockGrpcClient.Setup(x => x.MutateBillingSetupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateBillingSetupResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); BillingSetupServiceClient client = new BillingSetupServiceClientImpl(mockGrpcClient.Object, null); MutateBillingSetupResponse responseCallSettings = await client.MutateBillingSetupAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateBillingSetupResponse responseCancellationToken = await client.MutateBillingSetupAsync(request.CustomerId, request.Operation, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion License using System.Linq; /* * Original implementation is contributed by Alexey Yakovlev (yallie) */ namespace Irony.Parsing { using ConditionalEntry = ConditionalParserAction.ConditionalEntry; public class TokenPreviewHint : GrammarHint { public int MaxPreviewTokens = 1000; private PreferredActionType actionType; private StringSet beforeStrings = new StringSet(); private TerminalSet beforeTerminals = new TerminalSet(); private string description; private string firstString; private Terminal firstTerminal; public TokenPreviewHint(PreferredActionType actionType, string thisSymbol, params string[] comesBefore) { this.actionType = actionType; this.firstString = thisSymbol; this.beforeStrings.AddRange(comesBefore); } public TokenPreviewHint(PreferredActionType actionType, Terminal thisTerm, params Terminal[] comesBefore) { this.actionType = actionType; this.firstTerminal = thisTerm; this.beforeTerminals.UnionWith(comesBefore); } public override void Apply(LanguageData language, Construction.LRItem owner) { var state = owner.State; if (!state.BuilderData.IsInadequate) // The state is adequate, we don't need to do anything return; var conflicts = state.BuilderData.Conflicts; // Note that we remove lookaheads from the state conflicts set at the end of this method - to let parser builder know // that this conflict is taken care of. // On the other hand we may call this method multiple times for different LRItems if we have multiple hints in the same state. // Since we remove lookahead from conflicts on the first call, on the consequitive calls it will not be a conflict - // but we still need to add a new conditional entry to a conditional parser action for this lookahead. // Thus we process the lookahead anyway, even if it is not a conflict. // if (conflicts.Count == 0) return; -- this is a wrong thing to do switch (this.actionType) { case PreferredActionType.Reduce: { if (!owner.Core.IsFinal) return; // It is reduce action; find lookaheads in conflict var lkhs = owner.Lookaheads; if (lkhs.Count == 0) // If no conflicts then nothing to do return; var reduceAction = new ReduceParserAction(owner.Core.Production); var reduceCondEntry = new ConditionalEntry(this.CheckCondition, reduceAction, this.description); foreach (var lkh in lkhs) { this.AddConditionalEntry(state, lkh, reduceCondEntry); if (conflicts.Contains(lkh)) conflicts.Remove(lkh); } } break; case PreferredActionType.Shift: { var curr = owner.Core.Current as Terminal; if (curr == null) // It is either reduce item, or curr is a NonTerminal - we cannot shift it return; var shiftAction = new ShiftParserAction(owner); var shiftCondEntry = new ConditionalEntry(this.CheckCondition, shiftAction, this.description); this.AddConditionalEntry(state, curr, shiftCondEntry); if (conflicts.Contains(curr)) conflicts.Remove(curr); } break; } } public override void Init(GrammarData grammarData) { base.Init(grammarData); // Convert strings to terminals, if needed this.firstTerminal = this.firstTerminal ?? this.Grammar.ToTerm(this.firstString); if (this.beforeStrings.Count > 0) { // SL pukes here, it does not support co/contravariance in full, we have to do it long way foreach (var s in this.beforeStrings) { this.beforeTerminals.Add(this.Grammar.ToTerm(s)); } } // Build description var beforeTerms = string.Join(" ", this.beforeTerminals.Select(t => t.Name)); this.description = string.Format("{0} if {1} comes before {2}.", this.actionType, this.firstTerminal.Name, beforeTerms); } public override string ToString() { if (this.description == null) this.description = this.actionType.ToString() + " if ..."; return this.description; } /// <summary> /// Check if there is an action already in state for this term; if yes, and it is Conditional action, /// then simply add an extra conditional entry to it. If an action does not exist, or it is not conditional, /// create new conditional action for this term. /// </summary> /// <param name="state"></param> /// <param name="term"></param> /// <param name="entry"></param> private void AddConditionalEntry(ParserState state, BnfTerm term, ConditionalEntry entry) { ParserAction oldAction; ConditionalParserAction condAction = null; if (state.Actions.TryGetValue(term, out oldAction)) condAction = oldAction as ConditionalParserAction; if (condAction == null) { // There's no old action, or it is not conditional; create new conditional action condAction = new ConditionalParserAction(); condAction.DefaultAction = oldAction; state.Actions[term] = condAction; } condAction.ConditionalEntries.Add(entry); if (condAction.DefaultAction == null) condAction.DefaultAction = this.FindDefaultAction(state, term); if (condAction.DefaultAction == null) // If still no action, then use the cond. action as default. condAction.DefaultAction = entry.Action; } private bool CheckCondition(ParsingContext context) { var scanner = context.Parser.Scanner; try { var eof = this.Grammar.Eof; var count = 0; scanner.BeginPreview(); var token = scanner.GetToken(); while (token != null && token.Terminal != eof) { if (token.Terminal == this.firstTerminal) // Found! return true; if (this.beforeTerminals.Contains(token.Terminal)) return false; if (++count > this.MaxPreviewTokens && this.MaxPreviewTokens > 0) return false; token = scanner.GetToken(); } return false; } finally { scanner.EndPreview(true); } } /// <summary> /// Find an LR item without hints compatible with term (either shift on term or reduce with term as lookahead); /// this item without hints would become our default. We assume that other items have hints, and when conditions /// on all these hints fail, we chose this remaining item without hints. /// </summary> /// <param name="state"></param> /// <param name="term"></param> /// <returns></returns> private ParserAction FindDefaultAction(ParserState state, BnfTerm term) { // First check reduce items var reduceItems = state.BuilderData.ReduceItems.SelectByLookahead(term as Terminal); foreach (var item in reduceItems) { if (item.Core.Hints.Count == 0) return ReduceParserAction.Create(item.Core.Production); } var shiftItem = state.BuilderData.ShiftItems.SelectByCurrent(term).FirstOrDefault(); if (shiftItem != null) return new ShiftParserAction(shiftItem); // If everything failed, returned first reduce item return null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using NeuralNetwork; using JustGestures.TypeOfAction; using JustGestures.Languages; namespace JustGestures.GUI { using ControlItems; public partial class Form_modifyGesture : Form { GesturesCollection gestures; MyGesture[] modifiedGestures; MyGesture tempGesture; UC_openPrgFld uc_openPrgFld; UC_name uc_name; UC_gesture uc_gesture; UC_customKeystrokes uc_customKeystrokes; UC_selectProgram uc_selectProgram; UC_plainText uc_plainText; UC_clipboard uc_clipboard; UC_mailSearchWeb uc_mailSearchWeb; bool canContinue; MyNeuralNetwork m_network; MyNeuralNetwork m_networkOriginal; bool m_appMode = false; public Form_modifyGesture() { InitializeComponent(); this.Icon = Properties.Resources.modify16; canContinue = true; #region User Control Declaration uc_name = new UC_name(); uc_gesture = new UC_gesture(); uc_openPrgFld = new UC_openPrgFld(); uc_mailSearchWeb = new UC_mailSearchWeb(); uc_customKeystrokes = new UC_customKeystrokes(); uc_selectProgram = new UC_selectProgram(); uc_plainText = new UC_plainText(); uc_clipboard = new UC_clipboard(); List<BaseActionControl> uc_controls = new List<BaseActionControl>(); uc_controls.Add(uc_name); uc_controls.Add(uc_gesture); uc_controls.Add(uc_openPrgFld); uc_controls.Add(uc_customKeystrokes); uc_controls.Add(uc_selectProgram); uc_controls.Add(uc_plainText); uc_controls.Add(uc_clipboard); uc_controls.Add(uc_mailSearchWeb); foreach (BaseActionControl uc_control in uc_controls) { uc_control.CanContinue += new BaseActionControl.DlgCanContinue(Continue); uc_control.ChangeInfoText += new BaseActionControl.DlgChangeInfoText(uC_infoIcon1.ChangeInfoText); uc_control.Dock = DockStyle.Fill; } #endregion User Control Declaration btn_cancel.Text = Translation.Btn_cancel; btn_ok.Text = Translation.Btn_ok; } public bool AppMode { set { m_appMode = value; } } public GesturesCollection Gestures { get { return gestures; } set { gestures = value; } } public MyGesture[] ModifiedGestures { get { return modifiedGestures; } set { modifiedGestures = value; } } public MyNeuralNetwork MyNNetwork { get { return m_network; } set { m_network = value; } } public MyNeuralNetwork MyNNetworkOriginal { set { m_networkOriginal = value; } } public void Continue(bool _continue) { canContinue = _continue; if (canContinue) { btn_ok.Enabled = true; } else { btn_ok.Enabled = false; } } private void Form_modifyGesture_Load(object sender, EventArgs e) { if (!m_appMode) { this.Size = new Size(680, 580); this.Text = modifiedGestures[0].Caption; bool singleGesture = true; bool singleCurve = true; tempGesture = new MyGesture(modifiedGestures[0]); if (modifiedGestures.Length > 1) { this.Text = Translation.GetText("MG_multiple"); //Modify Multiple Gestures singleGesture = false; string curve = modifiedGestures[0].Activator.ID; foreach (MyGesture gest in modifiedGestures) if (curve != gest.Activator.ID) singleCurve = false; if (!singleCurve) { tempGesture = new MyGesture(string.Empty); tempGesture.Action = modifiedGestures[0].Action; } } uc_openPrgFld.TempGesture = tempGesture; uc_mailSearchWeb.TempGesture = tempGesture; uc_gesture.MyNNetwork = m_network; uc_gesture.MyNNetworkOriginal = m_networkOriginal; uc_gesture.TempGesture = tempGesture; uc_name.TempGesture = tempGesture; uc_gesture.Gestures = gestures; uc_name.Gestures = gestures; uc_customKeystrokes.TempGesture = tempGesture; uc_plainText.TempGesture = tempGesture; uc_clipboard.TempGesture = tempGesture; uc_clipboard.Gestures = gestures; if (singleGesture) { TabPage tP_gesture = new TabPage(); tP_gesture.Text = Translation.GetText("MG_tP_gesture"); // "Gesture"; tP_gesture.Controls.Add(uc_gesture); TabPage tP_name = new TabPage(); tP_name.Text = Translation.GetText("MG_tP_name"); // "Name" tP_name.Controls.Add(uc_name); TabPage tp_mailSearchWeb = new TabPage(); TabPage tP_openPrgFld = new TabPage(); TabPage tP_customKeystrokes = new TabPage(); switch (tempGesture.Action.Name) { case WindowsShell.SHELL_START_PRG: tP_openPrgFld.Text = Translation.GetText("MG_tP_program"); // "Program"; tP_openPrgFld.Controls.Add(uc_openPrgFld); tabControl1.TabPages.Add(tP_openPrgFld); break; case WindowsShell.SHELL_OPEN_FLDR: tP_openPrgFld.Text = Translation.GetText("MG_tP_folder"); // "Folder"; tP_openPrgFld.Controls.Add(uc_openPrgFld); tabControl1.TabPages.Add(tP_openPrgFld); break; case InternetOptions.INTERNET_SEARCH_WEB: case InternetOptions.INTERNET_OPEN_WEBSITE: tp_mailSearchWeb.Text = Translation.GetText("MG_tP_url"); // "Website Url"; tp_mailSearchWeb.Controls.Add(uc_mailSearchWeb); tabControl1.TabPages.Add(tp_mailSearchWeb); break; case InternetOptions.INTERNET_SEND_EMAIL: tp_mailSearchWeb.Text = Translation.GetText("MG_tP_mail"); // "E-mail"; tp_mailSearchWeb.Controls.Add(uc_mailSearchWeb); tabControl1.TabPages.Add(tp_mailSearchWeb); break; case InternetOptions.INTERNET_TAB_NEW: case InternetOptions.INTERNET_TAB_CLOSE: case InternetOptions.INTERNET_TAB_REOPEN: case KeystrokesOptions.KEYSTROKES_ZOOM_IN: case KeystrokesOptions.KEYSTROKES_ZOOM_OUT: case KeystrokesOptions.KEYSTROKES_SYSTEM_COPY: case KeystrokesOptions.KEYSTROKES_SYSTEM_CUT: case KeystrokesOptions.KEYSTROKES_SYSTEM_PASTE: case KeystrokesOptions.KEYSTROKES_CUSTOM: case ExtrasOptions.EXTRAS_CUSTOM_WHEEL_BTN: case ExtrasOptions.EXTRAS_TAB_SWITCHER: case ExtrasOptions.EXTRAS_TASK_SWITCHER: case ExtrasOptions.EXTRAS_ZOOM: tP_customKeystrokes.Text = Translation.GetText("MG_tP_customKeystrokes"); // "Custom Keystrokes"; tP_customKeystrokes.Controls.Add(uc_customKeystrokes); tabControl1.TabPages.Add(tP_customKeystrokes); break; case KeystrokesOptions.KEYSTROKES_PRIVATE_COPY_TEXT: case KeystrokesOptions.KEYSTROKES_PRIVATE_PASTE_TEXT: TabPage tP_clipboard = new TabPage(); tP_clipboard.Text = Translation.GetText("MG_tP_privateClipboard"); // "Private Clipboard"; tP_clipboard.Controls.Add(uc_clipboard); tabControl1.TabPages.Add(tP_clipboard); break; case KeystrokesOptions.KEYSTROKES_PLAIN_TEXT: TabPage tP_plainText = new TabPage(); tP_plainText.Text = Translation.GetText("MG_tP_plainText"); // "Plain Text"; tP_plainText.Controls.Add(uc_plainText); tabControl1.TabPages.Add(tP_plainText); break; } tabControl1.TabPages.Add(tP_gesture); tabControl1.TabPages.Add(tP_name); } else { TabPage tP_gesture = new TabPage(); tP_gesture.Text = Translation.GetText("MG_tP_gesture"); //"Gesture" tP_gesture.Controls.Add(uc_gesture); tabControl1.TabPages.Add(tP_gesture); } } else { this.Text = modifiedGestures[0].Caption; this.Size = new Size(530, 430); tempGesture = new MyGesture(modifiedGestures[0]); uc_selectProgram.TempGesture = tempGesture; TabPage tP_application = new TabPage(); tP_application.Text = Translation.GetText("MG_tP_application"); // "Application" tP_application.Controls.Add(uc_selectProgram); tabControl1.TabPages.Add(tP_application); } foreach (TabPage page in tabControl1.TabPages) page.Padding = new Padding(15, 10, 15, 10); } private void tabControl1_Deselecting(object sender, TabControlCancelEventArgs e) { if (!canContinue) { e.Cancel = true; MessageBox.Show(this, Translation.GetText("MG_msgText_validProps"), Translation.Text_warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void btn_ok_Click(object sender, EventArgs e) { if (!m_appMode) m_network = uc_gesture.MyNNetwork; if (modifiedGestures.Length == 1) { modifiedGestures[0].SetItem(tempGesture); modifiedGestures[0].Activator = tempGesture.Activator; modifiedGestures[0].Action = tempGesture.Action; if (modifiedGestures[0].IsImplicitOnly) modifiedGestures[0].ExecutionType = ExecuteType.Implicit; if (!m_appMode) modifiedGestures[0].ItemPos = -1; } else { foreach (MyGesture gest in modifiedGestures) { gest.Activator = tempGesture.Activator; gest.ItemPos = -1; } } } private void Form_modifyGesture_FormClosing(object sender, FormClosingEventArgs e) { if (!m_appMode) { uc_gesture.OnClosingForm(this.DialogResult); uc_openPrgFld.OnClosingForm(); uc_mailSearchWeb.OnClosingForm(); } else uc_selectProgram.OnClosingForm(); } private void panel_down_Paint(object sender, PaintEventArgs e) { Graphics g = panel_down.CreateGraphics(); g.DrawLine(new Pen(Brushes.Gray, 1), 0, 2, panel_down.Width, 2); g.DrawLine(new Pen(Brushes.White, 1), 0, 1, panel_down.Width, 1); g.Dispose(); } } }
// 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.Threading; using System.Reflection; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Tests; using Xunit; namespace System.Tests { public static partial class LazyTests { [Fact] public static void Ctor() { var lazyString = new Lazy<string>(); VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false); var lazyObject = new Lazy<int>(); VerifyLazy(lazyObject, 0, hasValue: true, isValueCreated: false); } [Theory] [InlineData(true)] [InlineData(false)] public static void Ctor_Bool(bool isThreadSafe) { var lazyString = new Lazy<string>(isThreadSafe); VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false); } [Fact] public static void Ctor_ValueFactory() { var lazyString = new Lazy<string>(() => "foo"); VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false); var lazyInt = new Lazy<int>(() => 1); VerifyLazy(lazyInt, 1, hasValue: true, isValueCreated: false); } [Fact] public static void Ctor_ValueFactory_NullValueFactory_ThrowsArguentNullException() { Assert.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null)); // Value factory is null } [Fact] public static void Ctor_LazyThreadSafetyMode() { var lazyString = new Lazy<string>(LazyThreadSafetyMode.PublicationOnly); VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false); } [Fact] public static void Ctor_LazyThreadSafetyMode_InvalidMode_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(LazyThreadSafetyMode.None - 1)); // Invalid thread saftety mode Assert.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(LazyThreadSafetyMode.ExecutionAndPublication + 1)); // Invalid thread saftety mode } [Theory] [InlineData(true)] [InlineData(false)] public static void Ctor_ValueFactor_Bool(bool isThreadSafe) { var lazyString = new Lazy<string>(() => "foo", isThreadSafe); VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false); } [Fact] public static void Ctor_ValueFactory_Bool_NullValueFactory_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null, false)); // Value factory is null } [Fact] public static void Ctor_ValueFactor_LazyThreadSafetyMode() { var lazyString = new Lazy<string>(() => "foo", LazyThreadSafetyMode.PublicationOnly); VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false); var lazyInt = new Lazy<int>(() => 1, LazyThreadSafetyMode.PublicationOnly); VerifyLazy(lazyInt, 1, hasValue: true, isValueCreated: false); } [Fact] public static void Ctor_ValueFactor_LazyThreadSafetyMode_Invalid() { Assert.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null, LazyThreadSafetyMode.PublicationOnly)); // Value factory is null Assert.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(() => "foo", LazyThreadSafetyMode.None - 1)); // Invalid thread saftety mode Assert.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(() => "foof", LazyThreadSafetyMode.ExecutionAndPublication + 1)); // Invalid thread saftety mode } [Fact] public static void ToString_DoesntForceAllocation() { var lazy = new Lazy<object>(() => 1); Assert.NotEqual("1", lazy.ToString()); Assert.False(lazy.IsValueCreated); object tmp = lazy.Value; Assert.Equal("1", lazy.ToString()); } private static void Value_Invalid_Impl<T>(ref Lazy<T> x, Lazy<T> lazy) { x = lazy; Assert.Throws<InvalidOperationException>(() => lazy.Value); } [Fact] public static void Value_Invalid() { Lazy<int> x = null; Func<int> f = () => x.Value; Value_Invalid_Impl(ref x, new Lazy<int>(f)); Value_Invalid_Impl(ref x, new Lazy<int>(f, true)); Value_Invalid_Impl(ref x, new Lazy<int>(f, false)); Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.ExecutionAndPublication)); Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.None)); // When used with LazyThreadSafetyMode.PublicationOnly this causes a stack overflow // Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.PublicationOnly)); } public class InitiallyExceptionThrowingCtor { public static int counter = 0; public static int getValue() { if (++counter < 5) throw new Exception(); else return counter; } public int Value { get; } public InitiallyExceptionThrowingCtor() { Value = getValue(); } } public static IEnumerable<object[]> Ctor_ExceptionRecovery_MemberData() { yield return new object[] { new Lazy<InitiallyExceptionThrowingCtor>(), 5 }; yield return new object[] { new Lazy<InitiallyExceptionThrowingCtor>(true), 5 }; yield return new object[] { new Lazy<InitiallyExceptionThrowingCtor>(false), 5 }; yield return new object[] { new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.ExecutionAndPublication), 5 }; yield return new object[] { new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.None), 5 }; yield return new object[] { new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.PublicationOnly), 5 }; } [Theory] [MemberData(nameof(Ctor_ExceptionRecovery_MemberData))] public static void Ctor_ExceptionRecovery(Lazy<InitiallyExceptionThrowingCtor> lazy, int expected) { InitiallyExceptionThrowingCtor.counter = 0; InitiallyExceptionThrowingCtor result = null; for (var i = 0; i < 10; ++i) { try { result = lazy.Value; } catch (Exception) { } } Assert.Equal(result.Value, expected); } private static void Value_ExceptionRecovery_IntImpl(Lazy<int> lazy, ref int counter, int expected) { counter = 0; int result = 0; for (var i = 0; i < 10; ++i) { try { result = lazy.Value; } catch (Exception) { } } Assert.Equal(result, expected); } private static void Value_ExceptionRecovery_StringImpl(Lazy<string> lazy, ref int counter, string expected) { counter = 0; var result = default(string); for (var i = 0; i < 10; ++i) { try { result = lazy.Value; } catch (Exception) { } } Assert.Equal(expected, result); } [Fact] public static void Value_ExceptionRecovery() { int counter = 0; // set in test function var fint = new Func<int> (() => { if (++counter < 5) throw new Exception(); else return counter; }); var fobj = new Func<string>(() => { if (++counter < 5) throw new Exception(); else return counter.ToString(); }); Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, true), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, false), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.ExecutionAndPublication), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.None), ref counter, 0); Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.PublicationOnly), ref counter, 5); Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, true), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, false), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.ExecutionAndPublication), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.None), ref counter, null); Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.PublicationOnly), ref counter, 5.ToString()); } class MyException : Exception { public int Value { get; } public MyException(int value) { Value = value; } } public class ExceptionInCtor { public ExceptionInCtor() : this(99) { } public ExceptionInCtor(int value) { throw new MyException(value); } } public static IEnumerable<object[]> Value_Func_Exception_MemberData() { yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, true) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, false) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.ExecutionAndPublication) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.None) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.PublicationOnly) }; } [Theory] [MemberData(nameof(Value_Func_Exception_MemberData))] public static void Value_Func_Exception(Lazy<int> lazy) { Assert.Throws<MyException>(() => lazy.Value); } public static IEnumerable<object[]> Value_FuncCtor_Exception_MemberData() { yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99)) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), true) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), false) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.ExecutionAndPublication) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.None) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.PublicationOnly) }; } [Theory] [MemberData(nameof(Value_FuncCtor_Exception_MemberData))] public static void Value_FuncCtor_Exception(Lazy<ExceptionInCtor> lazy) { Assert.Throws<MyException>(() => lazy.Value); } public static IEnumerable<object[]> Value_TargetInvocationException_MemberData() { yield return new object[] { new Lazy<ExceptionInCtor>() }; yield return new object[] { new Lazy<ExceptionInCtor>(true) }; yield return new object[] { new Lazy<ExceptionInCtor>(false) }; yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.ExecutionAndPublication) }; yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.None) }; yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.PublicationOnly) }; } [Theory] [MemberData(nameof(Value_TargetInvocationException_MemberData))] public static void Value_TargetInvocationException(Lazy<ExceptionInCtor> lazy) { Assert.Throws<TargetInvocationException>(() => lazy.Value); } public static IEnumerable<object[]> Exceptions_Func_Idempotent_MemberData() { yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, true) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, false) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.ExecutionAndPublication) }; yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.None) }; } [Theory] [MemberData(nameof(Exceptions_Func_Idempotent_MemberData))] public static void Exceptions_Func_Idempotent(Lazy<int> x) { var e = Assert.ThrowsAny<Exception>(() => x.Value); Assert.Same(e, Assert.ThrowsAny<Exception>(() => x.Value)); } public static IEnumerable<object[]> Exceptions_Ctor_Idempotent_MemberData() { yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99)) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), true) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), false) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.ExecutionAndPublication) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.None) }; } [Theory] [MemberData(nameof(Exceptions_Ctor_Idempotent_MemberData))] public static void Exceptions_Ctor_Idempotent(Lazy<ExceptionInCtor> x) { var e = Assert.ThrowsAny<Exception>(() => x.Value); Assert.Same(e, Assert.ThrowsAny<Exception>(() => x.Value)); } public static IEnumerable<object[]> Exceptions_Func_NotIdempotent_MemberData() { yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.PublicationOnly) }; } public static IEnumerable<object[]> Exceptions_Ctor_NotIdempotent_MemberData() { yield return new object[] { new Lazy<ExceptionInCtor>() }; yield return new object[] { new Lazy<ExceptionInCtor>(true) }; yield return new object[] { new Lazy<ExceptionInCtor>(false) }; yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.ExecutionAndPublication) }; yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.None) }; yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.PublicationOnly) }; yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.PublicationOnly) }; } [Theory] [MemberData(nameof(Exceptions_Func_NotIdempotent_MemberData))] public static void Exceptions_Func_NotIdempotent(Lazy<int> x) { var e = Assert.ThrowsAny<Exception>(() => x.Value); Assert.NotSame(e, Assert.ThrowsAny<Exception>(() => x.Value)); } [Theory] [MemberData(nameof(Exceptions_Ctor_NotIdempotent_MemberData))] public static void Exceptions_Ctor_NotIdempotent(Lazy<ExceptionInCtor> x) { var e = Assert.ThrowsAny<Exception>(() => x.Value); Assert.NotSame(e, Assert.ThrowsAny<Exception>(() => x.Value)); } [Fact] public static void Serialization_ValueType() { var stream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(stream, new Lazy<int>(() => 42)); stream.Seek(0, SeekOrigin.Begin); var fortytwo = (Lazy<int>)formatter.Deserialize(stream); Assert.True(fortytwo.IsValueCreated); Assert.Equal(fortytwo.Value, 42); } [Fact] public static void Serialization_RefType() { var stream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(stream, new Lazy<string>(() => "42")); stream.Seek(0, SeekOrigin.Begin); var x = BinaryFormatterHelpers.Clone(new object()); var fortytwo = (Lazy<string>)formatter.Deserialize(stream); Assert.True(fortytwo.IsValueCreated); Assert.Equal(fortytwo.Value, "42"); } [Theory] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] [InlineData(LazyThreadSafetyMode.None)] public static void Value_ThrownException_DoesntCreateValue(LazyThreadSafetyMode mode) { var lazy = new Lazy<string>(() => { throw new DivideByZeroException(); }, mode); Exception exception1 = Assert.Throws<DivideByZeroException>(() => lazy.Value); Exception exception2 = Assert.Throws<DivideByZeroException>(() => lazy.Value); Assert.Same(exception1, exception2); Assert.False(lazy.IsValueCreated); } [Fact] public static void Value_ThrownException_DoesntCreateValue_PublicationOnly() { var lazy = new Lazy<string>(() => { throw new DivideByZeroException(); }, LazyThreadSafetyMode.PublicationOnly); Exception exception1 = Assert.Throws<DivideByZeroException>(() => lazy.Value); Exception exception2 = Assert.Throws<DivideByZeroException>(() => lazy.Value); Assert.NotSame(exception1, exception2); Assert.False(lazy.IsValueCreated); } [Fact] public static void EnsureInitalized_SimpleRefTypes() { var hdcTemplate = new HasDefaultCtor(); string strTemplate = "foo"; // Activator.CreateInstance (uninitialized). HasDefaultCtor a = null; Assert.NotNull(LazyInitializer.EnsureInitialized(ref a)); Assert.Same(a, LazyInitializer.EnsureInitialized(ref a)); Assert.NotNull(a); // Activator.CreateInstance (already initialized). HasDefaultCtor b = hdcTemplate; Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b)); Assert.Same(b, LazyInitializer.EnsureInitialized(ref b)); Assert.Equal(hdcTemplate, b); // Func based initialization (uninitialized). string c = null; Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, () => strTemplate)); Assert.Same(c, LazyInitializer.EnsureInitialized(ref c)); Assert.Equal(strTemplate, c); // Func based initialization (already initialized). string d = strTemplate; Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, () => strTemplate + "bar")); Assert.Same(d, LazyInitializer.EnsureInitialized(ref d)); Assert.Equal(strTemplate, d); } [Fact] public static void EnsureInitalized_SimpleRefTypes_Invalid() { // Func based initialization (nulls not permitted). string e = null; Assert.Throws<InvalidOperationException>(() => LazyInitializer.EnsureInitialized(ref e, () => null)); // Activator.CreateInstance (for a type without a default ctor). NoDefaultCtor ndc = null; Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized(ref ndc)); } [Fact] public static void EnsureInitialized_ComplexRefTypes() { string strTemplate = "foo"; var hdcTemplate = new HasDefaultCtor(); // Activator.CreateInstance (uninitialized). HasDefaultCtor a = null; bool aInit = false; object aLock = null; Assert.NotNull(LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock)); Assert.NotNull(a); // Activator.CreateInstance (already initialized). HasDefaultCtor b = hdcTemplate; bool bInit = true; object bLock = null; Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock)); Assert.Equal(hdcTemplate, b); // Func based initialization (uninitialized). string c = null; bool cInit = false; object cLock = null; Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => strTemplate)); Assert.Equal(strTemplate, c); // Func based initialization (already initialized). string d = strTemplate; bool dInit = true; object dLock = null; Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => strTemplate + "bar")); Assert.Equal(strTemplate, d); // Func based initialization (nulls *ARE* permitted). string e = null; bool einit = false; object elock = null; int initCount = 0; Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return null; })); Assert.Null(e); Assert.Equal(1, initCount); Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return null; })); } [Fact] public static void EnsureInitalized_ComplexRefTypes_Invalid() { // Activator.CreateInstance (for a type without a default ctor). NoDefaultCtor ndc = null; bool ndcInit = false; object ndcLock = null; Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized(ref ndc, ref ndcInit, ref ndcLock)); } [Fact] public static void LazyInitializerComplexValueTypes() { var empty = new LIX(); var template = new LIX(33); // Activator.CreateInstance (uninitialized). LIX a = default(LIX); bool aInit = false; object aLock = null; LIX ensuredValA = LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock); Assert.Equal(empty, ensuredValA); Assert.Equal(empty, a); // Activator.CreateInstance (already initialized). LIX b = template; bool bInit = true; object bLock = null; LIX ensuredValB = LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock); Assert.Equal(template, ensuredValB); Assert.Equal(template, b); // Func based initialization (uninitialized). LIX c = default(LIX); bool cInit = false; object cLock = null; LIX ensuredValC = LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => template); Assert.Equal(template, c); Assert.Equal(template, ensuredValC); // Func based initialization (already initialized). LIX d = template; bool dInit = true; object dLock = null; LIX template2 = new LIX(template.f * 2); LIX ensuredValD = LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => template2); Assert.Equal(template, ensuredValD); Assert.Equal(template, d); } private static void VerifyLazy<T>(Lazy<T> lazy, T expectedValue, bool hasValue, bool isValueCreated) { Assert.Equal(isValueCreated, lazy.IsValueCreated); if (hasValue) { Assert.Equal(expectedValue, lazy.Value); Assert.True(lazy.IsValueCreated); } else { Assert.Throws<MissingMemberException>(() => lazy.Value); // Value could not be created Assert.False(lazy.IsValueCreated); } } private class HasDefaultCtor { } private class NoDefaultCtor { public NoDefaultCtor(int x) { } } private struct LIX { public int f; public LIX(int f) { this.f = f; } public override bool Equals(object other) => other is LIX && ((LIX)other).f == f; public override int GetHashCode() => f.GetHashCode(); public override string ToString() => "LIX<" + f + ">"; } } }
namespace VulkanCore { /// <summary> /// Vulkan structure types. /// </summary> public enum StructureType { ApplicationInfo = 0, InstanceCreateInfo = 1, DeviceQueueCreateInfo = 2, DeviceCreateInfo = 3, SubmitInfo = 4, MemoryAllocateInfo = 5, MappedMemoryRange = 6, BindSparseInfo = 7, FenceCreateInfo = 8, SemaphoreCreateInfo = 9, EventCreateInfo = 10, QueryPoolCreateInfo = 11, BufferCreateInfo = 12, BufferViewCreateInfo = 13, ImageCreateInfo = 14, ImageViewCreateInfo = 15, ShaderModuleCreateInfo = 16, PipelineCacheCreateInfo = 17, PipelineShaderStageCreateInfo = 18, PipelineVertexInputStateCreateInfo = 19, PipelineInputAssemblyStateCreateInfo = 20, PipelineTessellationStateCreateInfo = 21, PipelineViewportStateCreateInfo = 22, PipelineRasterizationStateCreateInfo = 23, PipelineMultisampleStateCreateInfo = 24, PipelineDepthStencilStateCreateInfo = 25, PipelineColorBlendStateCreateInfo = 26, PipelineDynamicStateCreateInfo = 27, GraphicsPipelineCreateInfo = 28, ComputePipelineCreateInfo = 29, PipelineLayoutCreateInfo = 30, SamplerCreateInfo = 31, DescriptorSetLayoutCreateInfo = 32, DescriptorPoolCreateInfo = 33, DescriptorSetAllocateInfo = 34, WriteDescriptorSet = 35, CopyDescriptorSet = 36, FramebufferCreateInfo = 37, RenderPassCreateInfo = 38, CommandPoolCreateInfo = 39, CommandBufferAllocateInfo = 40, CommandBufferInheritanceInfo = 41, CommandBufferBeginInfo = 42, RenderPassBeginInfo = 43, BufferMemoryBarrier = 44, ImageMemoryBarrier = 45, MemoryBarrier = 46, /// <summary> /// Reserved for internal use by the loader, layers, and ICDs. /// </summary> LoaderInstanceCreateInfo = 47, /// <summary> /// Reserved for internal use by the loader, layers, and ICDs. /// </summary> LoaderDeviceCreateInfo = 48, SwapchainCreateInfoKhr = 1000001000, PresentInfoKhr = 1000001001, DisplayModeCreateInfoKhr = 1000002000, DisplaySurfaceCreateInfoKhr = 1000002001, DisplayPresentInfoKhr = 1000003000, XlibSurfaceCreateInfoKhr = 1000004000, XcbSurfaceCreateInfoKhr = 1000005000, WaylandSurfaceCreateInfoKhr = 1000006000, MirSurfaceCreateInfoKhr = 1000007000, AndroidSurfaceCreateInfoKhr = 1000008000, Win32SurfaceCreateInfoKhr = 1000009000, NativeBufferAndroid = 1000010000, DebugReportCallbackCreateInfoExt = 1000011000, PipelineRasterizationStateRasterizationOrderAmd = 1000018000, DebugMarkerObjectNameInfoExt = 1000022000, DebugMarkerObjectTagInfoExt = 1000022001, DebugMarkerMarkerInfoExt = 1000022002, DedicatedAllocationImageCreateInfoNV = 1000026000, DedicatedAllocationBufferCreateInfoNV = 1000026001, DedicatedAllocationMemoryAllocateInfoNV = 1000026002, TextureLodGatherFormatPropertiesAmd = 1000041000, RenderPassMultiviewCreateInfoKhx = 1000053000, PhysicalDeviceMultiviewFeaturesKhx = 1000053001, PhysicalDeviceMultiviewPropertiesKhx = 1000053002, ExternalMemoryImageCreateInfoNV = 1000056000, ExportMemoryAllocateInfoNV = 1000056001, ImportMemoryWin32HandleInfoNV = 1000057000, ExportMemoryWin32HandleInfoNV = 1000057001, Win32KeyedMutexAcquireReleaseInfoNV = 1000058000, PhysicalDeviceFeatures2Khr = 1000059000, PhysicalDeviceProperties2Khr = 1000059001, FormatProperties2Khr = 1000059002, ImageFormatProperties2Khr = 1000059003, PhysicalDeviceImageFormatInfo2Khr = 1000059004, QueueFamilyProperties2Khr = 1000059005, PhysicalDeviceMemoryProperties2Khr = 1000059006, SparseImageFormatProperties2Khr = 1000059007, PhysicalDeviceSparseImageFormatInfo2Khr = 1000059008, MemoryAllocateFlagsInfoKhx = 1000060000, DeviceGroupRenderPassBeginInfoKhx = 1000060003, DeviceGroupCommandBufferBeginInfoKhx = 1000060004, DeviceGroupSubmitInfoKhx = 1000060005, DeviceGroupBindSparseInfoKhx = 1000060006, AcquireNextImageInfoKhx = 1000060010, ValidationFlagsExt = 1000061000, VISurfaceCreateInfoNN = 1000062000, PhysicalDeviceGroupPropertiesKhx = 1000070000, DeviceGroupDeviceCreateInfoKhx = 1000070001, PhysicalDeviceExternalImageFormatInfoKhr = 1000071000, ExternalImageFormatPropertiesKhr = 1000071001, PhysicalDeviceExternalBufferInfoKhr = 1000071002, ExternalBufferPropertiesKhr = 1000071003, PhysicalDeviceIdPropertiesKhr = 1000071004, ExternalMemoryBufferCreateInfoKhr = 1000072000, ExternalMemoryImageCreateInfoKhr = 1000072001, ExportMemoryAllocateInfoKhr = 1000072002, ImportMemoryWin32HandleInfoKhr = 1000073000, ExportMemoryWin32HandleInfoKhr = 1000073001, MemoryWin32HandlePropertiesKhr = 1000073002, MemoryGetWin32HandleInfoKhr = 1000073003, ImportMemoryFdInfoKhr = 1000074000, MemoryFdPropertiesKhr = 1000074001, MemoryGetFdInfoKhr = 1000074002, Win32KeyedMutexAcquireReleaseInfoKhr = 1000075000, PhysicalDeviceExternalSemaphoreInfoKhr = 1000076000, ExternalSemaphorePropertiesKhr = 1000076001, ExportSemaphoreCreateInfoKhr = 1000077000, ImportSemaphoreWin32HandleInfoKhr = 1000078000, ExportSemaphoreWin32HandleInfoKhr = 1000078001, D3D12FenceSubmitInfoKhr = 1000078002, SemaphoreGetWin32HandleInfoKhr = 1000078003, ImportSemaphoreFdInfoKhr = 1000079000, SemaphoreGetFdInfoKhr = 1000079001, PhysicalDevicePushDescriptorPropertiesKhr = 1000080000, PhysicalDevice16BitStorageFeaturesKhr = 1000083000, PresentRegionsKhr = 1000084000, DescriptorUpdateTemplateCreateInfoKhr = 1000085000, ObjectTableCreateInfoNvx = 1000086000, IndirectCommandsLayoutCreateInfoNvx = 1000086001, CmdProcessCommandsInfoNvx = 1000086002, CmdReserveSpaceForCommandsInfoNvx = 1000086003, DeviceGeneratedCommandsLimitsNvx = 1000086004, DeviceGeneratedCommandsFeaturesNvx = 1000086005, PipelineViewportWScalingStateCreateInfoNV = 1000087000, SurfaceCapabilities2Ext = 1000090000, DisplayPowerInfoExt = 1000091000, DeviceEventInfoExt = 1000091001, DisplayEventInfoExt = 1000091002, SwapchainCounterCreateInfoExt = 1000091003, PresentTimesInfoGoogle = 1000092000, PhysicalDeviceMultiviewPerViewAttributesPropertiesNvx = 1000097000, PipelineViewportSwizzleStateCreateInfoNV = 1000098000, PhysicalDeviceDiscardRectanglePropertiesExt = 1000099000, PipelineDiscardRectangleStateCreateInfoExt = 1000099001, PhysicalDeviceConservativeRasterizationPropertiesExt = 1000101000, PipelineRasterizationConservativeStateCreateInfoExt = 1000101001, HdrMetadataExt = 1000105000, SharedPresentSurfaceCapabilitiesKhr = 1000111000, PhysicalDeviceExternalFenceInfoKhr = 1000112000, ExternalFencePropertiesKhr = 1000112001, ExportFenceCreateInfoKhr = 1000113000, ImportFenceWin32HandleInfoKhr = 1000114000, ExportFenceWin32HandleInfoKhr = 1000114001, FenceGetWin32HandleInfoKhr = 1000114002, ImportFenceFdInfoKhr = 1000115000, FenceGetFdInfoKhr = 1000115001, PhysicalDevicePointClippingPropertiesKhr = 1000117000, RenderPassInputAttachmentAspectCreateInfoKhr = 1000117001, ImageViewUsageCreateInfoKhr = 1000117002, PipelineTessellationDomainOriginStateCreateInfoKhr = 1000117003, PhysicalDeviceSurfaceInfo2Khr = 1000119000, SurfaceCapabilities2Khr = 1000119001, SurfaceFormat2Khr = 1000119002, PhysicalDeviceVariablePointerFeaturesKhr = 1000120000, IOSSurfaceCreateInfoMvk = 1000122000, MacOSSurfaceCreateInfoMvk = 1000123000, MemoryDedicatedRequirementsKhr = 1000127000, MemoryDedicatedAllocateInfoKhr = 1000127001, PhysicalDeviceSamplerFilterMinmaxPropertiesExt = 1000130000, SamplerReductionModeCreateInfoExt = 1000130001, SampleLocationsInfoExt = 1000143000, RenderPassSampleLocationsBeginInfoExt = 1000143001, PipelineSampleLocationsStateCreateInfoExt = 1000143002, PhysicalDeviceSampleLocationsPropertiesExt = 1000143003, MultisamplePropertiesExt = 1000143004, BufferMemoryRequirementsInfo2Khr = 1000146000, ImageMemoryRequirementsInfo2Khr = 1000146001, ImageSparseMemoryRequirementsInfo2Khr = 1000146002, MemoryRequirements2Khr = 1000146003, SparseImageMemoryRequirements2Khr = 1000146004, ImageFormatListCreateInfoKhr = 1000147000, PhysicalDeviceBlendOperationAdvancedFeaturesExt = 1000148000, PhysicalDeviceBlendOperationAdvancedPropertiesExt = 1000148001, PipelineColorBlendAdvancedStateCreateInfoExt = 1000148002, PipelineCoverageToColorStateCreateInfoNV = 1000149000, PipelineCoverageModulationStateCreateInfoNV = 1000152000, SamplerYcbcrConversionCreateInfoKhr = 1000156000, SamplerYcbcrConversionInfoKhr = 1000156001, BindImagePlaneMemoryInfoKhr = 1000156002, ImagePlaneMemoryRequirementsInfoKhr = 1000156003, PhysicalDeviceSamplerYcbcrConversionFeaturesKhr = 1000156004, SamplerYcbcrConversionImageFormatPropertiesKhr = 1000156005, BindBufferMemoryInfoKhr = 1000157000, BindImageMemoryInfoKhr = 1000157001, ValidationCacheCreateInfoExt = 1000160000, ShaderModuleValidationCacheCreateInfoExt = 1000160001, // TODO: The entries below are for compatibility reasons. // TODO: Remove when their corresponding structures have been removed from vk.xml. DeviceGroupPresentCapabilitiesKhx = 1000060007, ImageSwapchainCreateInfoKhx = 1000060008, BindImageMemorySwapchainInfoKhx = 1000060009, DeviceGroupPresentInfoKhx = 1000060011, DeviceGroupSwapchainCreateInfoKhx = 1000060012, DeviceQueueGlobalPriorityCreateInfoExt = 1000174000, ImportMemoryHostPointerInfoExt = 1000178000, MemoryHostPointerPropertiesExt = 1000178001, PhysicalDeviceExternalMemoryHostPropertiesExt = 1000178002 } }
/* The MIT License (MIT) Copyright (c) 2016 Roaring Fangs Entertainment 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 RoaringFangs.Attributes; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace RoaringFangs.FSM { [Serializable] public abstract class StateMachine<TStateEnum> : MonoBehaviour, IStateManager<TStateEnum>, ISerializationCallbackReceiver where TStateEnum : struct, IConvertible { private static readonly Dictionary<TStateEnum, string> EnumLUT; private static readonly Dictionary<string, TStateEnum> StateTypeLUT; public static IEnumerable<TStateEnum> GetEnums() { return Enum.GetValues(typeof(TStateEnum)).Cast<TStateEnum>(); } static StateMachine() { var enums = GetEnums(); EnumLUT = enums.ToDictionary(e => e, e => e.ToString()); StateTypeLUT = enums.ToDictionary(e => e.ToString(), e => e); } [SerializeField, AutoProperty("StateProvider")] private MonoBehaviour _StateProviderBehavior; public StateProvider<TStateEnum> StateProvider { get { return _StateProviderBehavior as StateProvider<TStateEnum>; } protected set { _StateProviderBehavior = value; } } #region Serialization [SerializeField] private List<StateInfoEntry> _StateInfoList; [SerializeField] private List<TransitionEntry> _TransitionsList; // Converting between sealed types... private static TStateEnum ParseEnum(string enum_str) { try { return (TStateEnum)Enum.Parse(typeof(TStateEnum), enum_str); } catch (ArgumentException) { return default(TStateEnum); } } public void OnBeforeSerialize() { _StateInfoList = States .Select( e => new StateInfoEntry( e.Key.ToString(), e.Value)) .ToList(); _TransitionsList = Transitions .SelectMany( e => e.Value, (from, to) => new TransitionEntry(EnumLUT[from.Key], EnumLUT[to])) .ToList(); } public void OnAfterDeserialize() { if (_StateInfoList != null) { States = _StateInfoList .ToDictionary( e => ParseEnum(e.State), e => (StateInfo)e.Info); } if (_TransitionsList != null) { var transitions_valid = _TransitionsList .Where(e => e.From != null && e.To != null) .Select(e => new KeyValuePair<TStateEnum, TStateEnum>(StateTypeLUT[e.From], StateTypeLUT[e.To])) .ToArray(); var transitions_lookup = transitions_valid .ToLookup(e => e.Key, e => e.Value); var transitions_distinct = transitions_valid .Select(e => e.Key) .Distinct() .ToArray(); Transitions = transitions_distinct .ToDictionary( e => e, e => new HashSet<TStateEnum>(transitions_lookup[e])); } } #endregion Serialization [SerializeField] private StateChangeEvent _BeforeStateChange; public StateChangeEvent BeforeStateChange { get { return _BeforeStateChange; } protected set { _BeforeStateChange = value; } } [SerializeField] private StateChangeEvent _AfterStateChange; public StateChangeEvent AfterStateChange { get { return _AfterStateChange; } protected set { _AfterStateChange = value; } } [SerializeField] private StateInfo _AnyState = new StateInfo(); public StateInfo AnyState { get { return _AnyState; } protected set { _AnyState = value; } } private Dictionary<TStateEnum, StateInfo> _States; protected Dictionary<TStateEnum, StateInfo> States { get { if (_States == null) { _States = new Dictionary<TStateEnum, StateInfo>(); } if (_States.Count != GetEnums().LongCount()) { PopulateStates(ref _States); } return _States; } set { _States = value; } } public StateInfo GetStateInfo(TStateEnum state) { return States[state]; } public StateInfo this[TStateEnum state] { get { return GetStateInfo(state); } } protected void SetStateInfo(TStateEnum state, StateInfo info) { States[state] = info; } private void PopulateStates(ref Dictionary<TStateEnum, StateInfo> state_table) { var enum_values = Enum.GetValues(typeof(TStateEnum)).Cast<TStateEnum>(); foreach (TStateEnum state in enum_values) { if (!state_table.ContainsKey(state)) state_table[state] = new StateInfo(); } } private Dictionary<TStateEnum, HashSet<TStateEnum>> _Transitions; protected Dictionary<TStateEnum, HashSet<TStateEnum>> Transitions { get { if (_Transitions == null) { _Transitions = new Dictionary<TStateEnum, HashSet<TStateEnum>>(); } return _Transitions; } set { _Transitions = value; } } public void AddTransition(TStateEnum from, TStateEnum to) { if (!Transitions.ContainsKey(from)) Transitions[from] = new HashSet<TStateEnum>(); Transitions[from].Add(to); } public void RemoveTransition(TStateEnum from, TStateEnum to) { if (Transitions.ContainsKey(from)) { Transitions[from].Remove(to); if (Transitions[from].Count == 0) Transitions.Remove(from); } } public IEnumerable<TStateEnum> GetNextStates { get { return Transitions[CurrentState]; } } [SerializeField, AutoProperty] private TStateEnum _CurrentState; public virtual TStateEnum CurrentState { get { if (StateProvider != null) _CurrentState = StateProvider.CurrentState; return _CurrentState; } set { #if UNITY_EDITOR if (Application.isPlaying) { #endif var from_state = CurrentState; ExitState(from_state, value); if (StateProvider != null) StateProvider.CurrentState = value; _CurrentState = value; EnterState(from_state, value); #if UNITY_EDITOR } else { if (StateProvider != null) StateProvider.CurrentState = value; _CurrentState = value; } #endif } } private void ExitState(TStateEnum from_state, TStateEnum to_state) { Debug.Assert(CurrentState.Equals(from_state), "Transitioned from non-current state"); var destinations = Transitions[from_state]; if (!destinations.Contains(to_state)) throw new InvalidOperationException( "Cannot transition from state " + from_state + " to state " + to_state); OnBeforeStateChange(); OnStateExit(from_state, to_state); } private void EnterState(TStateEnum from_state, TStateEnum to_state) { OnStateEntry(from_state, to_state); OnAfterStateChange(); } protected virtual void OnBeforeStateChange() { BeforeStateChange.Invoke(this); } protected virtual void OnStateExit(TStateEnum from_state, TStateEnum? to_state) { StateInfo current_state_info = GetStateInfo(from_state); current_state_info.Exit.Invoke(this); AnyState.Exit.Invoke(this); } protected virtual void OnStateEntry(TStateEnum? from_state, TStateEnum to_state) { StateInfo next_state_info = GetStateInfo(to_state); next_state_info.Entry.Invoke(this); AnyState.Entry.Invoke(this); } protected virtual void OnAfterStateChange() { AfterStateChange.Invoke(this); } private bool _DidStart = false; protected virtual void Awake() { PopulateStates(ref _States); } protected virtual void Start() { _DidStart = true; OnBeforeStateChange(); OnStateEntry(null, CurrentState); OnAfterStateChange(); } protected virtual void OnDestroy() { OnBeforeStateChange(); OnStateExit(CurrentState, null); OnAfterStateChange(); } public virtual void Update() { StateInfo active_state_info; active_state_info = GetStateInfo(CurrentState); active_state_info.While.Invoke(this); AnyState.While.Invoke(this); } } }
using JetBrains.Annotations; using ModestTree; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Zenject { public static class TypeAnalyzer { static Dictionary<Type, ZenjectTypeInfo> _typeInfo = new Dictionary<Type, ZenjectTypeInfo>(); public static ZenjectTypeInfo GetInfo<T>() { return GetInfo(typeof(T)); } public static ZenjectTypeInfo GetInfo(Type type) { #if UNITY_EDITOR using (ProfileBlock.Start("Zenject Reflection")) #endif { Assert.That(type.IsStatic() || !type.IsAbstract(), "Tried to analyze abstract type '{0}'. This is not currently allowed.", type); ZenjectTypeInfo info; #if ZEN_MULTITHREADING lock (_typeInfo) #endif { if (!_typeInfo.TryGetValue(type, out info)) { info = CreateTypeInfo(type); _typeInfo.Add(type, info); } } return info; } } static ZenjectTypeInfo CreateTypeInfo(Type type) { var constructor = GetInjectConstructor(type); return new ZenjectTypeInfo( type, GetPostInjectMethods(type), constructor, GetFieldInjectables(type).ToList(), GetPropertyInjectables(type).ToList(), GetConstructorInjectables(type, constructor).ToList()); } static IEnumerable<InjectableInfo> GetConstructorInjectables(Type parentType, ConstructorInfo constructorInfo) { if (constructorInfo == null) { return Enumerable.Empty<InjectableInfo>(); } return constructorInfo.GetParameters().Select( paramInfo => CreateInjectableInfoForParam(parentType, paramInfo)); } static InjectableInfo CreateInjectableInfoForParam( Type parentType, ParameterInfo paramInfo) { var injectAttributes = paramInfo.AllAttributes<InjectAttributeBase>().ToList(); Assert.That(injectAttributes.Count <= 1, "Found multiple 'Inject' attributes on type parameter '{0}' of type '{1}'. Parameter should only have one", paramInfo.Name, parentType); var injectAttr = injectAttributes.SingleOrDefault(); object identifier = null; bool isOptional = false; InjectSources sourceType = InjectSources.Any; if (injectAttr != null) { identifier = injectAttr.Id; isOptional = injectAttr.Optional; sourceType = injectAttr.Source; } bool isOptionalWithADefaultValue = (paramInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault; return new InjectableInfo( isOptionalWithADefaultValue || isOptional, identifier, paramInfo.Name, paramInfo.ParameterType, parentType, null, isOptionalWithADefaultValue ? paramInfo.DefaultValue : null, sourceType); } static List<PostInjectableInfo> GetPostInjectMethods(Type type) { // Note that unlike with fields and properties we use GetCustomAttributes // This is so that we can ignore inherited attributes, which is necessary // otherwise a base class method marked with [Inject] would cause all overridden // derived methods to be added as well var methods = type.GetAllMethods() .Where(x => x.GetCustomAttributes(typeof(InjectAttribute), false).Any()).ToList(); var heirarchyList = type.Yield().Concat(type.GetParentTypes()).Reverse().ToList(); // Order by base classes first // This is how constructors work so it makes more sense var values = methods.OrderBy(x => heirarchyList.IndexOf(x.DeclaringType)); var postInjectInfos = new List<PostInjectableInfo>(); foreach (var methodInfo in values) { var paramsInfo = methodInfo.GetParameters(); var injectAttr = methodInfo.AllAttributes<InjectAttribute>().Single(); Assert.That(!injectAttr.Optional && injectAttr.Id == null && injectAttr.Source == InjectSources.Any, "Parameters of InjectAttribute do not apply to constructors and methods"); postInjectInfos.Add( new PostInjectableInfo( methodInfo, paramsInfo.Select(paramInfo => CreateInjectableInfoForParam(type, paramInfo)).ToList())); } return postInjectInfos; } static IEnumerable<InjectableInfo> GetPropertyInjectables(Type type) { var propInfos = type.GetAllProperties() .Where(x => x.HasAttribute(typeof(InjectAttributeBase))); foreach (var propInfo in propInfos) { yield return CreateForMember(propInfo, type); } } static IEnumerable<InjectableInfo> GetFieldInjectables(Type type) { var fieldInfos = type.GetAllFields() .Where(x => x.HasAttribute(typeof(InjectAttributeBase))); foreach (var fieldInfo in fieldInfos) { yield return CreateForMember(fieldInfo, type); } } private static IEnumerable<FieldInfo> GetAllFields(Type t, BindingFlags flags) { if (t == null) return Enumerable.Empty<FieldInfo>(); return t.GetFields(flags).Concat(GetAllFields(t.BaseType, flags)).Distinct(); } [NotNull] private static Action<object, object> GetOnlyPropertySetter( [NotNull] Type parentType, [NotNull] string propertyName) { if (parentType == null) throw new ArgumentNullException("parentType"); if (string.IsNullOrEmpty(propertyName)) throw new ArgumentException("Value cannot be null or empty.", "propertyName"); var allFields = GetAllFields(parentType, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); var writeableFields = allFields.Where(f => f.Name == string.Format("<{0}>k__BackingField", propertyName)).ToList(); if (!writeableFields.Any()) { throw new ZenjectException(string.Format( "Can't find backing field for get only property {0} on {1}.\r\n{2}", propertyName, parentType.FullName,string.Join(";", allFields.Select(f => f.Name).ToArray()))); } return ( injectable, value ) => writeableFields.ForEach( f => f.SetValue(injectable, value) ); } static InjectableInfo CreateForMember(MemberInfo memInfo, Type parentType) { var injectAttributes = memInfo.AllAttributes<InjectAttributeBase>().ToList(); Assert.That(injectAttributes.Count <= 1, "Found multiple 'Inject' attributes on type field '{0}' of type '{1}'. Field should only container one Inject attribute", memInfo.Name, parentType); var injectAttr = injectAttributes.SingleOrDefault(); object identifier = null; bool isOptional = false; InjectSources sourceType = InjectSources.Any; if (injectAttr != null) { identifier = injectAttr.Id; isOptional = injectAttr.Optional; sourceType = injectAttr.Source; } Type memberType; Action<object, object> setter; if (memInfo is FieldInfo) { var fieldInfo = (FieldInfo)memInfo; setter = ((object injectable, object value) => fieldInfo.SetValue(injectable, value)); memberType = fieldInfo.FieldType; } else { Assert.That(memInfo is PropertyInfo); var propInfo = (PropertyInfo)memInfo; memberType = propInfo.PropertyType; if (propInfo.CanWrite) setter = (( object injectable, object value ) => propInfo.SetValue(injectable, value, null)); else setter = GetOnlyPropertySetter(parentType, propInfo.Name); } return new InjectableInfo( isOptional, identifier, memInfo.Name, memberType, parentType, setter, null, sourceType); } static ConstructorInfo GetInjectConstructor(Type parentType) { var constructors = parentType.Constructors(); #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR // WP8 generates a dummy constructor with signature (internal Classname(UIntPtr dummy)) // So just ignore that constructors = constructors.Where(c => !IsWp8GeneratedConstructor(c)).ToArray(); #endif if (constructors.IsEmpty()) { return null; } if (constructors.HasMoreThan(1)) { var explicitConstructor = (from c in constructors where c.HasAttribute<InjectAttribute>() select c).SingleOrDefault(); if (explicitConstructor != null) { return explicitConstructor; } // If there is only one public constructor then use that // This makes decent sense but is also necessary on WSA sometimes since the WSA generated // constructor can sometimes be private with zero parameters var singlePublicConstructor = constructors.Where(x => !x.IsPrivate).OnlyOrDefault(); if (singlePublicConstructor != null) { return singlePublicConstructor; } return null; } return constructors[0]; } #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR static bool IsWp8GeneratedConstructor(ConstructorInfo c) { ParameterInfo[] args = c.GetParameters(); if (args.Length == 1) { return args[0].ParameterType == typeof(UIntPtr) && (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy"); } if (args.Length == 2) { return args[0].ParameterType == typeof(UIntPtr) && args[1].ParameterType == typeof(Int64*) && (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy") && (string.IsNullOrEmpty(args[1].Name) || args[1].Name == "dummy"); } return false; } #endif } }
/* * * (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 ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Mail.Core.Dao.Interfaces; using ASC.Mail.Core.DbSchema; using ASC.Mail.Core.DbSchema.Interfaces; using ASC.Mail.Core.DbSchema.Tables; using ASC.Mail.Core.Entities; using ASC.Mail.Extensions; namespace ASC.Mail.Core.Dao { public class ServerAddressDao : BaseDao, IServerAddressDao { protected static ITable table = new MailTableFactory().Create<ServerAddressTable>(); public ServerAddressDao(IDbManager dbManager, int tenant) : base(table, dbManager, tenant) { } public ServerAddress Get(int id) { var query = Query() .Where(ServerAddressTable.Columns.Tenant, Tenant) .Where(ServerAddressTable.Columns.Id, id); var address = Db.ExecuteList(query) .ConvertAll(ToServerAddress) .SingleOrDefault(); return address; } public List<ServerAddress> GetList(List<int> ids = null) { var query = Query() .Where(ServerAddressTable.Columns.Tenant, Tenant); if (ids != null && ids.Any()) { query.Where(Exp.In(ServerAddressTable.Columns.Id, ids)); } var list = Db.ExecuteList(query) .ConvertAll(ToServerAddress); return list; } public List<ServerAddress> GetList(int mailboxId) { var query = Query() .Where(ServerAddressTable.Columns.Tenant, Tenant) .Where(ServerAddressTable.Columns.MailboxId, mailboxId); var list = Db.ExecuteList(query) .ConvertAll(ToServerAddress); return list; } public List<ServerAddress> GetGroupAddresses(int groupId) { const string m_x_a_alias = "mxa"; const string address_alias = "msa"; var query = Query(address_alias) .InnerJoin(ServerMailGroupXAddressesTable.TABLE_NAME.Alias(m_x_a_alias), Exp.EqColumns(ServerMailGroupXAddressesTable.Columns.AddressId.Prefix(m_x_a_alias), ServerAddressTable.Columns.Id.Prefix(address_alias))) .Where(ServerMailGroupXAddressesTable.Columns.MailGroupId.Prefix(m_x_a_alias), groupId) .Where(ServerAddressTable.Columns.Tenant.Prefix(address_alias), Tenant); return Db.ExecuteList(query) .ConvertAll(ToServerAddress); } public List<ServerAddress> GetDomainAddresses(int domainId) { var query = Query() .Where(ServerAddressTable.Columns.Tenant, Tenant) .Where(ServerAddressTable.Columns.DomainId, domainId); var list = Db.ExecuteList(query) .ConvertAll(ToServerAddress); return list; } public void AddAddressesToMailGroup(int groupId, List<int> addressIds) { var query = new SqlInsert(ServerMailGroupXAddressesTable.TABLE_NAME) .InColumns(ServerMailGroupXAddressesTable.Columns.AddressId, ServerMailGroupXAddressesTable.Columns.MailGroupId); addressIds.ForEach(addressId => query.Values(addressId, groupId)); Db.ExecuteNonQuery(query); } public void DeleteAddressFromMailGroup(int groupId, int addressId) { var query = new SqlDelete(ServerMailGroupXAddressesTable.TABLE_NAME) .Where(ServerMailGroupXAddressesTable.Columns.AddressId, addressId) .Where(ServerMailGroupXAddressesTable.Columns.MailGroupId, groupId); Db.ExecuteNonQuery(query); } public void DeleteAddressesFromMailGroup(int groupId) { var query = new SqlDelete(ServerMailGroupXAddressesTable.TABLE_NAME) .Where(ServerMailGroupXAddressesTable.Columns.MailGroupId, groupId); Db.ExecuteNonQuery(query); } public void DeleteAddressesFromAnyMailGroup(List<int> addressIds) { var query = new SqlDelete(ServerMailGroupXAddressesTable.TABLE_NAME) .Where(Exp.In(ServerMailGroupXAddressesTable.Columns.AddressId, addressIds)); Db.ExecuteNonQuery(query); } public int Save(ServerAddress address) { var query = new SqlInsert(ServerAddressTable.TABLE_NAME, true) .InColumnValue(ServerAddressTable.Columns.Id, address.Id) .InColumnValue(ServerAddressTable.Columns.AddressName, address.AddressName) .InColumnValue(ServerAddressTable.Columns.Tenant, address.Tenant) .InColumnValue(ServerAddressTable.Columns.DomainId, address.DomainId) .InColumnValue(ServerAddressTable.Columns.MailboxId, address.MailboxId) .InColumnValue(ServerAddressTable.Columns.IsMailGroup, address.IsMailGroup) .InColumnValue(ServerAddressTable.Columns.IsAlias, address.IsAlias) .Identity(0, 0, true); if (address.Id <= 0) { query .InColumnValue(ServerAddressTable.Columns.DateCreated, DateTime.UtcNow); } var id = Db.ExecuteScalar<int>(query); return id; } public int Delete(int id) { var query = new SqlDelete(ServerAddressTable.TABLE_NAME) .Where(ServerAddressTable.Columns.Tenant, Tenant) .Where(ServerAddressTable.Columns.Id, id); var result = Db.ExecuteNonQuery(query); return result; } public int Delete(List<int> ids) { var query = new SqlDelete(ServerAddressTable.TABLE_NAME) .Where(ServerAddressTable.Columns.Tenant, Tenant) .Where(Exp.In(ServerAddressTable.Columns.Id, ids)); var result = Db.ExecuteNonQuery(query); return result; } private const string DOMAIN_ALIAS = "msd"; private const string ADDRESS_ALIAS = "msa"; public bool IsAddressAlreadyRegistered(string addressName, string domainName) { if (string.IsNullOrEmpty(addressName)) throw new ArgumentNullException("addressName"); if (string.IsNullOrEmpty(domainName)) throw new ArgumentNullException("domainName"); var addressQuery = new SqlQuery(ServerAddressTable.TABLE_NAME.Alias(ADDRESS_ALIAS)) .InnerJoin(ServerDomainTable.TABLE_NAME.Alias(DOMAIN_ALIAS), Exp.EqColumns( ServerAddressTable.Columns.DomainId.Prefix(ADDRESS_ALIAS), ServerDomainTable.Columns.Id.Prefix(DOMAIN_ALIAS)) ) .Select(ServerAddressTable.Columns.Id.Prefix(ADDRESS_ALIAS)) .Where(ServerAddressTable.Columns.AddressName.Prefix(ADDRESS_ALIAS), addressName) .Where(Exp.In(ServerAddressTable.Columns.Tenant.Prefix(ADDRESS_ALIAS), new List<int> { Tenant, Defines.SHARED_TENANT_ID })) .Where(ServerDomainTable.Columns.DomainName.Prefix(DOMAIN_ALIAS), domainName); return Db.ExecuteList(addressQuery).Any(); } protected ServerAddress ToServerAddress(object[] r) { var s = new ServerAddress { Id = Convert.ToInt32(r[0]), AddressName = Convert.ToString(r[1]), Tenant = Convert.ToInt32(r[2]), DomainId = Convert.ToInt32(r[3]), MailboxId = Convert.ToInt32(r[4]), IsMailGroup = Convert.ToBoolean(r[5]), IsAlias = Convert.ToBoolean(r[6]), DateCreated = Convert.ToDateTime(r[7]) }; return s; } } }
/* * Copyright 2014 Splunk, 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. */ // TODO: Ensure this code is solid // [O] Documentation // [X] Respect DataMemberAttribute.Order // [X] Do not serialize default values => define default values and check for them // [X] Rework this into a real parameter-passing class, not just a ToString implementation tool (toString shows all parameterts; args are passed as parameters by way of GetEnumerator) // [X] Work on nomenclature (serialization nomenclature is not necessarily appropriate) // [X] Ensure this class works with nullable types. // [ ] Support more than one level of inheritance => move away from generic implementation. // [ ] More (?) namespace Splunk.Client { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; /// <summary> /// /// </summary> /// <typeparam name="TArgs"></typeparam> public abstract class Args<TArgs> : IEnumerable<Argument> where TArgs : Args<TArgs> { #region Constructors static Args() { var propertyFormatters = new Dictionary<Type, Formatter>() { { typeof(bool), new Formatter { Format = FormatBoolean } }, { typeof(bool?), new Formatter { Format = FormatBoolean } }, { typeof(byte), new Formatter { Format = FormatNumber } }, { typeof(byte?), new Formatter { Format = FormatNumber } }, { typeof(sbyte), new Formatter { Format = FormatNumber } }, { typeof(sbyte?), new Formatter { Format = FormatNumber } }, { typeof(short), new Formatter { Format = FormatNumber } }, { typeof(short?), new Formatter { Format = FormatNumber } }, { typeof(ushort), new Formatter { Format = FormatNumber } }, { typeof(ushort?), new Formatter { Format = FormatNumber } }, { typeof(int), new Formatter { Format = FormatNumber } }, { typeof(int?), new Formatter { Format = FormatNumber } }, { typeof(uint), new Formatter { Format = FormatNumber } }, { typeof(uint?), new Formatter { Format = FormatNumber } }, { typeof(long), new Formatter { Format = FormatNumber } }, { typeof(long?), new Formatter { Format = FormatNumber } }, { typeof(ulong), new Formatter { Format = FormatNumber } }, { typeof(ulong?), new Formatter { Format = FormatNumber } }, { typeof(float), new Formatter { Format = FormatNumber } }, { typeof(float?), new Formatter { Format = FormatNumber } }, { typeof(double), new Formatter { Format = FormatNumber } }, { typeof(double?), new Formatter { Format = FormatNumber } }, { typeof(decimal), new Formatter { Format = FormatNumber } }, { typeof(decimal?), new Formatter { Format = FormatNumber } }, { typeof(string), new Formatter { Format = FormatString } } }; var defaultFormatter = new Formatter { Format = FormatString }; var parameters = new SortedSet<Parameter>(); foreach (PropertyInfo propertyInfo in typeof(TArgs).GetRuntimeProperties()) { var dataMember = propertyInfo.GetCustomAttribute<DataMemberAttribute>(); if (dataMember == null) { throw new InvalidDataContractException(string.Format("Missing DataMemberAttribute on {0}.{1}", propertyInfo.PropertyType.Name, propertyInfo.Name)); } var propertyName = propertyInfo.Name; var propertyType = propertyInfo.PropertyType; var propertyTypeInfo = propertyType.GetTypeInfo(); Formatter? formatter = GetPropertyFormatter(propertyName, null, propertyType, propertyTypeInfo, propertyFormatters); if (formatter == null) { var interfaces = propertyType.GetTypeInfo().ImplementedInterfaces; var isCollection = false; formatter = defaultFormatter; foreach (Type @interface in interfaces) { if (@interface.IsConstructedGenericType) { if (@interface.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { Type itemType = @interface.GenericTypeArguments[0]; formatter = GetPropertyFormatter(propertyName, propertyType, itemType, itemType.GetTypeInfo(), propertyFormatters); } } else if (@interface == typeof(IEnumerable)) { isCollection = true; } } formatter = new Formatter { Format = formatter.Value.Format, IsCollection = isCollection }; } var defaultValue = propertyInfo.GetCustomAttribute<DefaultValueAttribute>(); parameters.Add(new Parameter(dataMember.Name, dataMember.Order, propertyInfo) { // Properties DefaultValue = defaultValue == null ? null : defaultValue.Value, EmitDefaultValue = dataMember.EmitDefaultValue, IsCollection = formatter.Value.IsCollection, IsRequired = dataMember.IsRequired, // Methods Format = (formatter ?? defaultFormatter).Format }); } Parameters = parameters; } protected Args() { foreach (var serializationEntry in Parameters.Where(entry => entry.DefaultValue != null)) { serializationEntry.SetValue(this, serializationEntry.DefaultValue); } } #endregion #region Fields public static readonly IEnumerable<Argument> Empty = Enumerable.Empty<Argument>(); #endregion #region Methods public IEnumerator<Argument> GetEnumerator() { foreach (var parameter in Args<TArgs>.Parameters) { object value = parameter.GetValue(this); if (value == null) { if (parameter.IsRequired) { throw new SerializationException(string.Format("Missing value for required parameter {0}", parameter.Name)); } continue; } if (!parameter.EmitDefaultValue && value.Equals(parameter.DefaultValue)) { continue; } if (!parameter.IsCollection) { yield return new Argument(parameter.Name, parameter.Format(value)); continue; } foreach (var item in (IEnumerable)value) { yield return new Argument(parameter.Name, parameter.Format(item)); } } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public override string ToString() { StringBuilder builder = new StringBuilder(); Action<object, string, Func<object, string>> append = (item, name, format) => { builder.Append(name); builder.Append('='); builder.Append(format(item)); builder.Append("; "); }; foreach (var parameter in Args<TArgs>.Parameters) { object value = parameter.GetValue(this); if (value == null) { append("null", parameter.Name, FormatString); continue; } if (!parameter.IsCollection) { append(value, parameter.Name, parameter.Format); continue; } foreach (var item in (IEnumerable)value) { append(item, parameter.Name, parameter.Format); } } if (builder.Length > 0) { builder.Length = builder.Length - 2; } return builder.ToString(); } #endregion #region Privates static readonly SortedSet<Parameter> Parameters; static string FormatBoolean(object value) { return (bool)value ? "t" : "f"; } static string FormatNumber(object value) { return value.ToString(); } static string FormatString(object value) { return value.ToString(); } static Formatter? GetPropertyFormatter(string propertyName, Type container, Type type, TypeInfo info, Dictionary<Type, Formatter> formatters) { Formatter formatter; if (formatters.TryGetValue(container ?? type, out formatter)) { return formatter; } if (container != null && formatters.TryGetValue(type, out formatter)) { formatter = new Formatter { Format = formatter.Format, IsCollection = true }; } else if (info.IsEnum) { var map = new Dictionary<int, string>(); foreach (var value in Enum.GetValues(type)) { string name = Enum.GetName(type, value); FieldInfo field = type.GetRuntimeField(name); var enumMember = field.GetCustomAttribute<EnumMemberAttribute>(); map[(int)value] = enumMember == null ? name : enumMember.Value; } formatter = new Formatter { Format = (object value) => { string name; if (map.TryGetValue((int)value, out name)) { return name; } throw new ArgumentException(string.Format("{0}.{1}: {2}", typeof(TArgs).Name, propertyName, value)); }, IsCollection = container != null }; } else if (container != null) { formatter = new Formatter { Format = FormatString, IsCollection = true }; } else { return null; } formatters.Add(container ?? type, formatter); return formatter; } #endregion #region Types struct Formatter { public Func<object, string> Format; public bool IsCollection; } struct Ordinal : IComparable<Ordinal>, IEquatable<Ordinal> { #region Constructos public Ordinal(int position, string name) { this.Position = position; this.Name = name; } #endregion #region Fields public readonly int Position; public readonly string Name; #endregion #region Methods public int CompareTo(Ordinal other) { int result = this.Position - other.Position; return result != 0 ? result : this.Name.CompareTo(other.Name); } public override bool Equals(object o) { return o != null && o is Ordinal ? this.Equals((Ordinal)o) : false; } public bool Equals(Ordinal other) { return this.Position == other.Position && this.Name == other.Name; } public override int GetHashCode() { // TODO: Check this against the algorithm presented in Effective Java int hash = 17; hash = (hash * 23) + this.Position.GetHashCode(); hash = (hash * 23) + this.Name.GetHashCode(); return hash; } public override string ToString() { return string.Format("({0}, {1})", this.Position, this.Name); } #endregion } class Parameter : IComparable, IComparable<Parameter>, IEquatable<Parameter> { #region Constructors public Parameter(string name, int position, PropertyInfo propertyInfo) { this.ordinal = new Ordinal(position, name); this.propertyInfo = propertyInfo; } #endregion #region Properties public object DefaultValue { get; set; } public bool EmitDefaultValue { get; set; } public bool IsCollection { get; set; } public bool IsRequired { get; set; } public string Name { get { return this.ordinal.Name; } } public int Position { get { return this.ordinal.Position; } } #endregion #region Methods public int CompareTo(object other) { return this.CompareTo(other as Parameter); } public int CompareTo(Parameter other) { if (other == null) return 1; if (object.ReferenceEquals(this, other)) return 0; return this.ordinal.CompareTo(other.ordinal); } public override bool Equals(object other) { return this.Equals(other as Parameter); } public bool Equals(Parameter other) { if (other == null) { return false; } return object.ReferenceEquals(this, other) || this.ordinal.Equals(other.ordinal); } public Func<object, string> Format { get; set; } public override int GetHashCode() { return this.ordinal.GetHashCode(); } public object GetValue(object o) { return this.propertyInfo.GetValue(o); } public void SetValue(object o, object value) { this.propertyInfo.SetValue(o, value); } #endregion #region Privates PropertyInfo propertyInfo; Ordinal ordinal; #endregion } #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.Security; using System; public struct TestStruct { public int IntValue; public string StringValue; } public class DisposableClass : IDisposable { public void Dispose() { } } /// <summary> /// Target /// </summary> [SecuritySafeCritical] public class WeakReferenceTarget { #region Private Fields private const int c_MIN_STRING_LENGTH = 8; private const int c_MAX_STRING_LENGTH = 1024; private WeakReference[] m_References; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call Target on short weak reference to instance of an object"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); retVal = GenerateUnusedData1("001.1") && retVal; // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < m_References.Length; ++i) { if (m_References[i].Target != null) { TestLibrary.TestFramework.LogError("001.2", "Target is not null after GC collecting memory"); TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = " + m_References[i].Target.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call Target on long weak reference to instance of an object"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); retVal = GenerateUnusedData2("002.1") && retVal; // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < m_References.Length; ++i) { if (m_References[i].Target != null) { TestLibrary.TestFramework.LogError("002.2", "Target is not null after GC collecting memory"); TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = " + m_References[i].Target.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call set_Target on short weak reference to instance of an object before GC"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); retVal = GenerateUnusedData1("003.1") && retVal; object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); ; WeakReferenceTarget thisClass = new WeakReferenceTarget(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); Object[] objs = new object[] { obj, str, randBytes, thisClass, dc, ptr, IntPtr.Zero }; for (int i = 0; i < m_References.Length; ++i) { m_References[i].Target = objs[i]; if (!m_References[i].Target.Equals(objs[i])) { TestLibrary.TestFramework.LogError("003.2", "Target is not set correctly"); TestLibrary.TestFramework.LogInformation("WARNING: m_References[i].Target = " + m_References[i].Target.ToString() + ", objs = " + objs[i].ToString() + ", i = " + i.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Call set_Target on long weak reference to instance of an object before GC"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); retVal = GenerateUnusedData2("004.1") && retVal; object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); WeakReferenceTarget thisClass = new WeakReferenceTarget(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); Object[] objs = new object[] { obj, str, randBytes, thisClass, dc, ptr, IntPtr.Zero }; for (int i = 0; i < m_References.Length; ++i) { m_References[i].Target = objs[i]; if (!m_References[i].Target.Equals(objs[i])) { TestLibrary.TestFramework.LogError("004.2", "Target is not set correctly"); TestLibrary.TestFramework.LogInformation("WARNING: m_References[i].Target = " + m_References[i].Target.ToString() + ", objs = " + objs[i].ToString() + ", i = " + i.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } #endregion #endregion public static int Main() { WeakReferenceTarget test = new WeakReferenceTarget(); TestLibrary.TestFramework.BeginTestCase("WeakReferenceTarget"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool GenerateUnusedData1(string errorNo) { bool retVal = true; object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); WeakReferenceTarget thisClass = new WeakReferenceTarget(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); Object[] objs = new object[] { obj, str, randBytes, thisClass, dc, ptr, IntPtr.Zero }; m_References = new WeakReference[objs.Length]; for (int i = 0; i < objs.Length; ++i) { m_References[i] = new WeakReference(objs[i], false); } for (int i = 0; i < m_References.Length; ++i) { if (!m_References[i].Target.Equals(objs[i])) { TestLibrary.TestFramework.LogError(errorNo, "Target returns wrong value for weak references"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] i = " + i.ToString() + ", m_References[i].Target = " + m_References[i].Target.ToString() + ", objs[i] = " + objs[i].ToString()); retVal = false; } } return retVal; } private bool GenerateUnusedData2(string errorNo) { bool retVal = true; object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); TestStruct ts = new TestStruct(); ts.IntValue = TestLibrary.Generator.GetInt32(-55); WeakReferenceTarget thisClass = new WeakReferenceTarget(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); Object[] objs = new object[] { obj, str, randBytes, thisClass, dc, ptr, IntPtr.Zero }; m_References = new WeakReference[objs.Length]; for (int i = 0; i < objs.Length; ++i) { m_References[i] = new WeakReference(objs[i], true); } for (int i = 0; i < m_References.Length; ++i) { if (!m_References[i].Target.Equals(objs[i])) { TestLibrary.TestFramework.LogError(errorNo, "Target returns wrong value for weak references"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] i = " + i.ToString() + ", m_References[i].Target = " + m_References[i].Target.ToString() + ", objs[i] = " + objs[i].ToString()); retVal = false; } } return retVal; } private void GenerateUnusedDisposableData() { DisposableClass dc = null; m_References = new WeakReference[1]; try { dc = new DisposableClass(); m_References[0] = new WeakReference(dc); } finally { if (null != dc) { dc.Dispose(); } } GC.Collect(); } #endregion }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; using Microsoft.Research.AbstractDomains; using System.Collections.Generic; using Microsoft.Research.DataStructures; using Microsoft.Research.AbstractDomains.Expressions; using Microsoft.Research.AbstractDomains.Numerical; namespace Microsoft.Research.CodeAnalysis { public static partial class AnalysisWrapper { public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> { /// <summary> /// Analysis that propagates existential facts /// </summary> [ContractVerification(true)] public class ExistentialAnalysisPlugIn : ArrayAnalysisBasePlugIn<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>> { #region Constructor public ExistentialAnalysisPlugIn( int pluginCount, string name, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> driver, ILogOptions options, Predicate<APC> cachePCs ) : base(pluginCount, name, driver, options, cachePCs) { } #endregion #region Implementation of overridden public override IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> InitialState { get { return new ArraySegmentationEnvironment<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>, BoxedVariable<Variable>, BoxedExpression>(this.ExpressionManager); } } public override IFactQuery<BoxedExpression, Variable> FactQuery(IFixpointInfo<APC, ArrayState> fixpoint) { return null; } public override ArrayState.AdditionalStates Kind { get { return ArrayState.AdditionalStates.Existential; } } public override IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> AssignInParallel(Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> refinedMap, Converter<BoxedVariable<Variable>, BoxedExpression> convert, List<Pair<NormalizedExpression<BoxedVariable<Variable>>, NormalizedExpression<BoxedVariable<Variable>>>> equalities, ArrayState state) { Contract.Assume(refinedMap != null); Contract.Assume(convert != null); var renamed = Select(state); renamed.AssignInParallel(refinedMap, convert); return renamed; } #endregion #region Transfer functions #region Assume public override ArrayState Assume(APC pc, string tag, Variable source, object provenance, ArrayState data) { Contract.Assume(data != null, "Assume for inheritance"); #region Assume the existential, if any if (tag != "false") { var exist = this.MethodDriver.AsExistsIndexed(pc, source); if (exist != null) { var updated = AssumeExistsAll(pc, exist, data); if (updated.IsBottom) { return data.Bottom; } data = data.UpdatePluginAt(this.Id, updated); } } #endregion #region Look for contraddictions forall/exists var bottom = NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>.Unreached; foreach (var pair in Select(data).Elements) { if (pair.Value.IsNormal) { ArraySegmentation<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>, BoxedVariable<Variable>, BoxedExpression> universal; if (data.Array.TryGetValue(pair.Key, out universal)) { if (pair.Value.JoinAll(bottom).AreInContraddiction(universal.JoinAll(bottom))) { // Found a contraddiction!!! return data.Bottom; } } } } #endregion return data; } #region Handling of Assume Contract.Exists public ArraySegmentationEnvironment<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>, BoxedVariable<Variable>, BoxedExpression> AssumeExistsAll(APC pc, ExistsIndexedExpression exists, ArrayState data) { Contract.Requires(exists != null); Contract.Requires(data != null); // F: those are readonly-fields to which we cannot attach postcondition Contract.Assume(exists.LowerBound != null); Contract.Assume(exists.UpperBound != null); var mySubState = Select(data); // Shortcut for Exists(false => ...) if (exists.LowerBound.Equals(exists.UpperBound)) { return mySubState.Bottom as ArraySegmentationEnvironment<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>, BoxedVariable<Variable>, BoxedExpression>; } NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression> intv; BoxedExpression array; if (this.TryInferNonRelationalProperty(exists.BoundVariable, exists.Body, data.Numerical, out array, out intv)) { var arrayVar = ((Variable)array.UnderlyingVariable); Variable arrayLen; if ((array.UnderlyingVariable is Variable) && this.Context.ValueContext.TryGetArrayLength(this.Context.MethodContext.CFG.Post(pc), arrayVar, out arrayLen)) { Contract.Assume(arrayLen != null); // Clousot does not know arrayLen is a struct here ArraySegmentation<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>, BoxedVariable<Variable>, BoxedExpression> arraySegmentation; if (this.TryCreateArraySegment(exists.LowerBound, exists.UpperBound, arrayLen, intv, data.Numerical, out arraySegmentation)) { ArraySegmentation<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>, BoxedVariable<Variable>, BoxedExpression> prevVal; if (mySubState.TryGetValue(ToBoxedVariable(arrayVar), out prevVal)) { var meet = prevVal.Meet(arraySegmentation); mySubState.Update(ToBoxedVariable(arrayVar), meet); } else { mySubState.AddElement(ToBoxedVariable(arrayVar), arraySegmentation); } } } } return mySubState; } #endregion #endregion #region Assert public override ArrayState Assert(APC pc, string tag, Variable condition, object provenance, ArrayState data) { return this.Assume(pc, tag, condition, provenance, data); } #endregion #region Stelem public override ArrayState Stelem(APC pc, Type type, Variable array, Variable index, Variable value, ArrayState data) { var mySubState = Select(data); var bArray = new BoxedVariable<Variable>(array); if (mySubState.ContainsKey(bArray)) { mySubState.RemoveElement(bArray); return data.UpdatePluginAt(this.Id, mySubState); } return data; } #endregion #region Ldelem [ContractVerification(false)] public override ArrayState Ldelem(APC pc, Type type, Variable dest, Variable array, Variable index, ArrayState data) { var mySubState = Select(data); var bArray = new BoxedVariable<Variable>(array); ArraySegmentation<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>, BoxedVariable<Variable>, BoxedExpression> existentialSegmentation; var noConstraints = SetOfConstraints<BoxedVariable<Variable>>.Unknown; var newElement = new NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>(DisInterval.UnknownInterval, SymbolicExpressionTracker<BoxedVariable<Variable>, BoxedExpression>.Unknown, new SetOfConstraints<BoxedVariable<Variable>>(new BoxedVariable<Variable>(dest)), noConstraints, noConstraints, noConstraints, noConstraints); if (mySubState.TryGetValue(bArray, out existentialSegmentation)) { if (existentialSegmentation.IsNormal()) { var newSegmentation = new ArraySegmentation<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>, BoxedVariable<Variable>, BoxedExpression> (new NonNullList<SegmentLimit<BoxedVariable<Variable>>>() { existentialSegmentation.Limits.AsIndexable()[0], existentialSegmentation.LastLimit }, new NonNullList<NonRelationalValueAbstraction<BoxedVariable<Variable>, BoxedExpression>>() { newElement }, existentialSegmentation.Elements.AsIndexable()[0].Bottom, this.ExpressionManager); var meet = existentialSegmentation.Meet(newSegmentation); mySubState.Update(bArray, meet); return data.UpdatePluginAt(this.Id, mySubState); } } else // materialize { existentialSegmentation = MaterializeArray(this.Context.MethodContext.CFG.Post(pc), mySubState, data.Numerical.CheckIfNonZero, array, newElement, newElement.Bottom); // Segmentation may fail if (existentialSegmentation != null) { mySubState.Update(bArray, existentialSegmentation); return data.UpdatePluginAt(this.Id, mySubState); } } return data; } #endregion #endregion } } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using ESRI.ArcGIS.ADF; using ESRI.ArcGIS.PublisherControls; namespace SpinGlobe { /// <summary> /// Summary description for Form1. /// </summary> public class SpinGlobe : System.Windows.Forms.Form { internal System.Windows.Forms.Label lblFaster; internal System.Windows.Forms.Label lblSlower; internal System.Windows.Forms.TrackBar TrackBar1; internal System.Windows.Forms.Button btnStop; internal System.Windows.Forms.Button btnClockwise; internal System.Windows.Forms.Button btnAntiClockwise; internal System.Windows.Forms.Button btnLoad; private ESRI.ArcGIS.PublisherControls.AxArcReaderGlobeControl axArcReaderGlobeControl1; private System.Windows.Forms.OpenFileDialog openFileDialog1; private bool m_RotateDirection; private double m_CurLat; private double m_CurLong; private double m_CurElev; private double i; private System.Windows.Forms.Timer timer1; private System.ComponentModel.IContainer components; public SpinGlobe() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(SpinGlobe)); this.lblFaster = new System.Windows.Forms.Label(); this.lblSlower = new System.Windows.Forms.Label(); this.TrackBar1 = new System.Windows.Forms.TrackBar(); this.btnStop = new System.Windows.Forms.Button(); this.btnClockwise = new System.Windows.Forms.Button(); this.btnAntiClockwise = new System.Windows.Forms.Button(); this.btnLoad = new System.Windows.Forms.Button(); this.axArcReaderGlobeControl1 = new ESRI.ArcGIS.PublisherControls.AxArcReaderGlobeControl(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.timer1 = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.TrackBar1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axArcReaderGlobeControl1)).BeginInit(); this.SuspendLayout(); // // lblFaster // this.lblFaster.Location = new System.Drawing.Point(152, 16); this.lblFaster.Name = "lblFaster"; this.lblFaster.Size = new System.Drawing.Size(40, 20); this.lblFaster.TabIndex = 14; this.lblFaster.Text = "Faster"; // // lblSlower // this.lblSlower.Location = new System.Drawing.Point(360, 16); this.lblSlower.Name = "lblSlower"; this.lblSlower.Size = new System.Drawing.Size(40, 20); this.lblSlower.TabIndex = 13; this.lblSlower.Text = "Slower"; // // TrackBar1 // this.TrackBar1.Location = new System.Drawing.Point(192, 8); this.TrackBar1.Maximum = 1000; this.TrackBar1.Minimum = 100; this.TrackBar1.Name = "TrackBar1"; this.TrackBar1.Size = new System.Drawing.Size(164, 45); this.TrackBar1.TabIndex = 12; this.TrackBar1.TickStyle = System.Windows.Forms.TickStyle.None; this.TrackBar1.Value = 100; this.TrackBar1.ValueChanged += new System.EventHandler(this.TrackBar1_ValueChanged); // // btnStop // this.btnStop.Location = new System.Drawing.Point(512, 16); this.btnStop.Name = "btnStop"; this.btnStop.Size = new System.Drawing.Size(76, 36); this.btnStop.TabIndex = 11; this.btnStop.TextAlign = System.Drawing.ContentAlignment.BottomCenter; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // btnClockwise // this.btnClockwise.Location = new System.Drawing.Point(424, 16); this.btnClockwise.Name = "btnClockwise"; this.btnClockwise.Size = new System.Drawing.Size(76, 36); this.btnClockwise.TabIndex = 10; this.btnClockwise.TextAlign = System.Drawing.ContentAlignment.BottomCenter; this.btnClockwise.Click += new System.EventHandler(this.btnClockwise_Click); // // btnAntiClockwise // this.btnAntiClockwise.Location = new System.Drawing.Point(592, 16); this.btnAntiClockwise.Name = "btnAntiClockwise"; this.btnAntiClockwise.Size = new System.Drawing.Size(76, 36); this.btnAntiClockwise.TabIndex = 9; this.btnAntiClockwise.TextAlign = System.Drawing.ContentAlignment.BottomCenter; this.btnAntiClockwise.Click += new System.EventHandler(this.btnAntiClockwise_Click); // // btnLoad // this.btnLoad.ImageAlign = System.Drawing.ContentAlignment.BottomCenter; this.btnLoad.Location = new System.Drawing.Point(8, 16); this.btnLoad.Name = "btnLoad"; this.btnLoad.Size = new System.Drawing.Size(76, 36); this.btnLoad.TabIndex = 8; this.btnLoad.Text = "Load"; this.btnLoad.TextAlign = System.Drawing.ContentAlignment.TopCenter; this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // axArcReaderGlobeControl1 // this.axArcReaderGlobeControl1.Location = new System.Drawing.Point(8, 64); this.axArcReaderGlobeControl1.Name = "axArcReaderGlobeControl1"; this.axArcReaderGlobeControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axArcReaderGlobeControl1.OcxState"))); this.axArcReaderGlobeControl1.Size = new System.Drawing.Size(656, 376); this.axArcReaderGlobeControl1.TabIndex = 15; this.axArcReaderGlobeControl1.OnDocumentUnloaded += new System.EventHandler(this.axArcReaderGlobeControl1_OnDocumentUnloaded); this.axArcReaderGlobeControl1.OnDocumentLoaded += new ESRI.ArcGIS.PublisherControls.IARGlobeControlEvents_Ax_OnDocumentLoadedEventHandler(this.axArcReaderGlobeControl1_OnDocumentLoaded); this.axArcReaderGlobeControl1.OnMouseUp += new ESRI.ArcGIS.PublisherControls.IARGlobeControlEvents_Ax_OnMouseUpEventHandler(this.axArcReaderGlobeControl1_OnMouseUp); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // SpinGlobe // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(676, 450); this.Controls.Add(this.axArcReaderGlobeControl1); this.Controls.Add(this.lblFaster); this.Controls.Add(this.lblSlower); this.Controls.Add(this.TrackBar1); this.Controls.Add(this.btnStop); this.Controls.Add(this.btnClockwise); this.Controls.Add(this.btnAntiClockwise); this.Controls.Add(this.btnLoad); this.Name = "SpinGlobe"; this.Text = "SpinGlobe"; this.Closing += new System.ComponentModel.CancelEventHandler(this.SpinGlobe_Closing); this.Load += new System.EventHandler(this.SpinGlobe_Load); ((System.ComponentModel.ISupportInitialize)(this.TrackBar1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axArcReaderGlobeControl1)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.ArcReader)) { if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run(new SpinGlobe()); } private void SpinGlobe_Load(object sender, System.EventArgs e) { //Load command button images System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "browse.bmp")); bitmap.MakeTransparent(System.Drawing.Color.Teal); btnLoad.Image = bitmap; bitmap = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "spin_counterclockwise.bmp")); bitmap.MakeTransparent(System.Drawing.Color.Teal); btnAntiClockwise.Image = bitmap; bitmap = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "spin_clockwise.bmp")); bitmap.MakeTransparent(System.Drawing.Color.Teal); btnClockwise.Image = bitmap; bitmap = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "spin_stop.bmp")); bitmap.MakeTransparent(System.Drawing.Color.Teal); btnStop.Image = bitmap; //Set the current Slider value and timer interval to 100 milliseconds //Any faster and the Globe will not be able to refresh fast enough TrackBar1.Value = 100; timer1.Interval = 100; timer1.Enabled = false; i = 0; //Disable controls until doc is loaded btnAntiClockwise.Enabled = false; btnClockwise.Enabled = false; btnStop.Enabled = false; } private void btnLoad_Click(object sender, System.EventArgs e) { //Open a file dialog for selecting map documents openFileDialog1.Title = "Select Published Map Document"; openFileDialog1.Filter = "Published Map Documents (*.pmf)|*.pmf"; openFileDialog1.ShowDialog(); //Exit if no map document is selected string sFilePath = ""; sFilePath = openFileDialog1.FileName; if (sFilePath == "") { return; } //Load the specified pmf if (axArcReaderGlobeControl1.CheckDocument(sFilePath) == true) { axArcReaderGlobeControl1.LoadDocument(sFilePath); } else { MessageBox.Show("This document cannot be loaded!"); return; } //Zoom to Full Extent axArcReaderGlobeControl1.ARGlobe.ZoomToFullExtent(); //Set current tool to Globe Navigate axArcReaderGlobeControl1.CurrentARGlobeTool = ESRI.ArcGIS.PublisherControls.esriARGlobeTool.esriARGlobeToolNavigate; } private void TrackBar1_ValueChanged(object sender, System.EventArgs e) { //Update the timer interval to match the slider value timer1.Interval = TrackBar1.Value; } private void timer1_Tick(object sender, System.EventArgs e) { //Longitude Counter i = m_CurLong; //Increment Longitude by 1 decimal degree if (m_RotateDirection == false) { if (i == 360) { i = 0; } i = i + 1; } else { if (i == -360) { i = 0; } i = i - 1; } //Update the current location axArcReaderGlobeControl1.ARGlobe.SetObserverLocation(i, m_CurLat, m_CurElev); axArcReaderGlobeControl1.ARGlobe.GetObserverLocation(ref m_CurLong, ref m_CurLat, ref m_CurElev); } private void axArcReaderGlobeControl1_OnDocumentUnloaded(object sender, System.EventArgs e) { btnAntiClockwise.Enabled = false; btnClockwise.Enabled = false; btnStop.Enabled = false; } private void axArcReaderGlobeControl1_OnDocumentLoaded(object sender, ESRI.ArcGIS.PublisherControls.IARGlobeControlEvents_OnDocumentLoadedEvent e) { btnAntiClockwise.Enabled = true; btnClockwise.Enabled = true; btnStop.Enabled = true; } private void SpinGlobe_Closing(object sender, System.ComponentModel.CancelEventArgs e) { //Release COM Objects ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); } private void btnClockwise_Click(object sender, System.EventArgs e) { //Get latest location and start timer axArcReaderGlobeControl1.ARGlobe.GetObserverLocation(ref m_CurLong, ref m_CurLat, ref m_CurElev); m_RotateDirection = false; timer1.Enabled = true; //Unselect the current tool axArcReaderGlobeControl1.CurrentARGlobeTool = ESRI.ArcGIS.PublisherControls.esriARGlobeTool.esriARGlobeToolNoneSelected; } private void btnStop_Click(object sender, System.EventArgs e) { //Stops Timer timer1.Enabled = false; //Set the current tool to Globe Navigate axArcReaderGlobeControl1.CurrentARGlobeTool = ESRI.ArcGIS.PublisherControls.esriARGlobeTool.esriARGlobeToolNavigate; } private void btnAntiClockwise_Click(object sender, System.EventArgs e) { //Get latest location and start timer axArcReaderGlobeControl1.ARGlobe.GetObserverLocation(ref m_CurLong, ref m_CurLat, ref m_CurElev); m_RotateDirection = true; timer1.Enabled = true; //Unselect the current tool axArcReaderGlobeControl1.CurrentARGlobeTool = ESRI.ArcGIS.PublisherControls.esriARGlobeTool.esriARGlobeToolNoneSelected; } private void axArcReaderGlobeControl1_OnMouseUp(object sender, ESRI.ArcGIS.PublisherControls.IARGlobeControlEvents_OnMouseUpEvent e) { //Update m_CurLong incase observer has been repositioned as a consequence of using another tool. axArcReaderGlobeControl1.ARGlobe.GetObserverLocation(ref m_CurLong, ref m_CurLat, ref m_CurElev); } } }
/* Copyright (c) 2004-2005 Jan Benda. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Text; using System.Diagnostics; using System.Collections; #if SILVERLIGHT using PHP.CoreCLR; #endif namespace PHP.Core { #region Basic Stream Filters /// <summary> /// Interface encapsulating the stream filtering functionality. /// </summary> public interface IFilter { /// <summary> /// Processes the <paramref name="input"/> (either of type <see cref="string"/> or <see cref="PhpBytes"/>) /// data and returns the filtered data in one of the formats above or <c>null</c>. /// </summary> object Filter(object input, bool closing); /// <summary> /// Called when the filter is attached to a stream. /// </summary> void OnCreate(); /// <summary> /// Called when the containig stream is being closed. /// </summary> void OnClose(); } /// <summary> /// Stream Filter used to convert \r\n to \n when reading a text file. /// </summary> public class TextReadFilter : IFilter { /// <summary> /// Processes the <paramref name="input"/> (either of type <see cref="string"/> or <see cref="PhpBytes"/>) /// data and returns the filtered data in one of the formats above or <c>null</c>. /// </summary> public object Filter(object input, bool closing) { string str = PhpStream.AsText(input); if (pending) { // Both \r\n together make a pair which would consume a pending \r. if (str.Length == 0) str = "\r"; else if (str[0] != '\n') str.Insert(0, "\r"); } // Replace the pair. str = str.Replace("\r\n", "\n"); if (str.Length == 0) return string.Empty; // Check for pending \r at the end. pending = str[str.Length - 1] == '\r'; // Postpone the resolution of \r\n vs. \r to the next filtering if this is not the last one. if (!closing && pending) str.Remove(str.Length - 1, 1); return str; } bool pending = false; /// <summary> /// Called when the filter is attached to a stream. /// </summary> public void OnCreate() { } /// <summary> /// Called when the containig stream is being closed. /// </summary> public void OnClose() { } } /// <summary> /// Stream Filter used to convert \n to \r\n when writing to a text file. /// </summary> public class TextWriteFilter : IFilter { /// <summary> /// Processes the <paramref name="input"/> (either of type <see cref="string"/> or <see cref="PhpBytes"/>) /// data and returns the filtered data in one of the formats above or <c>null</c>. /// </summary> public object Filter(object input, bool closing) { string str = PhpStream.AsText(input); str = str.Replace("\n", "\r\n"); return str; } /// <summary> /// Called when the filter is attached to a stream. /// </summary> public void OnCreate() { } /// <summary> /// Called when the containig stream is being closed. /// </summary> public void OnClose() { } } #endregion #region Stream Filter Base Classes #region Filter options /// <summary> /// Indicates whether the filter is to be attached to the /// input/ouput filter-chain or both. /// </summary> [Flags] public enum FilterChainOptions { /// <summary>Insert the filter to the read filter chain of the stream (1).</summary> Read = 0x1, /// <summary>Insert the filter to the write filter chain of the stream (2).</summary> Write = 0x2, /// <summary>Insert the filter to both the filter chains of the stream (3).</summary> ReadWrite = Read | Write, /// <summary>Prepend the filter to the filter-chain (0x10).</summary> Head = 0x10, /// <summary>Append the filter to the filter-chain (0x20).</summary> Tail = 0x20 } #endregion /// <summary> /// Implementor of this interface provides filter creation. /// </summary> public interface IFilterFactory { /// <summary> /// Returns the list of filters created by this <see cref="IFilterFactory"/>. /// </summary> /// <returns>The list of implemented filters.</returns> string[] GetImplementedFilterNames(); /// <summary> /// Checks if a filter is being created by this factory and optionally returns a new instance of this filter. /// </summary> /// <param name="name">The name of the filter (may contain wildcards).</param> /// <param name="instantiate"><c>true</c> to fill <paramref name="instance"/> with a new instance of that filter.</param> /// <param name="instance">Filled with a new instance of an implemented filter if <paramref name="instantiate"/>.</param> /// <param name="parameters">Additional parameters provided to the filter constructor.</param> /// <returns><c>true</c> if a filter with the given name was found.</returns> bool GetImplementedFilter(string name, bool instantiate, out PhpFilter instance, object parameters); } /// <summary> /// Base class for PHP stream filters. /// </summary> public abstract class PhpFilter : IFilter { #region Filtering methods and properties. /// <summary> /// Creates a new instance of the <see cref="PhpFilter"/>. /// </summary> /// <param name="parameters">The parameters.</param> public PhpFilter(object parameters) { this.parameters = parameters; } /// <summary> /// The filter name, same as the name used for creating the filter (see GetFilter). /// </summary> public string FilterName { get; private set; } #region IFilter Overrides /// <summary> /// Processes the <paramref name="input"/> (either of type <see cref="string"/> or <see cref="PhpBytes"/>) /// data and returns the filtered data in one of the formats above or <c>null</c>. /// </summary> public abstract object Filter(object input, bool closing); /// <summary> /// Called when the filter is attached to a stream. /// </summary> public void OnCreate() { } /// <summary> /// Called when the containig stream is being closed. /// </summary> public void OnClose() { } #endregion /// <summary> /// An additional <c>mixed</c> parameter passed at <c>stream_filter_append/prepend</c>. /// </summary> protected readonly object parameters; #endregion #region Stream Filter Chain Access /// <summary> /// Insert the filter into the filter chains. /// </summary> /// <param name="stream">Which stream's filter chains.</param> /// <param name="filter">What filter.</param> /// <param name="where">What position in the chains.</param> /// <param name="parameters">Additional parameters for the filter.</param> /// <returns>True if successful.</returns> public static bool AddToStream(PhpStream stream, string filter, FilterChainOptions where, object parameters) { PhpFilter readFilter, writeFilter; if ((stream.Options & StreamAccessOptions.Read) == 0) where &= ~FilterChainOptions.Read; if ((stream.Options & StreamAccessOptions.Write) == 0) where &= ~FilterChainOptions.Write; if ((where & FilterChainOptions.Read) > 0) { if (!GetFilter(filter, true, out readFilter, parameters)) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("invalid_filter_name", filter)); return false; } stream.AddFilter(readFilter, where); readFilter.OnCreate(); // Add to chain, (filters buffers too). } if ((where & FilterChainOptions.Write) > 0) { if (!GetFilter(filter, true, out writeFilter, parameters)) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("invalid_filter_name", filter)); return false; } stream.AddFilter(writeFilter, where); writeFilter.OnCreate(); // Add to chain. } return true; } #endregion #region Implemented Filters /// <summary> /// Searches for a filter implementation in the known <see cref="PhpFilter"/> descendants. /// </summary> /// <param name="filter">The name of the filter (may contain wildcards).</param> /// <param name="instantiate"><c>true</c> to fille <paramref name="instance"/> with a new instance of that filter.</param> /// <param name="instance">Filled with a new instance of an implemented filter if <paramref name="instantiate"/>.</param> /// <param name="parameters">Additional parameters for the filter.</param> /// <returns><c>true</c> if a filter with the given name was found.</returns> internal static bool GetFilter(string filter, bool instantiate, out PhpFilter instance, object parameters) { instance = null; foreach (IFilterFactory factory in systemFilters) if (factory.GetImplementedFilter(filter, instantiate, out instance, parameters)) { if (instance != null) instance.FilterName = filter; return true; } // Note: the registered filter names may be wildcards - use fnmatch. if ((UserFilters != null) && (UserFilters.Contains(filter))) { if (instantiate) { // EX: [PhpFilter.GetFilter] create a new user filter; and support the WILDCARD naming too. } return true; } return false; } /// <summary> /// Registers a user stream filter. /// </summary> /// <param name="filter">The name of the filter (may contain wildcards).</param> /// <param name="classname">The PHP user class (derived from <c>php_user_filter</c>) implementing the filter.</param> /// <returns><c>true</c> if the filter was succesfully added, <c>false</c> if the filter of such name already exists.</returns> public static bool AddUserFilter(string filter, string classname) { // Note: have to check for wildcard conflicts too (?) PhpFilter instance; if (GetFilter(filter, false, out instance, null)) { // EX: [PhpFilter.Register] stringtable - filter already exists, check the filter name string? return false; } // Check the given filter for validity? UserFilters.Add(filter, classname); return true; } /// <summary> /// Register a built-in stream filter factory. /// </summary> /// <param name="factory">The filter factory.</param> /// <returns><c>true</c> if successfully added.</returns> public static bool AddSystemFilter(IFilterFactory factory) { PhpFilter instance; bool ok = true; foreach (string filter in factory.GetImplementedFilterNames()) if (GetFilter(filter, false, out instance, null)) ok = false; Debug.Assert(ok); systemFilters.Add(factory); return ok; } /// <summary> /// Merges the individual string[] into one PhpArray (numeric keys). /// </summary> /// <param name="filterList">List of filter name <see cref="string"/>s.</param> /// <param name="rv">Return value loopback (pass <c>null</c> to create new).</param> /// <returns></returns> private static PhpArray MergeFilterNames(ICollection filterList, PhpArray rv) { if (rv == null) rv = new PhpArray(8, 0); if (filterList != null) { foreach (string name in filterList) rv.Add(name); } return rv; } /// <summary> /// Retrieves the list of registered filters. /// </summary> /// <returns>A <see cref="PhpArray"/> containing the names of available filters.</returns> public static PhpArray GetFilterNames() { PhpArray rv = null; foreach (IFilterFactory factory in systemFilters) MergeFilterNames(factory.GetImplementedFilterNames(), rv); return MergeFilterNames((UserFilters != null) ? UserFilters.Keys : null, rv); } /// <summary> /// Gets or sets the collection of user filtername:classname associations. /// </summary> private static Hashtable UserFilters { get { return userFilters; // EX: store userfilters in ScriptContext. } set { userFilters = value; } } /// <summary>The list of (script-specific) user filters.</summary> #if SILVERLIGHT //TODO: Silverlight doesn't have ThreadStatic, it should be done it in different way... now output is just a normal field private static Hashtable userFilters = null;// { get { return tsuserFilters.Value; } set { tsuserFilters.Value = value; } } //private static ThreadStatic<Hashtable> tsuserFilters = new ThreadStatic<Hashtable>("PhpFilter.userFilters"); /// <summary>The list of built-in filters.</summary> //TODO: It should be synchronized version of ArrayList here. private static ArrayList systemFilters = new ArrayList(); #else [ThreadStatic] private static Hashtable userFilters = null; /// <summary>The list of built-in filters.</summary> private static ArrayList systemFilters = ArrayList.Synchronized(new ArrayList()); #endif #endregion } #endregion }
using System; using System.IO; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; namespace Org.BouncyCastle.Crypto.Tls { internal class TlsPskKeyExchange : TlsKeyExchange { protected TlsClientContext context; protected KeyExchangeAlgorithm keyExchange; protected TlsPskIdentity pskIdentity; protected byte[] psk_identity_hint = null; protected DHPublicKeyParameters dhAgreeServerPublicKey = null; protected DHPrivateKeyParameters dhAgreeClientPrivateKey = null; protected AsymmetricKeyParameter serverPublicKey = null; protected RsaKeyParameters rsaServerPublicKey = null; protected byte[] premasterSecret; internal TlsPskKeyExchange(TlsClientContext context, KeyExchangeAlgorithm keyExchange, TlsPskIdentity pskIdentity) { switch (keyExchange) { case KeyExchangeAlgorithm.PSK: case KeyExchangeAlgorithm.RSA_PSK: case KeyExchangeAlgorithm.DHE_PSK: break; default: throw new ArgumentException("unsupported key exchange algorithm", "keyExchange"); } this.context = context; this.keyExchange = keyExchange; this.pskIdentity = pskIdentity; } public virtual void SkipServerCertificate() { if (keyExchange == KeyExchangeAlgorithm.RSA_PSK) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } } public virtual void ProcessServerCertificate(Certificate serverCertificate) { if (keyExchange != KeyExchangeAlgorithm.RSA_PSK) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo; try { this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo); } // catch (RuntimeException) catch (Exception) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.IsPrivate) { throw new TlsFatalAlert(AlertDescription.internal_error); } this.rsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.serverPublicKey); TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment); // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ } public virtual void SkipServerKeyExchange() { if (keyExchange == KeyExchangeAlgorithm.DHE_PSK) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } this.psk_identity_hint = new byte[0]; } public virtual void ProcessServerKeyExchange(Stream input) { this.psk_identity_hint = TlsUtilities.ReadOpaque16(input); if (this.keyExchange == KeyExchangeAlgorithm.DHE_PSK) { byte[] pBytes = TlsUtilities.ReadOpaque16(input); byte[] gBytes = TlsUtilities.ReadOpaque16(input); byte[] YsBytes = TlsUtilities.ReadOpaque16(input); BigInteger p = new BigInteger(1, pBytes); BigInteger g = new BigInteger(1, gBytes); BigInteger Ys = new BigInteger(1, YsBytes); this.dhAgreeServerPublicKey = TlsDHUtilities.ValidateDHPublicKey( new DHPublicKeyParameters(Ys, new DHParameters(p, g))); } else if (this.psk_identity_hint.Length == 0) { // TODO Should we enforce that this message should have been skipped if hint is empty? //throw new TlsFatalAlert(AlertDescription.unexpected_message); } } public virtual void ValidateCertificateRequest(CertificateRequest certificateRequest) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } public virtual void SkipClientCredentials() { // OK } public virtual void ProcessClientCredentials(TlsCredentials clientCredentials) { throw new TlsFatalAlert(AlertDescription.internal_error); } public virtual void GenerateClientKeyExchange(Stream output) { if (psk_identity_hint == null || psk_identity_hint.Length == 0) { pskIdentity.SkipIdentityHint(); } else { pskIdentity.NotifyIdentityHint(psk_identity_hint); } byte[] psk_identity = pskIdentity.GetPskIdentity(); TlsUtilities.WriteOpaque16(psk_identity, output); if (this.keyExchange == KeyExchangeAlgorithm.RSA_PSK) { this.premasterSecret = TlsRsaUtilities.GenerateEncryptedPreMasterSecret( context.SecureRandom, this.rsaServerPublicKey, output); } else if (this.keyExchange == KeyExchangeAlgorithm.DHE_PSK) { this.dhAgreeClientPrivateKey = TlsDHUtilities.GenerateEphemeralClientKeyExchange( context.SecureRandom, this.dhAgreeServerPublicKey.Parameters, output); } } public virtual byte[] GeneratePremasterSecret() { byte[] psk = pskIdentity.GetPsk(); byte[] other_secret = GenerateOtherSecret(psk.Length); MemoryStream buf = new MemoryStream(4 + other_secret.Length + psk.Length); TlsUtilities.WriteOpaque16(other_secret, buf); TlsUtilities.WriteOpaque16(psk, buf); return buf.ToArray(); } protected virtual byte[] GenerateOtherSecret(int pskLength) { if (this.keyExchange == KeyExchangeAlgorithm.DHE_PSK) { return TlsDHUtilities.CalculateDHBasicAgreement(dhAgreeServerPublicKey, dhAgreeClientPrivateKey); } if (this.keyExchange == KeyExchangeAlgorithm.RSA_PSK) { return this.premasterSecret; } return new byte[pskLength]; } protected virtual RsaKeyParameters ValidateRsaPublicKey(RsaKeyParameters key) { // TODO What is the minimum bit length required? // key.Modulus.BitLength; if (!key.Exponent.IsProbablePrime(2)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } return key; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Channels; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using SoapCore.ServiceModel; namespace SoapCore.Meta { public class MetaWCFBodyWriter : BodyWriter { #pragma warning disable SA1009 // Closing parenthesis must be spaced correctly #pragma warning disable SA1008 // Opening parenthesis must be spaced correctly private static readonly Dictionary<string, (string, string)> SysTypeDic = new Dictionary<string, (string, string)>() { ["System.String"] = ("string", Namespaces.SYSTEM_NS), ["System.Boolean"] = ("boolean", Namespaces.SYSTEM_NS), ["System.Int16"] = ("short", Namespaces.SYSTEM_NS), ["System.Int32"] = ("int", Namespaces.SYSTEM_NS), ["System.Int64"] = ("long", Namespaces.SYSTEM_NS), ["System.Byte"] = ("byte", Namespaces.SYSTEM_NS), ["System.SByte"] = ("byte", Namespaces.SYSTEM_NS), ["System.UInt16"] = ("unsignedShort", Namespaces.SYSTEM_NS), ["System.UInt32"] = ("unsignedInt", Namespaces.SYSTEM_NS), ["System.UInt64"] = ("unsignedLong", Namespaces.SYSTEM_NS), ["System.Decimal"] = ("decimal", Namespaces.SYSTEM_NS), ["System.Double"] = ("double", Namespaces.SYSTEM_NS), ["System.Single"] = ("float", Namespaces.SYSTEM_NS), ["System.DateTime"] = ("dateTime", Namespaces.SYSTEM_NS), ["System.Guid"] = ("guid", Namespaces.SERIALIZATION_NS), ["System.Char"] = ("char", Namespaces.SERIALIZATION_NS), ["System.TimeSpan"] = ("duration", Namespaces.SERIALIZATION_NS), ["System.Object"] = ("anyType", Namespaces.SERIALIZATION_NS), ["System.Uri"] = ("anyUri", Namespaces.SERIALIZATION_NS), }; #pragma warning restore SA1008 // Opening parenthesis must be spaced correctly #pragma warning restore SA1009 // Closing parenthesis must be spaced correctly private static int _namespaceCounter = 1; private readonly ServiceDescription _service; private readonly string _baseUrl; private readonly string[] _numbers = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; private readonly Dictionary<Type, string> _complexTypeToBuild = new Dictionary<Type, string>(); private readonly HashSet<Type> _complexTypeProcessed = new HashSet<Type>(); // Contains types that have been discovered private readonly Queue<Type> _arrayToBuild; private readonly HashSet<string> _builtEnumTypes; private readonly HashSet<string> _builtComplexTypes; private readonly HashSet<string> _buildArrayTypes; private readonly HashSet<string> _builtSerializationElements; private bool _buildDateTimeOffset; private bool _buildDataTable; private string _schemaNamespace; [Obsolete] public MetaWCFBodyWriter(ServiceDescription service, string baseUrl, Binding binding) : this( service, baseUrl, binding?.Name ?? "BasicHttpBinding_" + service.GeneralContract.Name, binding.HasBasicAuth()) { } public MetaWCFBodyWriter(ServiceDescription service, string baseUrl, string bindingName, bool hasBasicAuthentication) : base(isBuffered: true) { _service = service; _baseUrl = baseUrl; _arrayToBuild = new Queue<Type>(); _builtEnumTypes = new HashSet<string>(); _builtComplexTypes = new HashSet<string>(); _buildArrayTypes = new HashSet<string>(); _builtSerializationElements = new HashSet<string>(); BindingType = service.GeneralContract.Name; TargetNameSpace = service.GeneralContract.Namespace; BindingName = bindingName; PortName = bindingName; HasBasicAuthentication = hasBasicAuthentication; } private bool HasBasicAuthentication { get; } private string BindingName { get; } private string BindingType { get; } private string PortName { get; } private string TargetNameSpace { get; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { AddTypes(writer); AddMessages(writer); AddPortType(writer); AddBinding(writer); AddService(writer); } private static string GetModelNamespace(string @namespace) { if (@namespace.StartsWith("http")) { return @namespace; } return $"{Namespaces.DataContractNamespace}{@namespace}"; } private static string GetDataContractNamespace(Type type) { if (type.IsArray || typeof(IEnumerable).IsAssignableFrom(type)) { var collectionDataContractAttribute = type.GetCustomAttribute<CollectionDataContractAttribute>(); if (collectionDataContractAttribute != null && collectionDataContractAttribute.IsNamespaceSetExplicitly) { return collectionDataContractAttribute.Namespace; } else { type = type.IsArray ? type.GetElementType() : GetGenericType(type); } } var dataContractAttribute = type.GetCustomAttribute<DataContractAttribute>(); if (dataContractAttribute != null && dataContractAttribute.IsNamespaceSetExplicitly) { return dataContractAttribute.Namespace; } return GetModelNamespace(type.Namespace); } private static Type GetGenericType(Type collectionType) { return GetGenericTypes(collectionType).DefaultIfEmpty(typeof(object)).FirstOrDefault(); } private static Type[] GetGenericTypes(Type collectionType) { // Recursively look through the base class to find the Generic Type of the Enumerable var baseType = collectionType; var collectionInterfaceTypeInfo = baseType.GetInterfaces().Where(a => a.Name == "ICollection`1").FirstOrDefault(); if (collectionInterfaceTypeInfo != null) { //handle Dictionary KeyValuePair's and other collections with more than one generic parameter as a simple return type return collectionInterfaceTypeInfo.GetGenericArguments(); } var baseTypeInfo = collectionType.GetTypeInfo(); while (!baseTypeInfo.IsGenericType && baseTypeInfo.BaseType != null) { baseType = baseTypeInfo.BaseType; baseTypeInfo = baseType.GetTypeInfo(); } return baseType.GetTypeInfo().GetGenericArguments(); } private string GetModelNamespace(Type type) { if (type != null && type.Namespace != _service.ServiceType.Namespace) { return $"{Namespaces.DataContractNamespace}{type.Namespace}"; } return $"{Namespaces.DataContractNamespace}{_service.ServiceType.Namespace}"; } private void WriteParameters(XmlDictionaryWriter writer, SoapMethodParameterInfo[] parameterInfos) { foreach (var parameterInfo in parameterInfos) { var elementAttribute = parameterInfo.Parameter.GetCustomAttribute<XmlElementAttribute>(); var parameterName = !string.IsNullOrEmpty(elementAttribute?.ElementName) ? elementAttribute.ElementName : parameterInfo.Parameter.GetCustomAttribute<MessageParameterAttribute>()?.Name ?? parameterInfo.Parameter.Name; var isRequired = !parameterInfo.Parameter.IsOptional; AddSchemaType(writer, parameterInfo.Parameter.ParameterType, parameterName, objectNamespace: elementAttribute?.Namespace ?? (parameterInfo.Namespace != "http://tempuri.org/" ? parameterInfo.Namespace : null), isRequired: isRequired); } } private void EnsureServiceKnownTypes(IEnumerable<ServiceKnownTypeAttribute> serviceKnownTypes) { foreach (ServiceKnownTypeAttribute knownType in serviceKnownTypes) { if (knownType.Type is null) { throw new NotSupportedException($"Only type property of `{nameof(ServiceKnownTypeAttribute)}` is supported."); } // Add service known type _complexTypeToBuild[knownType.Type] = GetDataContractNamespace(knownType.Type); // Discover type known types DiscoverTypes(knownType.Type, false); } } private void AddContractOperations(XmlDictionaryWriter writer, ContractDescription contract) { IEnumerable<OperationDescription> operations = contract.Operations; writer.WriteStartElement("xs", "schema", Namespaces.XMLNS_XSD); writer.WriteAttributeString("elementFormDefault", "qualified"); writer.WriteAttributeString("targetNamespace", contract.Namespace); writer.WriteXmlnsAttribute("xs", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute("ser", Namespaces.SERIALIZATION_NS); _schemaNamespace = TargetNameSpace; _namespaceCounter = 1; //discovery all parameters types which namespaceses diff with service namespace foreach (OperationDescription operation in operations) { // Ensure operation service known type attributes EnsureServiceKnownTypes(operation.ServiceKnownTypes); foreach (var parameter in operation.AllParameters) { var type = parameter.Parameter.ParameterType; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsByRef) { type = typeInfo.GetElementType(); } if (TypeIsComplexForWsdl(type, out type)) { _complexTypeToBuild[type] = GetDataContractNamespace(type); DiscoverTypes(type, true); } else if (type.IsEnum || Nullable.GetUnderlyingType(type)?.IsEnum == true) { _complexTypeToBuild[type] = GetDataContractNamespace(type); DiscoverTypes(type, true); } } if (operation.DispatchMethod.ReturnType != typeof(void) && operation.DispatchMethod.ReturnType != typeof(Task)) { var returnType = operation.DispatchMethod.ReturnType; if (returnType.IsConstructedGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>)) { returnType = returnType.GetGenericArguments().First(); } if (TypeIsComplexForWsdl(returnType, out returnType)) { _complexTypeToBuild[returnType] = GetDataContractNamespace(returnType); DiscoverTypes(returnType, true); } else if (returnType.IsEnum || Nullable.GetUnderlyingType(returnType)?.IsEnum == true) { _complexTypeToBuild[returnType] = GetDataContractNamespace(returnType); DiscoverTypes(returnType, true); } } } var groupedByNamespace = _complexTypeToBuild.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.Select(k => k.Key)); foreach (var @namespace in groupedByNamespace.Keys.Where(x => x != null && x != _service.ServiceType.Namespace).Distinct()) { writer.WriteStartElement("xs", "import", Namespaces.XMLNS_XSD); writer.WriteAttributeString("namespace", @namespace); writer.WriteEndElement(); } foreach (OperationDescription operation in operations) { // input parameters of operation writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", operation.Name); writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD); WriteParameters(writer, operation.InParameters); writer.WriteEndElement(); // xs:sequence writer.WriteEndElement(); // xs:complexType writer.WriteEndElement(); // xs:element // output parameter / return of operation writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", operation.Name + "Response"); writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD); if (operation.DispatchMethod.ReturnType != typeof(void) && operation.DispatchMethod.ReturnType != typeof(Task)) { var returnType = operation.DispatchMethod.ReturnType; if (returnType.IsConstructedGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>)) { returnType = returnType.GetGenericArguments().First(); } var returnName = operation.DispatchMethod.ReturnParameter.GetCustomAttribute<MessageParameterAttribute>()?.Name ?? operation.Name + "Result"; var isRequired = !operation.DispatchMethod.ReturnParameter.IsOptional; AddSchemaType(writer, returnType, returnName, false, GetDataContractNamespace(returnType), isRequired: isRequired); } WriteParameters(writer, operation.OutParameters); writer.WriteEndElement(); // xs:sequence writer.WriteEndElement(); // xs:complexType writer.WriteEndElement(); // xs:element AddFaultTypes(writer, operation); } writer.WriteEndElement(); // xs:schema } private void AddFaultTypes(XmlDictionaryWriter writer, OperationDescription operation) { foreach (var faultType in operation.Faults) { if (_complexTypeProcessed.Contains(faultType)) { continue; } _complexTypeToBuild[faultType] = GetDataContractNamespace(faultType); DiscoverTypes(faultType, true); } } private void AddTypes(XmlDictionaryWriter writer) { writer.WriteStartElement("wsdl", "types", Namespaces.WSDL_NS); // Ensure service known type attributes // TODO: should we parse only contact attributes ?? EnsureServiceKnownTypes(_service.ServiceKnownTypes); // Ensure service contract service known type attributes EnsureServiceKnownTypes(_service.Contracts.SelectMany(x => x.ServiceKnownTypes)); foreach (ContractDescription contract in _service.Contracts) { AddContractOperations(writer, contract); } AddMSSerialization(writer); AddComplexTypes(writer); AddArrayTypes(writer); AddSystemTypes(writer); writer.WriteEndElement(); } private void AddSystemTypes(XmlDictionaryWriter writer) { if (_buildDateTimeOffset) { writer.WriteStartElement("xs", "schema", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute("xs", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute("tns", Namespaces.SYSTEM_NS); writer.WriteAttributeString("elementFormDefault", "qualified"); writer.WriteAttributeString("targetNamespace", Namespaces.SYSTEM_NS); writer.WriteStartElement("xs", "import", Namespaces.XMLNS_XSD); writer.WriteAttributeString("namespace", Namespaces.SERIALIZATION_NS); writer.WriteEndElement(); writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "DateTimeOffset"); writer.WriteStartElement("xs", "annotation", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "appinfo", Namespaces.XMLNS_XSD); writer.WriteElementString("IsValueType", Namespaces.SERIALIZATION_NS, "true"); writer.WriteEndElement(); // xs:appinfo writer.WriteEndElement(); // xs:annotation writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "DateTime"); writer.WriteAttributeString("type", "xs:dateTime"); writer.WriteEndElement(); writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "OffsetMinutes"); writer.WriteAttributeString("type", "xs:short"); writer.WriteEndElement(); writer.WriteEndElement(); // xs:sequence writer.WriteEndElement(); // xs:complexType writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "DateTimeOffset"); writer.WriteAttributeString("nillable", "true"); writer.WriteAttributeString("type", "tns:DateTimeOffset"); writer.WriteEndElement(); writer.WriteEndElement(); // xs:schema } if (_buildDataTable) { writer.WriteStartElement("xs", "schema", Namespaces.XMLNS_XSD); writer.WriteAttributeString("elementFormDefault", "qualified"); writer.WriteAttributeString("targetNamespace", Namespaces.SystemData_NS); writer.WriteXmlnsAttribute("xs", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute("tns", Namespaces.SystemData_NS); writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "DataTable"); writer.WriteAttributeString("nillable", "true"); writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "annotation", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "appinfo", Namespaces.XMLNS_XSD); writer.WriteStartElement("ActualType"); writer.WriteAttributeString("xmlns", Namespaces.SERIALIZATION_NS); writer.WriteAttributeString("Name", "DataTable"); writer.WriteAttributeString("Namespace", Namespaces.SystemData_NS); writer.WriteEndElement(); //actual type writer.WriteEndElement(); //appinfo writer.WriteEndElement(); //annotation writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "any", Namespaces.XMLNS_XSD); writer.WriteAttributeString("minOccurs", "0"); writer.WriteAttributeString("maxOccurs", "unbounded"); writer.WriteAttributeString("namespace", Namespaces.XMLNS_XSD); writer.WriteAttributeString("processContents", "lax"); writer.WriteEndElement(); //any writer.WriteStartElement("xs", "any", Namespaces.XMLNS_XSD); writer.WriteAttributeString("minOccurs", "1"); writer.WriteAttributeString("namespace", "urn:schemas-microsoft-com:xml-diffgram-v1"); writer.WriteAttributeString("processContents", "lax"); writer.WriteEndElement(); //any writer.WriteEndElement(); //sequence writer.WriteEndElement(); //complexType writer.WriteEndElement(); //element writer.WriteEndElement(); //schema } } private void AddArrayTypes(XmlDictionaryWriter writer) { writer.WriteStartElement("xs", "schema", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute("xs", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute("tns", Namespaces.ARRAYS_NS); writer.WriteXmlnsAttribute("ser", Namespaces.SERIALIZATION_NS); writer.WriteAttributeString("elementFormDefault", "qualified"); writer.WriteAttributeString("targetNamespace", Namespaces.ARRAYS_NS); _namespaceCounter = 1; _schemaNamespace = Namespaces.ARRAYS_NS; writer.WriteStartElement("xs", "import", Namespaces.XMLNS_XSD); writer.WriteAttributeString("namespace", Namespaces.SERIALIZATION_NS); writer.WriteEndElement(); while (_arrayToBuild.Count > 0) { var toBuild = _arrayToBuild.Dequeue(); var elType = toBuild.IsArray ? toBuild.GetElementType() : GetGenericType(toBuild); var sysType = ResolveSystemType(elType); var toBuildName = "ArrayOf" + sysType.name; if (!_buildArrayTypes.Contains(toBuildName)) { writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", toBuildName); writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD); AddSchemaType(writer, elType, null, true); writer.WriteEndElement(); // :sequence writer.WriteEndElement(); // xs:complexType writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", toBuildName); writer.WriteAttributeString("nillable", "true"); writer.WriteAttributeString("type", "tns:" + toBuildName); writer.WriteEndElement(); // xs:element _buildArrayTypes.Add(toBuildName); } } writer.WriteEndElement(); // xs:schema } private void AddMSSerialization(XmlDictionaryWriter writer) { writer.WriteStartElement("xs", "schema", Namespaces.XMLNS_XSD); writer.WriteAttributeString("attributeFormDefault", "qualified"); writer.WriteAttributeString("elementFormDefault", "qualified"); writer.WriteAttributeString("targetNamespace", Namespaces.SERIALIZATION_NS); writer.WriteXmlnsAttribute("xs", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute("tns", Namespaces.SERIALIZATION_NS); WriteSerializationElement(writer, "anyType", "xs:anyType", true); WriteSerializationElement(writer, "anyURI", "xs:anyURI", true); WriteSerializationElement(writer, "base64Binary", "xs:base64Binary", true); WriteSerializationElement(writer, "boolean", "xs:boolean", true); WriteSerializationElement(writer, "byte", "xs:byte", true); WriteSerializationElement(writer, "dateTime", "xs:dateTime", true); WriteSerializationElement(writer, "decimal", "xs:decimal", true); WriteSerializationElement(writer, "double", "xs:double", true); WriteSerializationElement(writer, "float", "xs:float", true); WriteSerializationElement(writer, "int", "xs:int", true); WriteSerializationElement(writer, "long", "xs:long", true); WriteSerializationElement(writer, "QName", "xs:QName", true); WriteSerializationElement(writer, "short", "xs:short", true); WriteSerializationElement(writer, "string", "xs:string", true); WriteSerializationElement(writer, "unsignedByte", "xs:unsignedByte", true); WriteSerializationElement(writer, "unsignedInt", "xs:unsignedInt", true); WriteSerializationElement(writer, "unsignedLong", "xs:unsignedLong", true); WriteSerializationElement(writer, "unsignedShort", "xs:unsignedShort", true); WriteSerializationElement(writer, "char", "tns:char", true); writer.WriteStartElement("xs", "simpleType", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "char"); writer.WriteStartElement("xs", "restriction", Namespaces.XMLNS_XSD); writer.WriteAttributeString("base", "xs:int"); writer.WriteEndElement(); writer.WriteEndElement(); WriteSerializationElement(writer, "duration", "tns:duration", true); writer.WriteStartElement("xs", "simpleType", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "duration"); writer.WriteStartElement("xs", "restriction", Namespaces.XMLNS_XSD); writer.WriteAttributeString("base", "xs:duration"); writer.WriteStartElement("xs", "pattern", Namespaces.XMLNS_XSD); writer.WriteAttributeString("value", @"\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?"); writer.WriteEndElement(); writer.WriteStartElement("xs", "minInclusive", Namespaces.XMLNS_XSD); writer.WriteAttributeString("value", @"-P10675199DT2H48M5.4775808S"); writer.WriteEndElement(); writer.WriteStartElement("xs", "maxInclusive", Namespaces.XMLNS_XSD); writer.WriteAttributeString("value", @"P10675199DT2H48M5.4775807S"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); WriteSerializationElement(writer, "guid", "tns:guid", true); writer.WriteStartElement("xs", "simpleType", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "guid"); writer.WriteStartElement("xs", "restriction", Namespaces.XMLNS_XSD); writer.WriteAttributeString("base", "xs:string"); writer.WriteStartElement("xs", "pattern", Namespaces.XMLNS_XSD); writer.WriteAttributeString("value", @"[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("xs", "attribute", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "FactoryType"); writer.WriteAttributeString("type", "xs:QName"); writer.WriteEndElement(); writer.WriteStartElement("xs", "attribute", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "Id"); writer.WriteAttributeString("type", "xs:ID"); writer.WriteEndElement(); writer.WriteStartElement("xs", "attribute", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", "Ref"); writer.WriteAttributeString("type", "xs:IDREF"); writer.WriteEndElement(); writer.WriteEndElement(); //schema } private void WriteSerializationElement(XmlDictionaryWriter writer, string name, string type, bool nillable) { if (!_builtSerializationElements.Contains(name)) { writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", name); writer.WriteAttributeString("nillable", nillable ? "true" : "false"); writer.WriteAttributeString("type", type); writer.WriteEndElement(); _builtSerializationElements.Add(name); } } private void AddComplexTypes(XmlDictionaryWriter writer) { foreach (var type in _complexTypeToBuild.ToArray()) { _complexTypeToBuild[type.Key] = GetDataContractNamespace(type.Key); DiscoverTypes(type.Key, true); } var groupedByNamespace = _complexTypeToBuild.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.Select(k => k.Key)); foreach (var types in groupedByNamespace.Distinct()) { writer.WriteStartElement("xs", "schema", Namespaces.XMLNS_XSD); writer.WriteAttributeString("elementFormDefault", "qualified"); writer.WriteAttributeString("targetNamespace", GetModelNamespace(types.Key)); writer.WriteXmlnsAttribute("xs", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute("tns", GetModelNamespace(types.Key)); writer.WriteXmlnsAttribute("ser", Namespaces.SERIALIZATION_NS); _namespaceCounter = 1; _schemaNamespace = GetModelNamespace(types.Key); writer.WriteStartElement("xs", "import", Namespaces.XMLNS_XSD); writer.WriteAttributeString("namespace", Namespaces.SYSTEM_NS); writer.WriteEndElement(); writer.WriteStartElement("xs", "import", Namespaces.XMLNS_XSD); writer.WriteAttributeString("namespace", Namespaces.ARRAYS_NS); writer.WriteEndElement(); foreach (var type in types.Value.Distinct(new TypesComparer(GetTypeName))) { if (type.IsEnum) { WriteEnum(writer, type); } else { WriteComplexType(writer, type); } writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", GetTypeName(type)); if (!type.IsEnum || Nullable.GetUnderlyingType(type) != null) { writer.WriteAttributeString("nillable", "true"); } writer.WriteAttributeString("type", "tns:" + GetTypeName(type)); writer.WriteEndElement(); // xs:element } writer.WriteEndElement(); } } private void DiscoverTypes(Type type, bool isRootType) { //guard against infinity recursion //check is made against _complexTypeProcessed, which contains types that have been //discovered by the current method if (_complexTypeProcessed.Contains(type)) { return; } if (type == typeof(DateTimeOffset)) { return; } //type will be processed, so can be added to _complexTypeProcessed _complexTypeProcessed.Add(type); // discover known types IEnumerable<KnownTypeAttribute> knownTypes = type.GetCustomAttributes<KnownTypeAttribute>(inherit: false); foreach (KnownTypeAttribute knownType in knownTypes) { if (knownType.Type is null) { throw new NotSupportedException($"Only type property of `{nameof(KnownTypeAttribute)}` is supported."); } // add known type _complexTypeToBuild[knownType.Type] = GetDataContractNamespace(knownType.Type); // discover recursive DiscoverTypes(knownType.Type, false); } if (HasBaseType(type) && type.BaseType != null) { _complexTypeToBuild[type.BaseType] = GetDataContractNamespace(type.BaseType); DiscoverTypes(type.BaseType, false); } if ((type.IsArray || typeof(IEnumerable).IsAssignableFrom(type)) && type.IsGenericType) { var genericType = GetGenericType(type); var (name, _) = ResolveSystemType(genericType); if (string.IsNullOrEmpty(name)) { _complexTypeToBuild[genericType] = GetDataContractNamespace(genericType); DiscoverTypes(genericType, true); } } foreach (var member in type.GetPropertyOrFieldMembers().Where(mi => mi.DeclaringType == type && mi.CustomAttributes.All(attr => attr.AttributeType.Name != "IgnoreDataMemberAttribute") && (!mi.DeclaringType.CustomAttributes.Any(x => x.AttributeType == typeof(DataContractAttribute)) || mi.CustomAttributes.Any(x => x.AttributeType == typeof(DataMemberAttribute))) && !mi.GetPropertyOrFieldType().IsPrimitive && !SysTypeDic.ContainsKey(mi.GetPropertyOrFieldType().FullName) && mi.GetPropertyOrFieldType() != typeof(ValueType) && mi.GetPropertyOrFieldType() != typeof(DateTimeOffset))) { Type memberType; var underlyingType = Nullable.GetUnderlyingType(member.GetPropertyOrFieldType()); if (Nullable.GetUnderlyingType(member.GetPropertyOrFieldType()) != null) { memberType = underlyingType; } else if (member.GetPropertyOrFieldType().IsArray || typeof(IEnumerable).IsAssignableFrom(member.GetPropertyOrFieldType())) { memberType = member.GetPropertyOrFieldType().IsArray ? member.GetPropertyOrFieldType().GetElementType() : GetGenericType(member.GetPropertyOrFieldType()); _complexTypeToBuild[member.GetPropertyOrFieldType()] = GetDataContractNamespace(member.GetPropertyOrFieldType()); } else { memberType = member.GetPropertyOrFieldType(); } if (memberType != null && !memberType.IsPrimitive && !SysTypeDic.ContainsKey(memberType.FullName)) { if (memberType == type) { continue; } _complexTypeToBuild[memberType] = GetDataContractNamespace(memberType); DiscoverTypes(memberType, false); } } } private void WriteEnum(XmlDictionaryWriter writer, Type type) { if (type.IsByRef) { type = type.GetElementType(); } var typeName = GetTypeName(type); if (!_builtEnumTypes.Contains(typeName)) { writer.WriteStartElement("xs", "simpleType", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", typeName); writer.WriteStartElement("xs", "restriction", Namespaces.XMLNS_XSD); writer.WriteAttributeString("base", "xs:string"); foreach (var name in Enum.GetNames(type)) { writer.WriteStartElement("xs", "enumeration", Namespaces.XMLNS_XSD); // Search for EnumMember attribute. If available, get enum value from its Value field var enumMemberAttribute = ((EnumMemberAttribute[])type.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).SingleOrDefault(); var value = enumMemberAttribute is null || !enumMemberAttribute.IsValueSetExplicitly ? name : enumMemberAttribute.Value; writer.WriteAttributeString("value", value); writer.WriteEndElement(); // xs:enumeration } writer.WriteEndElement(); // xs:restriction writer.WriteEndElement(); // xs:simpleType _builtEnumTypes.Add(typeName); } } private void WriteComplexType(XmlDictionaryWriter writer, Type type) { var toBuildName = GetTypeName(type); if (_builtComplexTypes.Contains(toBuildName)) { return; } writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD); writer.WriteAttributeString("name", toBuildName); writer.WriteAttributeString("xmlns", "ser", null, Namespaces.SERIALIZATION_NS); if (type.IsValueType && ResolveSystemType(type).name == null) { writer.WriteStartElement("xs", "annotation", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "appinfo", Namespaces.XMLNS_XSD); writer.WriteStartElement("IsValueType", Namespaces.SERIALIZATION_NS); writer.WriteValue(true); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); } var hasBaseType = HasBaseType(type); if (hasBaseType) { writer.WriteStartElement("xs", "complexContent", Namespaces.XMLNS_XSD); writer.WriteAttributeString("mixed", "false"); writer.WriteStartElement("xs", "extension", Namespaces.XMLNS_XSD); var modelNamespace = GetDataContractNamespace(type.BaseType); var typeName = GetTypeName(type.BaseType); if (_schemaNamespace != modelNamespace) { var ns = $"q{_namespaceCounter++}"; writer.WriteAttributeString("base", $"{ns}:{typeName}"); writer.WriteAttributeString("xmlns", ns, null, modelNamespace); } else { writer.WriteAttributeString("base", $"tns:{typeName}"); } } writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD); if (type.IsArray || typeof(IEnumerable).IsAssignableFrom(type)) { var elementType = type.IsArray ? type.GetElementType() : GetGenericType(type); string elementName = null; var collectionDataContractAttribute = type.GetCustomAttribute<CollectionDataContractAttribute>(); if (collectionDataContractAttribute != null && collectionDataContractAttribute.IsItemNameSetExplicitly) { elementName = collectionDataContractAttribute.ItemName; } AddSchemaType(writer, elementType, elementName, true, GetDataContractNamespace(type)); } else { var propertyOrFieldMembers = type.GetPropertyOrFieldMembers().Where(mi => mi.DeclaringType == type && mi.CustomAttributes.All(attr => attr.AttributeType.Name != "IgnoreDataMemberAttribute") && (!mi.DeclaringType.CustomAttributes.Any(x => x.AttributeType == typeof(DataContractAttribute)) || mi.CustomAttributes.Any(x => x.AttributeType == typeof(DataMemberAttribute)))); var dataMembersToWrite = new List<DataMemberDescription>(); //TODO: base type properties //TODO: enforce order attribute parameters foreach (var member in propertyOrFieldMembers) { var memberName = member.Name; var attributes = member.GetCustomAttributes(true); int order = 0; bool isRequired = false; foreach (var attr in attributes) { if (attr is DataMemberAttribute dataContractAttribute) { if (dataContractAttribute.IsNameSetExplicitly) { memberName = dataContractAttribute.Name; } if (dataContractAttribute.Order > 0) { order = dataContractAttribute.Order; } isRequired = dataContractAttribute.IsRequired; break; } } dataMembersToWrite.Add(new DataMemberDescription { Name = memberName, Type = member.GetPropertyOrFieldType(), Order = order, IsRequired = isRequired }); } foreach (var p in dataMembersToWrite.OrderBy(x => x.Order).ThenBy(p => p.Name, StringComparer.Ordinal)) { AddSchemaType(writer, p.Type, p.Name, false, GetDataContractNamespace(p.Type), p.IsRequired); } } writer.WriteEndElement(); // xs:sequence if (hasBaseType) { writer.WriteEndElement(); // xs:extension writer.WriteEndElement(); // xs:complexContent } writer.WriteEndElement(); // xs:complexType _builtComplexTypes.Add(toBuildName); } private void AddMessages(XmlDictionaryWriter writer) { foreach (var operation in _service.Operations) { // input writer.WriteStartElement("wsdl", "message", Namespaces.WSDL_NS); writer.WriteAttributeString("name", $"{BindingType}_{operation.Name}_InputMessage"); writer.WriteStartElement("wsdl", "part", Namespaces.WSDL_NS); writer.WriteAttributeString("name", "parameters"); string inputElement = "tns:" + operation.Name; if (operation.Contract.Name != BindingType) { var ns = $"q{_namespaceCounter++}"; writer.WriteXmlnsAttribute($"{ns}", operation.Contract.Namespace); inputElement = $"{ns}:{operation.Name}"; } writer.WriteAttributeString("element", inputElement); writer.WriteEndElement(); // wsdl:part writer.WriteEndElement(); // wsdl:message // output if (!operation.IsOneWay) { writer.WriteStartElement("wsdl", "message", Namespaces.WSDL_NS); writer.WriteAttributeString("name", $"{BindingType}_{operation.Name}_OutputMessage"); writer.WriteStartElement("wsdl", "part", Namespaces.WSDL_NS); writer.WriteAttributeString("name", "parameters"); string outputElement = "tns:" + operation.Name + "Response"; if (operation.Contract.Name != BindingType) { var ns = $"q{_namespaceCounter++}"; writer.WriteXmlnsAttribute($"{ns}", operation.Contract.Namespace); outputElement = $"{ns}:{operation.Name}Response"; } writer.WriteAttributeString("element", outputElement); writer.WriteEndElement(); // wsdl:part writer.WriteEndElement(); // wsdl:message } AddMessageFaults(writer, operation); } } private void AddMessageFaults(XmlDictionaryWriter writer, OperationDescription operation) { foreach (Type fault in operation.Faults) { writer.WriteStartElement("wsdl", "message", Namespaces.WSDL_NS); writer.WriteAttributeString("name", $"{BindingType}_{operation.Name}_{fault.Name}Fault_FaultMessage"); writer.WriteStartElement("wsdl", "part", Namespaces.WSDL_NS); writer.WriteAttributeString("name", "detail"); var ns = $"q{_namespaceCounter++}"; writer.WriteAttributeString("element", $"{ns}:{fault.Name}"); writer.WriteAttributeString("xmlns", ns, null, GetDataContractNamespace(fault)); writer.WriteEndElement(); // wsdl:part writer.WriteEndElement(); // wsdl:message } } private void AddPortType(XmlDictionaryWriter writer) { writer.WriteStartElement("wsdl", "portType", Namespaces.WSDL_NS); writer.WriteAttributeString("name", BindingType); foreach (var operation in _service.Operations) { writer.WriteStartElement("wsdl", "operation", Namespaces.WSDL_NS); writer.WriteAttributeString("name", operation.Name); writer.WriteStartElement("wsdl", "input", Namespaces.WSDL_NS); writer.WriteAttributeString("wsam", "Action", Namespaces.WSAM_NS, operation.SoapAction); writer.WriteAttributeString("message", $"tns:{BindingType}_{operation.Name}_InputMessage"); writer.WriteEndElement(); // wsdl:input if (!operation.IsOneWay) { writer.WriteStartElement("wsdl", "output", Namespaces.WSDL_NS); writer.WriteAttributeString("wsam", "Action", Namespaces.WSAM_NS, operation.SoapAction + "Response"); writer.WriteAttributeString("message", $"tns:{BindingType}_{operation.Name}_OutputMessage"); writer.WriteEndElement(); // wsdl:output } AddPortTypeFaults(writer, operation); writer.WriteEndElement(); // wsdl:operation } writer.WriteEndElement(); // wsdl:portType } private void AddPortTypeFaults(XmlDictionaryWriter writer, OperationDescription operation) { foreach (Type fault in operation.Faults) { writer.WriteStartElement("wsdl", "fault", Namespaces.WSDL_NS); writer.WriteAttributeString("wsam", "Action", Namespaces.WSAM_NS, $"{operation.SoapAction}{fault.Name}Fault"); writer.WriteAttributeString("name", $"{fault.Name}Fault"); writer.WriteAttributeString("message", $"tns:{_service.GeneralContract.Name}_{operation.Name}_{fault.Name}Fault_FaultMessage"); writer.WriteEndElement(); // wsdl:fault } } private void AddBinding(XmlDictionaryWriter writer) { writer.WriteStartElement("wsdl", "binding", Namespaces.WSDL_NS); writer.WriteAttributeString("name", BindingName); writer.WriteAttributeString("type", "tns:" + BindingType); if (HasBasicAuthentication) { writer.WriteStartElement("wsp", "PolicyReference", Namespaces.WSP_NS); writer.WriteAttributeString("URI", $"#{BindingName}_{BindingType}_policy"); writer.WriteEndElement(); } writer.WriteStartElement("soap", "binding", Namespaces.SOAP11_NS); writer.WriteAttributeString("transport", Namespaces.TRANSPORT_SCHEMA); writer.WriteEndElement(); // soap:binding foreach (var operation in _service.Operations) { writer.WriteStartElement("wsdl", "operation", Namespaces.WSDL_NS); writer.WriteAttributeString("name", operation.Name); writer.WriteStartElement("soap", "operation", Namespaces.SOAP11_NS); writer.WriteAttributeString("soapAction", operation.SoapAction); writer.WriteAttributeString("style", "document"); writer.WriteEndElement(); // soap:operation writer.WriteStartElement("wsdl", "input", Namespaces.WSDL_NS); writer.WriteStartElement("soap", "body", Namespaces.SOAP11_NS); writer.WriteAttributeString("use", "literal"); writer.WriteEndElement(); // soap:body writer.WriteEndElement(); // wsdl:input if (!operation.IsOneWay) { writer.WriteStartElement("wsdl", "output", Namespaces.WSDL_NS); writer.WriteStartElement("soap", "body", Namespaces.SOAP11_NS); writer.WriteAttributeString("use", "literal"); writer.WriteEndElement(); // soap:body writer.WriteEndElement(); // wsdl:output } AddBindingFaults(writer, operation); writer.WriteEndElement(); // wsdl:operation } writer.WriteEndElement(); // wsdl:binding } private void AddBindingFaults(XmlDictionaryWriter writer, OperationDescription operation) { foreach (Type fault in operation.Faults) { writer.WriteStartElement("wsdl", "fault", Namespaces.WSDL_NS); writer.WriteAttributeString("name", $"{fault.Name}Fault"); writer.WriteStartElement("soap", "fault", Namespaces.SOAP11_NS); writer.WriteAttributeString("use", "literal"); writer.WriteAttributeString("name", $"{fault.Name}Fault"); writer.WriteEndElement(); // soap:fault writer.WriteEndElement(); // wsdl:fault } } private void AddService(XmlDictionaryWriter writer) { writer.WriteStartElement("wsdl", "service", Namespaces.WSDL_NS); writer.WriteAttributeString("name", _service.ServiceName); writer.WriteStartElement("wsdl", "port", Namespaces.WSDL_NS); writer.WriteAttributeString("name", PortName); writer.WriteAttributeString("binding", "tns:" + BindingName); writer.WriteStartElement("soap", "address", Namespaces.SOAP11_NS); writer.WriteAttributeString("location", _baseUrl); writer.WriteEndElement(); // soap:address writer.WriteEndElement(); // wsdl:port } private void AddSchemaType(XmlDictionaryWriter writer, Type type, string name, bool isArray = false, string objectNamespace = null, bool isRequired = false) { var typeInfo = type.GetTypeInfo(); var typeName = GetTypeName(type); if (typeInfo.IsByRef) { type = typeInfo.GetElementType(); } if (writer.TryAddSchemaTypeFromXmlSchemaProviderAttribute(type, name, SoapSerializer.DataContractSerializer)) { return; } writer.WriteStartElement("xs", "element", Namespaces.XMLNS_XSD); if (objectNamespace == null) { objectNamespace = GetModelNamespace(type); } if (typeInfo.IsEnum || Nullable.GetUnderlyingType(typeInfo)?.IsEnum == true) { WriteComplexElementType(writer, typeName, _schemaNamespace, objectNamespace, type); if (string.IsNullOrEmpty(name)) { name = typeName; } writer.WriteAttributeString("name", name); if (isArray) { writer.WriteAttributeString("minOccurs", isRequired ? "1" : "0"); writer.WriteAttributeString("maxOccurs", "unbounded"); } } else if (type.IsValueType) { string xsTypename; if (typeof(DateTimeOffset).IsAssignableFrom(type)) { if (string.IsNullOrEmpty(name)) { name = typeName; } var ns = $"q{_namespaceCounter++}"; xsTypename = $"{ns}:{typeName}"; writer.WriteXmlnsAttribute($"{ns}", Namespaces.SYSTEM_NS); _buildDateTimeOffset = true; } else { Type underlyingType = Nullable.GetUnderlyingType(type); if (underlyingType != null) { objectNamespace = GetDataContractNamespace(underlyingType); typeName = GetTypeName(underlyingType); if (ResolveSystemType(underlyingType).name != null) { var sysType = ResolveSystemType(underlyingType); xsTypename = $"{(sysType.ns == Namespaces.SERIALIZATION_NS ? "ser" : "xs")}:{sysType.name}"; writer.WriteAttributeString("nillable", "true"); } else if (_schemaNamespace != objectNamespace) { var ns = $"q{_namespaceCounter++}"; writer.WriteXmlnsAttribute($"{ns}", GetDataContractNamespace(type)); xsTypename = $"{ns}:{typeName}"; } else { xsTypename = $"tns:{typeName}"; } } else { if (ResolveSystemType(type).name != null) { var sysType = ResolveSystemType(type); xsTypename = $"{(sysType.ns == Namespaces.SERIALIZATION_NS ? "ser" : "xs")}:{sysType.name}"; } else if (_schemaNamespace != objectNamespace) { var ns = $"q{_namespaceCounter++}"; writer.WriteXmlnsAttribute($"{ns}", GetDataContractNamespace(type)); xsTypename = $"{ns}:{typeName}"; } else { xsTypename = $"tns:{typeName}"; } } } writer.WriteAttributeString("minOccurs", isRequired ? "1" : "0"); if (isArray) { writer.WriteAttributeString("maxOccurs", "unbounded"); } if (string.IsNullOrEmpty(name)) { name = xsTypename.Split(':')[1]; } writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", xsTypename); } else { writer.WriteAttributeString("minOccurs", isRequired ? "1" : "0"); if (isArray) { writer.WriteAttributeString("maxOccurs", "unbounded"); } if (type.Name == "String" || type.Name == "String&") { if (string.IsNullOrEmpty(name)) { name = "string"; } writer.WriteAttributeString("name", name); writer.WriteAttributeString("nillable", "true"); writer.WriteAttributeString("type", "xs:string"); } else if (type.Name == "Object" || type.Name == "Object&") { if (string.IsNullOrEmpty(name)) { name = "anyType"; } writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", "xs:anyType"); } else if (type.Name == "Uri" || type.Name == "Uri&") { if (string.IsNullOrEmpty(name)) { name = "anyURI"; } // TODO: should we compare namespace to `System.Uri` or ensure type assembly is mscorelib/System writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", "xs:anyURI"); } else if (type == typeof(DataTable)) { _buildDataTable = true; writer.WriteAttributeString("name", name); writer.WriteAttributeString("nillable", "true"); writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "annotation", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "appinfo", Namespaces.XMLNS_XSD); writer.WriteStartElement("ActualType"); writer.WriteAttributeString("xmlns", Namespaces.SERIALIZATION_NS); writer.WriteAttributeString("Name", "DataTable"); writer.WriteAttributeString("Namespace", Namespaces.SystemData_NS); writer.WriteEndElement(); //actual type writer.WriteEndElement(); // appinfo writer.WriteEndElement(); //annotation writer.WriteEndElement(); //complex type writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD); writer.WriteStartElement("xs", "any", Namespaces.XMLNS_XSD); writer.WriteAttributeString("minOccurs", "0"); writer.WriteAttributeString("maxOccurs", "unbounded"); writer.WriteAttributeString("namespace", Namespaces.XMLNS_XSD); writer.WriteAttributeString("processContents", "lax"); writer.WriteEndElement(); writer.WriteStartElement("xs", "any", Namespaces.XMLNS_XSD); writer.WriteAttributeString("minOccurs", "1"); writer.WriteAttributeString("namespace", "urn:schemas-microsoft-com:xml-diffgram-v1"); writer.WriteAttributeString("processContents", "lax"); writer.WriteEndElement(); writer.WriteEndElement(); //sequence } else if (type.Name == "Byte[]") { if (string.IsNullOrEmpty(name)) { name = "base64Binary"; } writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", "xs:base64Binary"); } else if (type == typeof(Stream) || typeof(Stream).IsAssignableFrom(type)) { name = "StreamBody"; writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", "xs:base64Binary"); } else if (typeof(IEnumerable).IsAssignableFrom(type)) { var elType = type; var collectionDataContractAttribute = type.GetCustomAttribute<CollectionDataContractAttribute>(); if (collectionDataContractAttribute == null) { elType = elType.IsArray ? type.GetElementType() : GetGenericType(type); } var sysType = ResolveSystemType(elType); if (sysType.name != null) { if (string.IsNullOrEmpty(name)) { name = typeName; } var ns = $"q{_namespaceCounter++}"; writer.WriteXmlnsAttribute($"{ns}", Namespaces.ARRAYS_NS); writer.WriteAttributeString("name", name); writer.WriteAttributeString("nillable", "true"); writer.WriteAttributeString("type", $"{ns}:ArrayOf{sysType.name}"); _arrayToBuild.Enqueue(type); } else { if (string.IsNullOrEmpty(name)) { name = typeName; } writer.WriteAttributeString("name", name); WriteComplexElementType(writer, typeName, _schemaNamespace, objectNamespace, type); _complexTypeToBuild[type] = GetDataContractNamespace(type); } } else { if (string.IsNullOrEmpty(name)) { name = typeName; } writer.WriteAttributeString("name", name); WriteComplexElementType(writer, typeName, _schemaNamespace, objectNamespace, type); _complexTypeToBuild[type] = GetDataContractNamespace(type); } } writer.WriteEndElement(); // xs:element } private bool TypeIsComplexForWsdl(Type type, out Type resultType) { var typeInfo = type.GetTypeInfo(); resultType = type; if (typeInfo.IsByRef) { type = typeInfo.GetElementType(); } if (typeof(IEnumerable).IsAssignableFrom(type)) { var collectionDataContractAttribute = type.GetCustomAttribute<CollectionDataContractAttribute>(); if (collectionDataContractAttribute != null) { return true; } resultType = type.IsArray ? type.GetElementType() : GetGenericType(type); type = resultType; } if (type == typeof(DateTimeOffset)) { return false; } if (typeInfo.IsEnum) { return false; } if (type.Name == "String" || type.Name == "String&") { return false; } if (type == typeof(System.Xml.Linq.XElement)) { return false; } if (type == typeof(DataTable)) { return false; } if (type.Name == "Byte[]") { return false; } if (SysTypeDic.ContainsKey(type.FullName)) { return false; } return true; } private void WriteComplexElementType(XmlDictionaryWriter writer, string typeName, string schemaNamespace, string objectNamespace, Type type) { var underlying = Nullable.GetUnderlyingType(type); if (!type.IsEnum || underlying != null) { writer.WriteAttributeString("nillable", "true"); } // In case of Nullable<T>, type is replaced by the underlying type if (underlying?.IsEnum == true) { type = underlying; typeName = GetTypeName(underlying); objectNamespace = GetModelNamespace(underlying); } if (schemaNamespace != objectNamespace) { var ns = $"q{_namespaceCounter++}"; writer.WriteXmlnsAttribute($"{ns}", GetDataContractNamespace(type)); writer.WriteAttributeString("type", $"{ns}:{typeName}"); } else { writer.WriteAttributeString("type", $"tns:{typeName}"); } } private string GetTypeName(Type type) { if (type.IsGenericType && !type.IsArray && !typeof(IEnumerable).IsAssignableFrom(type)) { var genericTypes = GetGenericTypes(type); var genericTypeNames = genericTypes.Select(a => GetTypeName(a)); var typeName = ReplaceGenericNames(type.Name); typeName = typeName + "Of" + string.Concat(genericTypeNames); return typeName; } if (type.IsArray) { return "ArrayOf" + GetTypeName(type.GetElementType()); } //Special case as string is IEnumerable and we don't want to turn it into System.Object if (typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string)) { var collectionDataContractAttribute = type.GetCustomAttribute<CollectionDataContractAttribute>(); if (collectionDataContractAttribute != null) { var typeName = collectionDataContractAttribute.IsNameSetExplicitly ? collectionDataContractAttribute.Name : ReplaceGenericNames(type.Name); if (type.IsGenericType) { var genericType = GetGenericType(type); var (name, _) = ResolveSystemType(genericType); var genericTypeName = string.IsNullOrEmpty(name) ? GetTypeName(genericType) : name; typeName = string.Format(typeName, genericTypeName); } return typeName; } else { return "ArrayOf" + GetTypeName(GetGenericType(type)); } } // Make use of DataContract attribute, if set, as it may contain a Name override var dataContractAttribute = type.GetCustomAttribute<DataContractAttribute>(); if (dataContractAttribute != null && dataContractAttribute.IsNameSetExplicitly) { return dataContractAttribute.Name; } return type.Name; } private string ReplaceGenericNames(string name) { if (name.Contains("`")) { //Regex would be easier foreach (var number in _numbers) { name = name.Replace("`" + number, "`" + string.Empty); } return name.Replace("`", string.Empty); } else { return name; } } private (string name, string ns) ResolveSystemType(Type type) { if (SysTypeDic.ContainsKey(type.FullName)) { return SysTypeDic[type.FullName]; } return (null, null); } private bool HasBaseType(Type type) { var isArrayType = type.IsArray || typeof(IEnumerable).IsAssignableFrom(type); var baseType = type.GetTypeInfo().BaseType; return !isArrayType && !type.IsEnum && !type.IsPrimitive && !type.IsValueType && baseType != null && !baseType.Name.Equals("Object"); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A collection of music tracks. /// </summary> public class MusicAlbum_Core : TypeCore, IMusicPlaylist { public MusicAlbum_Core() { this._TypeId = 174; this._Id = "MusicAlbum"; this._Schema_Org_Url = "http://schema.org/MusicAlbum"; string label = ""; GetLabel(out label, "MusicAlbum", typeof(MusicAlbum_Core)); this._Label = label; this._Ancestors = new int[]{266,78,177}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{177}; this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,145,223,39}; } /// <summary> /// The subject matter of the content. /// </summary> private About_Core about; public About_Core About { get { return about; } set { about = value; SetPropertyInstance(about); } } /// <summary> /// Specifies the Person that is legally accountable for the CreativeWork. /// </summary> private AccountablePerson_Core accountablePerson; public AccountablePerson_Core AccountablePerson { get { return accountablePerson; } set { accountablePerson = value; SetPropertyInstance(accountablePerson); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// A secondary title of the CreativeWork. /// </summary> private AlternativeHeadline_Core alternativeHeadline; public AlternativeHeadline_Core AlternativeHeadline { get { return alternativeHeadline; } set { alternativeHeadline = value; SetPropertyInstance(alternativeHeadline); } } /// <summary> /// The media objects that encode this creative work. This property is a synonym for encodings. /// </summary> private AssociatedMedia_Core associatedMedia; public AssociatedMedia_Core AssociatedMedia { get { return associatedMedia; } set { associatedMedia = value; SetPropertyInstance(associatedMedia); } } /// <summary> /// An embedded audio object. /// </summary> private Audio_Core audio; public Audio_Core Audio { get { return audio; } set { audio = value; SetPropertyInstance(audio); } } /// <summary> /// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely. /// </summary> private Author_Core author; public Author_Core Author { get { return author; } set { author = value; SetPropertyInstance(author); } } /// <summary> /// Awards won by this person or for this creative work. /// </summary> private Awards_Core awards; public Awards_Core Awards { get { return awards; } set { awards = value; SetPropertyInstance(awards); } } /// <summary> /// The artist that performed this album or recording. /// </summary> private ByArtist_Core byArtist; public ByArtist_Core ByArtist { get { return byArtist; } set { byArtist = value; SetPropertyInstance(byArtist); } } /// <summary> /// Comments, typically from users, on this CreativeWork. /// </summary> private Comment_Core comment; public Comment_Core Comment { get { return comment; } set { comment = value; SetPropertyInstance(comment); } } /// <summary> /// The location of the content. /// </summary> private ContentLocation_Core contentLocation; public ContentLocation_Core ContentLocation { get { return contentLocation; } set { contentLocation = value; SetPropertyInstance(contentLocation); } } /// <summary> /// Official rating of a piece of content\u2014for example,'MPAA PG-13'. /// </summary> private ContentRating_Core contentRating; public ContentRating_Core ContentRating { get { return contentRating; } set { contentRating = value; SetPropertyInstance(contentRating); } } /// <summary> /// A secondary contributor to the CreativeWork. /// </summary> private Contributor_Core contributor; public Contributor_Core Contributor { get { return contributor; } set { contributor = value; SetPropertyInstance(contributor); } } /// <summary> /// The party holding the legal copyright to the CreativeWork. /// </summary> private CopyrightHolder_Core copyrightHolder; public CopyrightHolder_Core CopyrightHolder { get { return copyrightHolder; } set { copyrightHolder = value; SetPropertyInstance(copyrightHolder); } } /// <summary> /// The year during which the claimed copyright for the CreativeWork was first asserted. /// </summary> private CopyrightYear_Core copyrightYear; public CopyrightYear_Core CopyrightYear { get { return copyrightYear; } set { copyrightYear = value; SetPropertyInstance(copyrightYear); } } /// <summary> /// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. /// </summary> private Creator_Core creator; public Creator_Core Creator { get { return creator; } set { creator = value; SetPropertyInstance(creator); } } /// <summary> /// The date on which the CreativeWork was created. /// </summary> private DateCreated_Core dateCreated; public DateCreated_Core DateCreated { get { return dateCreated; } set { dateCreated = value; SetPropertyInstance(dateCreated); } } /// <summary> /// The date on which the CreativeWork was most recently modified. /// </summary> private DateModified_Core dateModified; public DateModified_Core DateModified { get { return dateModified; } set { dateModified = value; SetPropertyInstance(dateModified); } } /// <summary> /// Date of first broadcast/publication. /// </summary> private DatePublished_Core datePublished; public DatePublished_Core DatePublished { get { return datePublished; } set { datePublished = value; SetPropertyInstance(datePublished); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// A link to the page containing the comments of the CreativeWork. /// </summary> private DiscussionURL_Core discussionURL; public DiscussionURL_Core DiscussionURL { get { return discussionURL; } set { discussionURL = value; SetPropertyInstance(discussionURL); } } /// <summary> /// Specifies the Person who edited the CreativeWork. /// </summary> private Editor_Core editor; public Editor_Core Editor { get { return editor; } set { editor = value; SetPropertyInstance(editor); } } /// <summary> /// The media objects that encode this creative work /// </summary> private Encodings_Core encodings; public Encodings_Core Encodings { get { return encodings; } set { encodings = value; SetPropertyInstance(encodings); } } /// <summary> /// Genre of the creative work /// </summary> private Genre_Core genre; public Genre_Core Genre { get { return genre; } set { genre = value; SetPropertyInstance(genre); } } /// <summary> /// Headline of the article /// </summary> private Headline_Core headline; public Headline_Core Headline { get { return headline; } set { headline = value; SetPropertyInstance(headline); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a> /// </summary> private InLanguage_Core inLanguage; public InLanguage_Core InLanguage { get { return inLanguage; } set { inLanguage = value; SetPropertyInstance(inLanguage); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// Indicates whether this content is family friendly. /// </summary> private IsFamilyFriendly_Core isFamilyFriendly; public IsFamilyFriendly_Core IsFamilyFriendly { get { return isFamilyFriendly; } set { isFamilyFriendly = value; SetPropertyInstance(isFamilyFriendly); } } /// <summary> /// The keywords/tags used to describe this content. /// </summary> private Keywords_Core keywords; public Keywords_Core Keywords { get { return keywords; } set { keywords = value; SetPropertyInstance(keywords); } } /// <summary> /// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. /// </summary> private Mentions_Core mentions; public Mentions_Core Mentions { get { return mentions; } set { mentions = value; SetPropertyInstance(mentions); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The number of tracks in this album or playlist. /// </summary> private NumTracks_Core numTracks; public NumTracks_Core NumTracks { get { return numTracks; } set { numTracks = value; SetPropertyInstance(numTracks); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// Specifies the Person or Organization that distributed the CreativeWork. /// </summary> private Provider_Core provider; public Provider_Core Provider { get { return provider; } set { provider = value; SetPropertyInstance(provider); } } /// <summary> /// The publisher of the creative work. /// </summary> private Publisher_Core publisher; public Publisher_Core Publisher { get { return publisher; } set { publisher = value; SetPropertyInstance(publisher); } } /// <summary> /// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. /// </summary> private PublishingPrinciples_Core publishingPrinciples; public PublishingPrinciples_Core PublishingPrinciples { get { return publishingPrinciples; } set { publishingPrinciples = value; SetPropertyInstance(publishingPrinciples); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The Organization on whose behalf the creator was working. /// </summary> private SourceOrganization_Core sourceOrganization; public SourceOrganization_Core SourceOrganization { get { return sourceOrganization; } set { sourceOrganization = value; SetPropertyInstance(sourceOrganization); } } /// <summary> /// A thumbnail image relevant to the Thing. /// </summary> private ThumbnailURL_Core thumbnailURL; public ThumbnailURL_Core ThumbnailURL { get { return thumbnailURL; } set { thumbnailURL = value; SetPropertyInstance(thumbnailURL); } } /// <summary> /// A music recording (track)\u2014usually a single song. /// </summary> private Tracks_Core tracks; public Tracks_Core Tracks { get { return tracks; } set { tracks = value; SetPropertyInstance(tracks); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } /// <summary> /// The version of the CreativeWork embodied by a specified resource. /// </summary> private Version_Core version; public Version_Core Version { get { return version; } set { version = value; SetPropertyInstance(version); } } /// <summary> /// An embedded video object. /// </summary> private Video_Core video; public Video_Core Video { get { return video; } set { video = value; SetPropertyInstance(video); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Methods for Parsing numbers and Strings. ** ** ===========================================================*/ using System; using System.Text; using System.Runtime.CompilerServices; namespace System { internal static class ParseNumbers { internal const int LeftAlign = 0x0001; internal const int RightAlign = 0x0004; internal const int PrefixSpace = 0x0008; internal const int PrintSign = 0x0010; internal const int PrintBase = 0x0020; internal const int PrintAsI1 = 0x0040; internal const int PrintAsI2 = 0x0080; internal const int PrintAsI4 = 0x0100; internal const int TreatAsUnsigned = 0x0200; internal const int TreatAsI1 = 0x0400; internal const int TreatAsI2 = 0x0800; internal const int IsTight = 0x1000; internal const int NoSpace = 0x2000; internal const int PrintRadixBase = 0x4000; private const int MinRadix = 2; private const int MaxRadix = 36; public static unsafe long StringToLong(System.String s, int radix, int flags) { int pos = 0; return StringToLong(s, radix, flags, ref pos); } public static long StringToLong(string s, int radix, int flags, ref int currPos) { long result = 0; int sign = 1; int length; int i; int grabNumbersStart = 0; int r; if (s != null) { i = currPos; // Do some radix checking. // A radix of -1 says to use whatever base is spec'd on the number. // Parse in Base10 until we figure out what the base actually is. r = (-1 == radix) ? 10 : radix; if (r != 2 && r != 10 && r != 8 && r != 16) throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix)); length = s.Length; if (i < 0 || i >= length) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index); // Get rid of the whitespace and then check that we've still got some digits to parse. if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0)) { EatWhiteSpace(s, ref i); if (i == length) throw new FormatException(SR.Format_EmptyInputString); } // Check for a sign if (s[i] == '-') { if (r != 10) throw new ArgumentException(SR.Arg_CannotHaveNegativeValue); if ((flags & TreatAsUnsigned) != 0) throw new OverflowException(SR.Overflow_NegativeUnsigned); sign = -1; i++; } else if (s[i] == '+') { i++; } if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0') { if (s[i + 1] == 'x' || s[i + 1] == 'X') { r = 16; i += 2; } } grabNumbersStart = i; result = GrabLongs(r, s, ref i, (flags & TreatAsUnsigned) != 0); // Check if they passed us a string with no parsable digits. if (i == grabNumbersStart) throw new FormatException(SR.Format_NoParsibleDigits); if ((flags & IsTight) != 0) { //If we've got effluvia left at the end of the string, complain. if (i < length) throw new FormatException(SR.Format_ExtraJunkAtEnd); } // Put the current index back into the correct place. currPos = i; // Return the value properly signed. if ((ulong)result == 0x8000000000000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0)) throw new OverflowException(SR.Overflow_Int64); if (r == 10) result *= sign; } else { result = 0; } return result; } public static int StringToInt(string s, int radix, int flags) { int pos = 0; return StringToInt(s, radix, flags, ref pos); } public static int StringToInt(string s, int radix, int flags, ref int currPos) { int result = 0; int sign = 1; int length; int i; int grabNumbersStart = 0; int r; if (s != null) { // They're requied to tell me where to start parsing. i = currPos; // Do some radix checking. // A radix of -1 says to use whatever base is spec'd on the number. // Parse in Base10 until we figure out what the base actually is. r = (-1 == radix) ? 10 : radix; if (r != 2 && r != 10 && r != 8 && r != 16) throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix)); length = s.Length; if (i < 0 || i >= length) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index); // Get rid of the whitespace and then check that we've still got some digits to parse. if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0)) { EatWhiteSpace(s, ref i); if (i == length) throw new FormatException(SR.Format_EmptyInputString); } // Check for a sign if (s[i] == '-') { if (r != 10) throw new ArgumentException(SR.Arg_CannotHaveNegativeValue); if ((flags & TreatAsUnsigned) != 0) throw new OverflowException(SR.Overflow_NegativeUnsigned); sign = -1; i++; } else if (s[i] == '+') { i++; } // Consume the 0x if we're in an unknown base or in base-16. if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0') { if (s[i + 1] == 'x' || s[i + 1] == 'X') { r = 16; i += 2; } } grabNumbersStart = i; result = GrabInts(r, s, ref i, ((flags & TreatAsUnsigned) != 0)); // Check if they passed us a string with no parsable digits. if (i == grabNumbersStart) throw new FormatException(SR.Format_NoParsibleDigits); if ((flags & IsTight) != 0) { // If we've got effluvia left at the end of the string, complain. if (i < length) throw new FormatException(SR.Format_ExtraJunkAtEnd); } // Put the current index back into the correct place. currPos = i; // Return the value properly signed. if ((flags & TreatAsI1) != 0) { if ((uint)result > 0xFF) throw new OverflowException(SR.Overflow_SByte); } else if ((flags & TreatAsI2) != 0) { if ((uint)result > 0xFFFF) throw new OverflowException(SR.Overflow_Int16); } else if ((uint)result == 0x80000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0)) { throw new OverflowException(SR.Overflow_Int32); } if (r == 10) result *= sign; } else { result = 0; } return result; } public static String IntToString(int n, int radix, int width, char paddingChar, int flags) { bool isNegative = false; int index = 0; int buffLength; int i; uint l; char[] buffer = new char[66]; // Longest possible string length for an integer in binary notation with prefix if (radix < MinRadix || radix > MaxRadix) throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix)); // If the number is negative, make it positive and remember the sign. // If the number is MIN_VALUE, this will still be negative, so we'll have to // special case this later. if (n < 0) { isNegative = true; // For base 10, write out -num, but other bases write out the // 2's complement bit pattern if (10 == radix) l = (uint)-n; else l = (uint)n; } else { l = (uint)n; } // The conversion to a uint will sign extend the number. In order to ensure // that we only get as many bits as we expect, we chop the number. if ((flags & PrintAsI1) != 0) l &= 0xFF; else if ((flags & PrintAsI2) != 0) l &= 0xFFFF; // Special case the 0. if (0 == l) { buffer[0] = '0'; index = 1; } else { do { uint charVal = l % (uint)radix; l /= (uint)radix; if (charVal < 10) buffer[index++] = (char)(charVal + '0'); else buffer[index++] = (char)(charVal + 'a' - 10); } while (l != 0); } // If they want the base, append that to the string (in reverse order) if (radix != 10 && ((flags & PrintBase) != 0)) { if (16 == radix) { buffer[index++] = 'x'; buffer[index++] = '0'; } else if (8 == radix) { buffer[index++] = '0'; } } if (10 == radix) { // If it was negative, append the sign, else if they requested, add the '+'. // If they requested a leading space, put it on. if (isNegative) buffer[index++] = '-'; else if ((flags & PrintSign) != 0) buffer[index++] = '+'; else if ((flags & PrefixSpace) != 0) buffer[index++] = ' '; } // Figure out the size of our string. if (width <= index) buffLength = index; else buffLength = width; StringBuilder sb = new StringBuilder(buffLength); // Put the characters into the String in reverse order // Fill the remaining space -- if there is any -- // with the correct padding character. if ((flags & LeftAlign) != 0) { for (i = 0; i < index; i++) sb.Append(buffer[index - i - 1]); if (buffLength > index) sb.Append(paddingChar, buffLength - index); } else { if (buffLength > index) sb.Append(paddingChar, buffLength - index); for (i = 0; i < index; i++) sb.Append(buffer[index - i - 1]); } return sb.ToString(); } public static String LongToString(long n, int radix, int width, char paddingChar, int flags) { bool isNegative = false; int index = 0; int charVal; ulong ul; int i; int buffLength = 0; char[] buffer = new char[67];//Longest possible string length for an integer in binary notation with prefix if (radix < MinRadix || radix > MaxRadix) throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix)); //If the number is negative, make it positive and remember the sign. if (n < 0) { isNegative = true; // For base 10, write out -num, but other bases write out the // 2's complement bit pattern if (10 == radix) ul = (ulong)(-n); else ul = (ulong)n; } else { ul = (ulong)n; } if ((flags & PrintAsI1) != 0) ul = ul & 0xFF; else if ((flags & PrintAsI2) != 0) ul = ul & 0xFFFF; else if ((flags & PrintAsI4) != 0) ul = ul & 0xFFFFFFFF; //Special case the 0. if (0 == ul) { buffer[0] = '0'; index = 1; } else { //Pull apart the number and put the digits (in reverse order) into the buffer. for (index = 0; ul > 0; ul = ul / (ulong)radix, index++) { if ((charVal = (int)(ul % (ulong)radix)) < 10) buffer[index] = (char)(charVal + '0'); else buffer[index] = (char)(charVal + 'a' - 10); } } //If they want the base, append that to the string (in reverse order) if (radix != 10 && ((flags & PrintBase) != 0)) { if (16 == radix) { buffer[index++] = 'x'; buffer[index++] = '0'; } else if (8 == radix) { buffer[index++] = '0'; } else if ((flags & PrintRadixBase) != 0) { buffer[index++] = '#'; buffer[index++] = (char)((radix % 10) + '0'); buffer[index++] = (char)((radix / 10) + '0'); } } if (10 == radix) { //If it was negative, append the sign. if (isNegative) { buffer[index++] = '-'; } //else if they requested, add the '+'; else if ((flags & PrintSign) != 0) { buffer[index++] = '+'; } //If they requested a leading space, put it on. else if ((flags & PrefixSpace) != 0) { buffer[index++] = ' '; } } //Figure out the size of our string. if (width <= index) buffLength = index; else buffLength = width; StringBuilder sb = new StringBuilder(buffLength); //Put the characters into the String in reverse order //Fill the remaining space -- if there is any -- //with the correct padding character. if ((flags & LeftAlign) != 0) { for (i = 0; i < index; i++) sb.Append(buffer[index - i - 1]); if (buffLength > index) sb.Append(paddingChar, buffLength - index); } else { if (buffLength > index) sb.Append(paddingChar, buffLength - index); for (i = 0; i < index; i++) sb.Append(buffer[index - i - 1]); } return sb.ToString(); } private static void EatWhiteSpace(string s, ref int i) { for (; i < s.Length && char.IsWhiteSpace(s[i]); i++) ; } private static long GrabLongs(int radix, string s, ref int i, bool isUnsigned) { ulong result = 0; int value; ulong maxVal; // Allow all non-decimal numbers to set the sign bit. if (radix == 10 && !isUnsigned) { maxVal = 0x7FFFFFFFFFFFFFFF / 10; // Read all of the digits and convert to a number while (i < s.Length && (IsDigit(s[i], radix, out value))) { // Check for overflows - this is sufficient & correct. if (result > maxVal || ((long)result) < 0) throw new OverflowException(SR.Overflow_Int64); result = result * (ulong)radix + (ulong)value; i++; } if ((long)result < 0 && result != 0x8000000000000000) throw new OverflowException(SR.Overflow_Int64); } else { maxVal = 0xffffffffffffffff / (ulong)radix; // Read all of the digits and convert to a number while (i < s.Length && (IsDigit(s[i], radix, out value))) { // Check for overflows - this is sufficient & correct. if (result > maxVal) throw new OverflowException(SR.Overflow_UInt64); ulong temp = result * (ulong)radix + (ulong)value; if (temp < result) // this means overflow as well throw new OverflowException(SR.Overflow_UInt64); result = temp; i++; } } return (long)result; } private static int GrabInts(int radix, string s, ref int i, bool isUnsigned) { uint result = 0; int value; uint maxVal; // Allow all non-decimal numbers to set the sign bit. if (radix == 10 && !isUnsigned) { maxVal = (0x7FFFFFFF / 10); // Read all of the digits and convert to a number while (i < s.Length && (IsDigit(s[i], radix, out value))) { // Check for overflows - this is sufficient & correct. if (result > maxVal || (int)result < 0) throw new OverflowException(SR.Overflow_Int32); result = result * (uint)radix + (uint)value; i++; } if ((int)result < 0 && result != 0x80000000) throw new OverflowException(SR.Overflow_Int32); } else { maxVal = 0xffffffff / (uint)radix; // Read all of the digits and convert to a number while (i < s.Length && (IsDigit(s[i], radix, out value))) { // Check for overflows - this is sufficient & correct. if (result > maxVal) throw new OverflowException(SR.Overflow_UInt32); // the above check won't cover 4294967296 to 4294967299 uint temp = result * (uint)radix + (uint)value; if (temp < result) // this means overflow as well throw new OverflowException(SR.Overflow_UInt32); result = temp; i++; } } return (int)result; } private static bool IsDigit(char c, int radix, out int result) { if (c >= '0' && c <= '9') result = c - '0'; else if (c >= 'A' && c <= 'Z') result = c - 'A' + 10; else if (c >= 'a' && c <= 'z') result = c - 'a' + 10; else result = -1; if ((result >= 0) && (result < radix)) return true; return false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.IO; using System.Reflection; using System.Xml; namespace BLToolkit.DataAccess { using Aspects; using Common; using Data; using Data.DataProvider; using Mapping; using Patterns; using Properties; using Reflection; using TypeBuilder; //[DataAccessor, DebuggerStepThrough] [DataAccessor] public abstract class DataAccessor : DataAccessorBase { #region Constructors protected DataAccessor() { } protected DataAccessor(DbManager dbManager) : base(dbManager) { } protected DataAccessor(DbManager dbManager, bool dispose) : base(dbManager, dispose) { } #endregion #region CreateInstance public static DataAccessor CreateInstance(Type type) { return (DataAccessor)Activator.CreateInstance(TypeFactory.GetType(type)); } public static DataAccessor CreateInstance(Type type, InitContext context) { return (DataAccessor)Activator.CreateInstance(TypeFactory.GetType(type), context); } public static DataAccessor CreateInstance(Type type, DbManager dbManager) { return CreateInstance(type, dbManager, false); } public static DataAccessor CreateInstance( Type type, InitContext context, DbManager dbManager) { return CreateInstance(type, context, dbManager, false); } public static DataAccessor CreateInstance(Type type, DbManager dbManager, bool dispose) { DataAccessor da = CreateInstance(type); da.SetDbManager(dbManager, dispose); return da; } public static DataAccessor CreateInstance( Type type, InitContext context, DbManager dbManager, bool dispose) { DataAccessor da = CreateInstance(type, context); da.SetDbManager(dbManager, dispose); return da; } public static T CreateInstance<T>() where T : DataAccessor { return TypeFactory.CreateInstance<T>(); } public static T CreateInstance<T>(DbManager dbManager) where T : DataAccessor { return CreateInstance<T>(dbManager, false); } public static T CreateInstance<T>(DbManager dbManager, bool dispose) where T : DataAccessor { T da = TypeFactory.CreateInstance<T>(); da.SetDbManager(dbManager, dispose); return da; } #endregion #region Protected Members #region Parameters [NoInterception] protected virtual string GetQueryParameterName(DbManager db, string paramName) { return (string)db.DataProvider.Convert(paramName, ConvertType.NameToQueryParameter); } [NoInterception] protected virtual string GetSpParameterName(DbManager db, string paramName) { return (string)db.DataProvider.Convert(paramName, db.GetConvertTypeToParameter()); } [NoInterception] protected virtual IDbDataParameter[] PrepareParameters(DbManager db, object[] parameters) { return db.PrepareParameters(parameters); } [NoInterception] protected virtual IDbDataParameter GetParameter(DbManager db, string paramName) { IDbDataParameter p = db.Parameter(paramName); if (p == null) { // This usually means that the parameter name is incorrect. // throw new DataAccessException(string.Format( Resources.DataAccessot_ParameterNotFound, paramName)); } // Input parameter mapping make no sence. // Debug.WriteLineIf(p.Direction == ParameterDirection.Input, string.Format("'{0}.{1}' is an input parameter.", db.Command.CommandText, paramName)); return p; } [NoInterception] protected virtual IDbDataParameter[] CreateParameters( DbManager db, object obj, string[] outputParameters, string[] inputOutputParameters, string[] ignoreParameters, params IDbDataParameter[] commandParameters) { return db.CreateParameters(obj, outputParameters, inputOutputParameters, ignoreParameters, commandParameters); } [NoInterception] protected virtual IDbDataParameter[] CreateParameters( DbManager db, DataRow dataRow, string[] outputParameters, string[] inputOutputParameters, string[] ignoreParameters, params IDbDataParameter[] commandParameters) { return db.CreateParameters(dataRow, outputParameters, inputOutputParameters, ignoreParameters, commandParameters); } [NoInterception] protected virtual string PrepareSqlQuery(DbManager db, int queryID, int uniqueID, string sqlQuery) { return sqlQuery; } #endregion #region ExecuteDictionary protected void ExecuteDictionary( DbManager db, IDictionary dictionary, Type objectType, Type keyType, string methodName) { bool isIndex = TypeHelper.IsSameOrParent(typeof(CompoundValue), keyType); MemberMapper[] mms = new SqlQuery(Extensions).GetKeyFieldList(db, objectType); if (mms.Length == 0) throw new DataAccessException(string.Format( Resources.DataAccessor_UnknownIndex, GetType().Name, methodName)); if (mms.Length > 1 && keyType != typeof(object) && !isIndex) throw new DataAccessException(string.Format( Resources.DataAccessor_InvalidKeyType, GetType().Name, methodName)); if (isIndex || mms.Length > 1) { string[] fields = new string[mms.Length]; for (int i = 0; i < mms.Length; i++) fields[i] = mms[i].MemberName; db.ExecuteDictionary(dictionary, new MapIndex(fields), objectType, null); } else { db.ExecuteDictionary(dictionary, mms[0].MemberName, objectType, null); } } protected void ExecuteDictionary<TValue>( DbManager db, IDictionary<CompoundValue, TValue> dictionary, Type objectType, string methodName) { MemberMapper[] mms = new SqlQuery(Extensions).GetKeyFieldList(db, objectType); if (mms.Length == 0) throw new DataAccessException(string.Format( Resources.DataAccessor_UnknownIndex, GetType().Name, methodName)); string[] fields = new string[mms.Length]; for (int i = 0; i < mms.Length; i++) fields[i] = mms[i].MemberName; db.ExecuteDictionary<TValue>(dictionary, new MapIndex(fields), objectType, null); } protected void ExecuteDictionary<TKey, TValue>( DbManager db, IDictionary<TKey, TValue> dictionary, Type objectType, string methodName) { MemberMapper[] mms = new SqlQuery(Extensions).GetKeyFieldList(db, objectType); if (mms.Length == 0) throw new DataAccessException(string.Format( Resources.DataAccessor_UnknownIndex, GetType().Name, methodName)); if (mms.Length != 1) throw new DataAccessException(string.Format( Resources.DataAccessor_IndexIsComplex, GetType().Name, methodName)); db.ExecuteDictionary<TKey, TValue>(dictionary, mms[0].MemberName, objectType, null); } protected void ExecuteScalarDictionary( DbManager db, IDictionary dictionary, Type objectType, Type keyType, string methodName, NameOrIndexParameter scalarField, Type elementType) { bool isIndex = TypeHelper.IsSameOrParent(typeof(CompoundValue), keyType); MemberMapper[] mms = new SqlQuery(Extensions).GetKeyFieldList(db, objectType); if (mms.Length == 0) throw new DataAccessException(string.Format( Resources.DataAccessor_UnknownIndex, GetType().Name, methodName)); if (mms.Length > 1 && keyType != typeof(object) && !isIndex) throw new DataAccessException(string.Format( Resources.DataAccessor_InvalidKeyType, GetType().Name, methodName)); if (isIndex || mms.Length > 1) { string[] fields = new string[mms.Length]; for (int i = 0; i < mms.Length; i++) fields[i] = mms[i].Name; db.ExecuteScalarDictionary(dictionary, new MapIndex(fields), scalarField, elementType); } else { db.ExecuteScalarDictionary( dictionary, mms[0].Name, keyType, scalarField, elementType); } } #endregion #region ExecuteEnumerable protected IEnumerable<T> ExecuteEnumerable<T>(DbManager db, Type objectType, bool disposeDbManager) { try { using (IDataReader rd = db.ExecuteReader()) { if (rd.Read()) { ObjectMapper dest = MappingSchema.GetObjectMapper(objectType); DataReaderMapper source = MappingSchema.CreateDataReaderMapper(rd); InitContext ctx = new InitContext(); ctx.MappingSchema = MappingSchema; ctx.ObjectMapper = dest; ctx.DataSource = source; ctx.SourceObject = rd; int[] index = MappingSchema.GetIndex(source, dest); IValueMapper[] mappers = ctx.MappingSchema.GetValueMappers(source, dest, index); do { T destObject = (T)dest.CreateInstance(ctx); if (ctx.StopMapping) yield return destObject; ISupportMapping smDest = destObject as ISupportMapping; if (smDest != null) { smDest.BeginMapping(ctx); if (ctx.StopMapping) yield return destObject; } MappingSchema.MapInternal(source, rd, dest, destObject, index, mappers); if (smDest != null) smDest.EndMapping(ctx); yield return destObject; } while (rd.Read()); } } } finally { if (disposeDbManager) db.Dispose(); } } protected IEnumerable ExecuteEnumerable(DbManager db, Type objectType, bool disposeDbManager) { MappingSchema ms = db.MappingSchema; if (disposeDbManager) { using (db) using (IDataReader rd = db.ExecuteReader()) while (rd.Read()) yield return ms.MapDataReaderToObject(rd, objectType); } else { using (IDataReader rd = db.ExecuteReader()) while (rd.Read()) yield return ms.MapDataReaderToObject(rd, objectType); } } #endregion #region Convert #region Primitive Types [CLSCompliant(false)] [NoInterception] protected virtual SByte ConvertToSByte(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSByte(value); } [NoInterception] protected virtual Int16 ConvertToInt16(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToInt16(value); } [NoInterception] protected virtual Int32 ConvertToInt32(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToInt32(value); } [NoInterception] protected virtual Int64 ConvertToInt64(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToInt64(value); } [NoInterception] protected virtual Byte ConvertToByte(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToByte(value); } [CLSCompliant(false)] [NoInterception] protected virtual UInt16 ConvertToUInt16(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToUInt16(value); } [CLSCompliant(false)] [NoInterception] protected virtual UInt32 ConvertToUInt32(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToUInt32(value); } [CLSCompliant(false)] [NoInterception] protected virtual UInt64 ConvertToUInt64(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToUInt64(value); } [NoInterception] protected virtual Char ConvertToChar(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToChar(value); } [NoInterception] protected virtual Single ConvertToSingle(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSingle(value); } [NoInterception] protected virtual Double ConvertToDouble(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToDouble(value); } [NoInterception] protected virtual Boolean ConvertToBoolean(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToBoolean(value); } #endregion #region Simple Types [NoInterception] protected virtual String ConvertToString(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToString(value); } [NoInterception] protected virtual DateTime ConvertToDateTime(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToDateTime(value); } #if FW3 [NoInterception] protected virtual DateTimeOffset ConvertToDateTimeOffset(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToDateTimeOffset(value); } [NoInterception] protected virtual System.Data.Linq.Binary ConvertToLinqBinary(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToLinqBinary(value); } #endif [NoInterception] protected virtual Decimal ConvertToDecimal(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToDecimal(value); } [NoInterception] protected virtual Guid ConvertToGuid(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToGuid(value); } [NoInterception] protected virtual Stream ConvertToStream(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToStream(value); } [NoInterception] protected virtual XmlReader ConvertToXmlReader(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToXmlReader(value); } [NoInterception] protected virtual XmlDocument ConvertToXmlDocument(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToXmlDocument(value); } [NoInterception] protected virtual Byte[] ConvertToByteArray(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToByteArray(value); } [NoInterception] protected virtual Char[] ConvertToCharArray(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToCharArray(value); } #endregion #region SqlTypes [NoInterception] protected virtual SqlByte ConvertToSqlByte(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlByte(value); } [NoInterception] protected virtual SqlInt16 ConvertToSqlInt16(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlInt16(value); } [NoInterception] protected virtual SqlInt32 ConvertToSqlInt32(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlInt32(value); } [NoInterception] protected virtual SqlInt64 ConvertToSqlInt64(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlInt64(value); } [NoInterception] protected virtual SqlSingle ConvertToSqlSingle(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlSingle(value); } [NoInterception] protected virtual SqlBoolean ConvertToSqlBoolean(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlBoolean(value); } [NoInterception] protected virtual SqlDouble ConvertToSqlDouble(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlDouble(value); } [NoInterception] protected virtual SqlDateTime ConvertToSqlDateTime(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlDateTime(value); } [NoInterception] protected virtual SqlDecimal ConvertToSqlDecimal(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlDecimal(value); } [NoInterception] protected virtual SqlMoney ConvertToSqlMoney(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlMoney(value); } [NoInterception] protected virtual SqlGuid ConvertToSqlGuid(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlGuid(value); } [NoInterception] protected virtual SqlString ConvertToSqlString(DbManager db, object value, object parameter) { return db.MappingSchema.ConvertToSqlString(value); } #endregion #region General case [NoInterception] protected virtual object ConvertChangeType( DbManager db, object value, Type conversionType, object parameter) { return db.MappingSchema.ConvertChangeType(value, conversionType); } #endregion #endregion #region IsNull /// <summary> /// Reserved for internal BLToolkit use. /// </summary> public interface INullableInternal { bool IsNull { [MustImplement(false, false)] get; } } [NoInterception] protected virtual bool IsNull( DbManager db, object value, object parameter) { // Speed up for scalar and nullable types. // switch (System.Convert.GetTypeCode(value)) { // null, DBNull.Value, Nullable<T> without a value. // case TypeCode.Empty: case TypeCode.DBNull: return true; case TypeCode.Object: break; // int, byte, string, DateTime and other primitives except Guid. // Also Nullable<T> with a value. // default: return false; } // Speed up for SqlTypes. // INullable nullable = value as INullable; if (nullable != null) return nullable.IsNull; // All other types which have 'IsNull' property but does not implement 'INullable' interface. // For example: 'Oracle.DataAccess.Types.OracleDecimal'. // // For types without 'IsNull' property the return value is always false. // INullableInternal nullableInternal = (INullableInternal)DuckTyping.Implement(typeof(INullableInternal), value); return nullableInternal.IsNull; } #endregion protected SqlQueryAttribute GetSqlQueryAttribute(MethodInfo methodInfo) { object[] attrs = methodInfo.GetCustomAttributes(typeof(SqlQueryAttribute), true); return (SqlQueryAttribute)attrs[0]; } #endregion } }
using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using Xbehave.Sdk; using Xbehave.Test.Infrastructure; using Xunit; using Xunit.Abstractions; namespace Xbehave.Test { // In order to prevent bugs due to incorrect code // As a developer // I want to run automated acceptance tests describing each feature of my product using scenarios public class ScenarioFeature : Feature { // NOTE (adamralph): a plain xunit fact to prove that plain scenarios work in 2.x [Fact] public void ScenarioWithTwoPassingStepsAndOneFailingStepYieldsTwoPassesAndOneFail() { // arrange var feature = typeof(FeatureWithAScenarioWithTwoPassingStepsAndOneFailingStep); // act var results = this.Run<ITestResultMessage>(feature); // assert Assert.Equal(3, results.Length); Assert.All(results.Take(2), result => Assert.IsAssignableFrom<ITestPassed>(result)); Assert.All(results.Skip(2), result => Assert.IsAssignableFrom<ITestFailed>(result)); } [Scenario] public void ScenarioWithThreeSteps(Type feature, IMessageSinkMessage[] messages, ITestResultMessage[] results) { "Given a feature with a scenario with three steps" .x(() => feature = typeof(FeatureWithAScenarioWithThreeSteps)); "When I run the scenarios" .x(() => results = (messages = this.Run<IMessageSinkMessage>(feature)) .OfType<ITestResultMessage>().ToArray()); "Then there should be three results" .x(() => Assert.Equal(3, results.Length)); "And the first result should have a display name ending with 'Step 1'" .x(() => Assert.EndsWith("Step 1", results[0].Test.DisplayName)); "And the second result should have a display name ending with 'Step 2'" .x(() => Assert.EndsWith("Step 2", results[1].Test.DisplayName)); "And the third result should have a display name ending with 'Step 3'" .x(() => Assert.EndsWith("Step 3", results[2].Test.DisplayName)); "And the messages should satisfy the xunit message contract" .x(() => Assert.Equal( new[] { "TestCollectionStarting", "TestClassStarting", "TestMethodStarting", "TestCaseStarting", "TestStarting", "TestPassed", "TestFinished", "TestStarting", "TestPassed", "TestFinished", "TestStarting", "TestPassed", "TestFinished", "TestCaseFinished", "TestMethodFinished", "TestClassFinished", "TestCollectionFinished", }, messages.Select(message => message.GetType().Name).SkipWhile(name => name == "TestAssemblyStarting").Take(17).ToArray())); } [Scenario] public void OrderingStepsByDisplayName(Type feature, ITestResultMessage[] results) { "Given ten steps named alphabetically backwards starting with 'z'" .x(() => feature = typeof(TenStepsNamedAlphabeticallyBackwardsStartingWithZ)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "And I sort the results by their display name" .x(() => results = results.OrderBy(result => result.Test.DisplayName).ToArray()); "Then a concatenation of the last character of each result display names should be 'zyxwvutsrq'" .x(() => Assert.Equal("zyxwvutsrq", new string(results.Select(result => result.Test.DisplayName.Last()).ToArray()))); } [Scenario] public void ScenarioWithTwoPassingStepsAndOneFailingStep(Type feature, ITestResultMessage[] results) { "Given a feature with a scenario with two passing steps and one failing step" .x(() => feature = typeof(FeatureWithAScenarioWithTwoPassingStepsAndOneFailingStep)); "When I run the scenarios" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be three results" .x(() => Assert.Equal(3, results.Length)); "And the first two results should be passes" .x(() => Assert.All(results.Take(2), result => Assert.IsAssignableFrom<ITestPassed>(result))); "And the third result should be a fail" .x(() => Assert.All(results.Skip(2), result => Assert.IsAssignableFrom<ITestFailed>(result))); } [Scenario] public void ScenarioBodyThrowsAnException(Type feature, Exception exception, ITestResultMessage[] results) { "Given a feature with a scenario body which throws an exception" .x(() => feature = typeof(FeatureWithAScenarioBodyWhichThrowsAnException)); "When I run the scenarios" .x(() => exception = Record.Exception(() => results = this.Run<ITestResultMessage>(feature))); "Then no exception should be thrown" .x(() => Assert.Null(exception)); "And the results should not be empty" .x(() => Assert.NotEmpty(results)); "And each result should be a failure" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestFailed>(result))); } [Scenario] public void FeatureCannotBeConstructed(Type feature, Exception exception, ITestResultMessage[] results) { "Given a feature with a non-static scenario but no default constructor" .x(() => feature = typeof(FeatureWithANonStaticScenarioButNoDefaultConstructor)); "When I run the scenarios" .x(() => exception = Record.Exception(() => results = this.Run<ITestResultMessage>(feature))); "Then no exception should be thrown" .x(() => Assert.Null(exception)); "And the results should not be empty" .x(() => Assert.NotEmpty(results)); "And each result should be a failure" .x(() => Assert.All(results, result => Assert.IsAssignableFrom<ITestFailed>(result))); } [Scenario] public void FeatureConstructionFails(Type feature, ITestFailed[] failures) { "Given a feature with a failing constructor" .x(() => feature = typeof(FeatureWithAFailingConstructor)); "When I run the scenarios" .x(() => failures = this.Run<ITestFailed>(feature)); "Then there should be one test failure" .x(() => Assert.Single(failures)); } [Scenario] public void FailingStepThenPassingSteps(Type feature, ITestResultMessage[] results) { "Given a failing step and two passing steps named alphabetically backwards" .x(() => feature = typeof(AFailingStepAndTwoPassingStepsNamedAlphabeticallyBackwards)); "When I run the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "And I sort the results by their display name" .x(() => results = results.OrderBy(result => result.Test.DisplayName).ToArray()); "Then the there should be three results" .x(() => Assert.Equal(3, results.Length)); "Then the first result should be a failure" .x(() => Assert.IsAssignableFrom<ITestFailed>(results[0])); "And the second and third results should be skips" .x(() => Assert.All(results.Skip(1), result => Assert.IsAssignableFrom<ITestSkipped>(result))); "And the second result should refer to the second step" .x(() => Assert.Contains("Step y", results[1].Test.DisplayName)); "And the third result should refer to the third step" .x(() => Assert.Contains("Step x", results[2].Test.DisplayName)); "And the second and third result messages should indicate that the first step failed" .x(() => Assert.All( results.Skip(1).Cast<ITestSkipped>(), result => { Assert.Contains("Failed to execute preceding step", result.Reason); Assert.Contains("Step z", result.Reason); })); } [Scenario] public void ScenarioWithNoSteps(Type feature, ITestResultMessage[] results) { "Given a scenario with no steps" .x(() => feature = typeof(FeatureWithAScenarioWithNoSteps)); "When I run the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one result" .x(() => Assert.Single(results)); "And the result should be a pass" .x(() => Assert.IsAssignableFrom<ITestPassed>(results.Single())); } [Scenario] public void NullStepText() => ((string)null) .x(() => { }); [Scenario] public void NullStepBody() => "Given a null body" .x((Action)null); [Scenario] public void NullContextualStepBody() => "Given a null body" .x((Action<IStepContext>)null); [Scenario] public void NestedStep(Type feature, ITestResultMessage[] results) { "Given a scenario with a nested step" .x(() => feature = typeof(ScenarioWithANestedStep)); "When I run the scenario" .x(() => results = this.Run<ITestResultMessage>(feature)); "Then there should be one result" .x(() => Assert.Single(results)); "And the result should be a fail" .x(() => Assert.IsAssignableFrom<ITestFailed>(results.Single())); } private class FeatureWithAScenarioWithThreeSteps { [Scenario] public void Scenario() { "Step 1" .x(() => { }); "Step 2" .x(() => { }); "Step 3" .x(() => { }); } } private class TenStepsNamedAlphabeticallyBackwardsStartingWithZ { [Scenario] public static void Scenario() { "z" .x(() => { }); "y" .x(() => { }); "x" .x(() => { }); "w" .x(() => { }); "v" .x(() => { }); "u" .x(() => { }); "t" .x(() => { }); "s" .x(() => { }); "r" .x(() => { }); "q" .x(() => { }); } } private class FeatureWithAScenarioWithTwoPassingStepsAndOneFailingStep { [Scenario] public static void Scenario() { var i = 0; "Given 1" .x(() => i = 1); "When I add 1" .x(() => i += 1); "Then I have 3" .x(() => Assert.Equal(3, i)); } } private class FeatureWithAScenarioBodyWhichThrowsAnException { [Scenario] public static void Scenario() => throw new InvalidOperationException(); } private class AFailingStepAndTwoPassingStepsNamedAlphabeticallyBackwards { [Scenario] public static void Scenario() { "Step z" .x(() => throw new NotImplementedException()); "Step y" .x(() => { }); "Step x" .x(() => { }); } } private class FeatureWithANonStaticScenarioButNoDefaultConstructor { #pragma warning disable IDE0060 // Remove unused parameter public FeatureWithANonStaticScenarioButNoDefaultConstructor(int _) #pragma warning restore IDE0060 // Remove unused parameter { } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for testing.")] [Scenario] public void Scenario() => "Given something" .x(() => { }); } private class FeatureWithAFailingConstructor { public FeatureWithAFailingConstructor() => throw new InvalidOperationException(); [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for testing.")] [Scenario] public void Scenario() => "Given something" .x(() => { }); } private class FeatureWithAScenarioWithNoSteps { [Scenario] public void Scenario() { } } private class ScenarioWithANestedStep { [Scenario] public void Scenario() => "Given something" .x(() => "With something nested".x(() => { })); } } }
using System; using System.Collections.Generic; using System.Linq; namespace CppSharp.AST { /// <summary> /// Represents a declaration context. /// </summary> public abstract class DeclarationContext : Declaration { public bool IsAnonymous { get; set; } public List<Declaration> Declarations; public List<TypeReference> TypeReferences; public DeclIterator<Namespace> Namespaces { get { return new DeclIterator<Namespace>(Declarations); } } public DeclIterator<Enumeration> Enums { get { return new DeclIterator<Enumeration>(Declarations); } } public DeclIterator<Function> Functions { get { return new DeclIterator<Function>(Declarations); } } public DeclIterator<Class> Classes { get { return new DeclIterator<Class>(Declarations); } } public DeclIterator<Template> Templates { get { return new DeclIterator<Template>(Declarations); } } public DeclIterator<TypedefNameDecl> Typedefs { get { return new DeclIterator<TypedefNameDecl>(Declarations); } } public DeclIterator<Variable> Variables { get { return new DeclIterator<Variable>(Declarations); } } public DeclIterator<Event> Events { get { return new DeclIterator<Event>(Declarations); } } // Used to keep track of anonymous declarations. public Dictionary<ulong, Declaration> Anonymous; // True if the context is inside an extern "C" context. public bool IsExternCContext; public override string LogicalName { get { return IsAnonymous ? "<anonymous>" : base.Name; } } public override string LogicalOriginalName { get { return IsAnonymous ? "<anonymous>" : base.OriginalName; } } protected DeclarationContext() { Declarations = new List<Declaration>(); TypeReferences = new List<TypeReference>(); Anonymous = new Dictionary<ulong, Declaration>(); } protected DeclarationContext(DeclarationContext dc) : base(dc) { Declarations = dc.Declarations; TypeReferences = new List<TypeReference>(dc.TypeReferences); Anonymous = new Dictionary<ulong, Declaration>(dc.Anonymous); IsAnonymous = dc.IsAnonymous; } public IEnumerable<DeclarationContext> GatherParentNamespaces() { var children = new Stack<DeclarationContext>(); var currentNamespace = this; while (currentNamespace != null) { if (!(currentNamespace is TranslationUnit)) children.Push(currentNamespace); currentNamespace = currentNamespace.Namespace; } return children; } public Declaration FindAnonymous(ulong key) { return Anonymous.ContainsKey(key) ? Anonymous[key] : null; } public DeclarationContext FindDeclaration(IEnumerable<string> declarations) { DeclarationContext currentDeclaration = this; foreach (var declaration in declarations) { var subDeclaration = currentDeclaration.Namespaces .Concat<DeclarationContext>(currentDeclaration.Classes) .FirstOrDefault(e => e.Name.Equals(declaration)); if (subDeclaration == null) return null; currentDeclaration = subDeclaration; } return currentDeclaration as DeclarationContext; } public Namespace FindNamespace(string name) { var namespaces = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries); return FindNamespace(namespaces); } public Namespace FindNamespace(IEnumerable<string> namespaces) { DeclarationContext currentNamespace = this; foreach (var @namespace in namespaces) { var childNamespace = currentNamespace.Namespaces.Find( e => e.Name.Equals(@namespace)); if (childNamespace == null) return null; currentNamespace = childNamespace; } return currentNamespace as Namespace; } public Namespace FindCreateNamespace(string name) { var @namespace = FindNamespace(name); if (@namespace == null) { @namespace = new Namespace { Name = name, Namespace = this, }; Namespaces.Add(@namespace); } return @namespace; } public Enumeration FindEnum(string name, bool createDecl = false) { var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var @enum = Enums.Find(e => e.Name.Equals(name)); if (@enum == null && createDecl) { @enum = new Enumeration() { Name = name, Namespace = this }; Enums.Add(@enum); } return @enum; } var enumName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindEnum(enumName, createDecl); } public Enumeration FindEnum(IntPtr ptr) { return Enums.FirstOrDefault(f => f.OriginalPtr == ptr); } public Function FindFunction(string name, bool createDecl = false) { if (string.IsNullOrEmpty(name)) return null; var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var function = Functions.Find(e => e.Name.Equals(name)); if (function == null && createDecl) { function = new Function() { Name = name, Namespace = this }; Functions.Add(function); } return function; } var funcName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindFunction(funcName, createDecl); } public Function FindFunctionByUSR(string usr) { return Functions .Concat(Templates.OfType<FunctionTemplate>() .Select(t => t.TemplatedFunction)) .FirstOrDefault(f => f.USR == usr); } Class CreateClass(string name, bool isComplete) { var @class = new Class { Name = name, Namespace = this, IsIncomplete = !isComplete }; return @class; } public Class FindClass(string name, StringComparison stringComparison = StringComparison.Ordinal) { if (string.IsNullOrEmpty(name)) return null; var entries = name.Split(new[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var @class = Classes.Find(c => c.Name.Equals(name, stringComparison)) ?? Namespaces.Select(n => n.FindClass(name, stringComparison)).FirstOrDefault(c => c != null); if (@class != null) return @class.CompleteDeclaration == null ? @class : (Class) @class.CompleteDeclaration; return null; } var className = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); DeclarationContext declContext = FindDeclaration(namespaces); if (declContext == null) { declContext = FindClass(entries[0]); if (declContext == null) return null; } return declContext.FindClass(className); } public Class FindClass(string name, bool isComplete, bool createDecl = false) { var @class = FindClass(name); if (@class == null) { if (createDecl) { @class = CreateClass(name, isComplete); Classes.Add(@class); } return @class; } if (@class.IsIncomplete == !isComplete) return @class; if (!createDecl) return null; var newClass = CreateClass(name, isComplete); // Replace the incomplete declaration with the complete one. if (@class.IsIncomplete) { @class.CompleteDeclaration = newClass; Classes.Replace(@class, newClass); } return newClass; } public FunctionTemplate FindFunctionTemplate(string name) { return Templates.OfType<FunctionTemplate>() .FirstOrDefault(t => t.Name == name); } public FunctionTemplate FindFunctionTemplateByUSR(string usr) { return Templates.OfType<FunctionTemplate>() .FirstOrDefault(t => t.USR == usr); } public IEnumerable<ClassTemplate> FindClassTemplate(string name) { foreach (var template in Templates.OfType<ClassTemplate>().Where(t => t.Name == name)) yield return template; foreach (var @namespace in Namespaces) foreach (var template in @namespace.FindClassTemplate(name)) yield return template; } public ClassTemplate FindClassTemplateByUSR(string usr) { return Templates.OfType<ClassTemplate>() .FirstOrDefault(t => t.USR == usr); } public TypedefNameDecl FindTypedef(string name, bool createDecl = false) { var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var typeDef = Typedefs.Find(e => e.Name.Equals(name)); if (typeDef == null && createDecl) { typeDef = new TypedefDecl { Name = name, Namespace = this }; Typedefs.Add(typeDef); } return typeDef; } var typeDefName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindTypedef(typeDefName, createDecl); } public T FindType<T>(string name) where T : Declaration { var type = FindEnum(name) ?? FindFunction(name) ?? (Declaration)FindClass(name) ?? FindTypedef(name); return type as T; } public Enumeration FindEnumWithItem(string name) { return Enums.Find(e => e.ItemsByName.ContainsKey(name)) ?? (from declContext in Namespaces.Union<DeclarationContext>(Classes) let @enum = declContext.FindEnumWithItem(name) where @enum != null select @enum).FirstOrDefault(); } public virtual IEnumerable<Function> FindOperator(CXXOperatorKind kind) { return Functions.Where(fn => fn.OperatorKind == kind); } public virtual IEnumerable<Function> GetOverloads(Function function) { if (function.IsOperator) return FindOperator(function.OperatorKind); return Functions.Where(fn => fn.Name == function.Name); } public bool HasDeclarations { get { Func<Declaration, bool> pred = (t => t.IsGenerated); return Enums.Exists(pred) || HasFunctions || Typedefs.Exists(pred) || Classes.Any() || Namespaces.Exists(n => n.HasDeclarations) || Templates.Any(pred); } } public bool HasFunctions { get { Func<Declaration, bool> pred = (t => t.IsGenerated); return Functions.Exists(pred) || Namespaces.Exists(n => n.HasFunctions); } } public bool IsRoot { get { return Namespace == null; } } } /// <summary> /// Represents a C++ namespace. /// </summary> public class Namespace : DeclarationContext { public override string LogicalName { get { return IsInline ? string.Empty : base.Name; } } public override string LogicalOriginalName { get { return IsInline ? string.Empty : base.OriginalName; } } public bool IsInline; public override T Visit<T>(IDeclVisitor<T> visitor) { return visitor.VisitNamespace(this); } } }
#region License /* * NReco Data library (http://www.nrecosite.com/) * Copyright 2016 Vitaliy Fedorchenko * Distributed under the MIT license * * 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; using System.Collections.Generic; using System.Data; using System.Text; using System.ComponentModel; namespace NReco.Data { /// <summary> /// Automatically generates SQL commands for SELECT/INSERT/UPDATE/DELETE queries. /// </summary> public class DbCommandBuilder : IDbCommandBuilder { /// <summary> /// Gets DB Factory component. /// </summary> public IDbFactory DbFactory { get; private set; } /// <summary> /// Gets or sets template for SQL SELECT query. /// </summary> /// <remarks> /// Template is processed with <see cref="StringTemplate"/>. /// List of available variables: /// <list> /// <item>@columns (comma-separated list of fields from Query or '*')</item> /// <item>@table (table name, possibly with alias like 'users u')</item> /// <item>@where (query conditions, may be empty)</item> /// <item>@orderby (order by expression, may be empty)</item> /// <item>@recordoffset (starting record index offset, 0 by default)</item> /// <item>@recordcount (max number of records to return, empty if not specified)</item> /// <item>@recordtop (recordoffset+recordcount, empty if recordcount is not specified)</item> /// <item>@&lt;extendedPropertyKey&gt; (value from Query.ExtendedProperties dictionary)</item> /// </list> /// @record* variables are useful for database-specific paging optimizations, for example: /// <code> /// // MS SQL TOP syntax /// DbCommandBuilder cmdBuilder; /// cmdBuilder = "SELECT @recordtop[TOP {0}] @columns FROM @table @where[ WHERE {0}] @groupby[ GROUP BY {0}] @orderby[ ORDER BY {0}]"; /// </code> /// <code> /// // PostgreSql LIMIT and OFFSET syntax /// DbCommandBuilder cmdBuilder; /// cmdBuilder = "SELECT @columns FROM @table @where[ WHERE {0}] @groupby[ GROUP BY {0}] @orderby[ ORDER BY {0}] @recordcount[LIMIT {0}] @recordoffset[OFFSET {0}]"; /// </code> /// Note that if offset is applied on DB level and <see cref="DbDataAdapter.ApplyOffset"/> should be false. /// </remarks> public string SelectTemplate { get; set; } = "SELECT @columns FROM @table@where[ WHERE {0}]@groupby[ GROUP BY {0}]@orderby[ ORDER BY {0}]"; /// <summary> /// Gets or sets template for SQL UPDATE query. /// </summary> /// <remarks> /// Template is processed with <see cref="StringTemplate"/>. /// List of available variables: /// <list> /// <item>@table (table name)</item> /// <item>@set (comma-separated set statements)</item> /// <item>@where (query conditions, may be empty)</item> /// </list> /// </remarks> public string UpdateTemplate { get; set; } = "UPDATE @table SET @set @where[WHERE {0}]"; /// <summary> /// Gets or sets template for SQL INSERT query. /// </summary> /// <remarks> /// Template is processed with <see cref="StringTemplate"/>. /// List of available variables: /// <list> /// <item>@table (table name)</item> /// <item>@columns (comma-separated list of columns)</item> /// <item>@values (comma-separated list of values)</item> /// </list> /// </remarks> public string InsertTemplate { get; set; } = "INSERT INTO @table (@columns) VALUES (@values)"; /// <summary> /// Gets or sets template for SQL DELETE query. /// </summary> /// <remarks> /// Template is processed with <see cref="StringTemplate"/>. /// List of available variables: /// <list> /// <item>@table (table name)</item> /// <item>@where (query conditions, may be empty)</item> /// </list> /// </remarks> public string DeleteTemplate { get; set; } = "DELETE FROM @table @where[WHERE {0}]"; /// <summary> /// Gets or sets view name -> <see cref="DbDataView"/> dictionary. /// </summary> public IDictionary<string,DbDataView> Views { get; set; } /// <summary> /// Initializes a new instance of the DbCommandBuilder. /// </summary> /// <param name="dbFactory">DB provider-specific factory implementation</param> public DbCommandBuilder(IDbFactory dbFactory) { DbFactory = dbFactory; Views = new Dictionary<string,DbDataView>(); } protected ISqlExpressionBuilder GetSqlBuilder(IDbCommand cmd) { ISqlExpressionBuilder sqlBuilder = null; sqlBuilder = DbFactory.CreateSqlBuilder(cmd, (q) => { return BuildSelectInternal(q,sqlBuilder,true); } ); return sqlBuilder; } protected virtual IDbCommand GetCommand() { return DbFactory.CreateCommand(); } protected virtual void SetCommandText(IDbCommand cmd, string sqlStatement) { cmd.CommandText = sqlStatement; } /// <summary> /// Gets the automatically generated <see cref="IDbCommand"/> object to select rows by specified <see cref="Query"/>. /// </summary> /// <param name="query">query that determines table and select options</param> /// <returns></returns> public virtual IDbCommand GetSelectCommand(Query query) { var cmd = GetCommand(); var cmdSqlBuilder = GetSqlBuilder(cmd); SetCommandText(cmd,BuildSelectInternal(query, cmdSqlBuilder, false)); return cmd; } DbDataView defaultSelectView = null; internal string BuildSelectInternal(Query query, ISqlExpressionBuilder sqlBuilder, bool isSubquery) { DbDataView view = null; if (Views==null || !Views.TryGetValue(query.Table.Name, out view)) { // default template if (defaultSelectView!=null && defaultSelectView.SelectTemplate == SelectTemplate) view = defaultSelectView; else view = defaultSelectView = new DbDataView(SelectTemplate); } return view.FormatSelectSql(query,sqlBuilder,isSubquery); } /// <summary> /// Gets the automatically generated <see cref="IDbCommand"/> object to delete rows by specified <see cref="Query"/>. /// </summary> /// <param name="query">query that determines delete table and conditions</param> /// <returns>delete SQL command</returns> public virtual IDbCommand GetDeleteCommand(Query query) { var cmd = GetCommand(); var dbSqlBuilder = GetSqlBuilder(cmd); // prepare WHERE part var whereExpression = dbSqlBuilder.BuildExpression( query.Condition ); var tblName = dbSqlBuilder.BuildTableName( new QTable(query.Table.Name, null) ); var deleteTpl = new StringTemplate(DeleteTemplate); SetCommandText(cmd, deleteTpl.FormatTemplate( (varName) => { switch (varName) { case "table": return new StringTemplate.TokenResult(tblName); case "where": return new StringTemplate.TokenResult(whereExpression); } return StringTemplate.TokenResult.NotDefined; }) ); return cmd; } /// <summary> /// Gets the automatically generated <see cref="IDbCommand"/> object to update rows by specified <see cref="Query"/>. /// </summary> /// <param name="query">query that determines update table and conditions</param> /// <param name="data">changeset data</param> /// <returns>update SQL command</returns> public virtual IDbCommand GetUpdateCommand(Query query, IEnumerable<KeyValuePair<string,IQueryValue>> data) { var cmd = GetCommand(); var dbSqlBuilder = GetSqlBuilder(cmd); // prepare fields Part var setExpression = new StringBuilder(); foreach (var setField in data) { if (setExpression.Length>0) setExpression.Append(','); setExpression.Append( dbSqlBuilder.BuildValue(new QField(setField.Key)) ); setExpression.Append('='); setExpression.Append( dbSqlBuilder.BuildValue(setField.Value) ); } // prepare WHERE part string whereExpression = dbSqlBuilder.BuildExpression( query.Condition ); var tblName = dbSqlBuilder.BuildTableName( new QTable(query.Table.Name, null) ); var updateTpl = new StringTemplate(UpdateTemplate); SetCommandText(cmd, updateTpl.FormatTemplate( (varName) => { switch (varName) { case "table": return new StringTemplate.TokenResult(tblName); case "set": return new StringTemplate.TokenResult(setExpression.ToString()); case "where": return new StringTemplate.TokenResult(whereExpression); } return StringTemplate.TokenResult.NotDefined; }) ); return cmd; } /// <summary> /// Gets the automatically generated <see cref="IDbCommand"/> object to insert new record. /// </summary> /// <param name="tableName">table name</param> /// <param name="data">new record data</param> /// <returns>insert SQL command</returns> public virtual IDbCommand GetInsertCommand(string tableName, IEnumerable<KeyValuePair<string,IQueryValue>> data) { var cmd = GetCommand(); var dbSqlBuilder = GetSqlBuilder(cmd); // Prepare fields part var columns = new StringBuilder(); var values = new StringBuilder(); foreach (var setField in data) { if (columns.Length>0) columns.Append(','); columns.Append( dbSqlBuilder.BuildValue( (QField)setField.Key) ); if (values.Length>0) values.Append(','); values.Append(dbSqlBuilder.BuildValue(setField.Value)); } var tblName = dbSqlBuilder.BuildTableName( new QTable(tableName, null) ); var colStr = columns.ToString(); var valStr = values.ToString(); var insertTpl = new StringTemplate(InsertTemplate); SetCommandText(cmd, insertTpl.FormatTemplate( (varName) => { switch (varName) { case "table": return new StringTemplate.TokenResult(tblName); case "columns": return new StringTemplate.TokenResult(colStr); case "values": return new StringTemplate.TokenResult(valStr); } return StringTemplate.TokenResult.NotDefined; }) ); return cmd; } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Targets; namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using NLog.Layouts; using Xunit; public class JsonLayoutTests : NLogTestBase { [Fact] public void JsonLayoutRendering() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"hello, world\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingNoSpaces() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), }, SuppressSpaces = true }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; Assert.Equal("{\"date\":\"2010-01-01 12:34:56.0000\",\"level\":\"Info\",\"message\":\"hello, world\"}", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingAndEncodingSpecialCharacters() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "\"hello, world\"" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"\\\"hello, world\\\"\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingAndEncodingLineBreaks() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello,\n\r world" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"hello,\\n\\r world\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingAndNotEncodingMessageAttribute() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}", false), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "{ \"hello\" : \"world\" }" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": { \"hello\" : \"world\" } }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingAndEncodingMessageAttribute() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "{ \"hello\" : \"world\" }" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"{ \\\"hello\\\" : \\\"world\\\" }\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void NestedJsonAttrTest() { var jsonLayout = new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=Type}"), new JsonAttribute("message", "${exception:format=Message}"), new JsonAttribute("innerException", new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), } }, //don't escape layout false) } }; var logEventInfo = new LogEventInfo { Exception = new NLogRuntimeException("test", new NullReferenceException("null is bad!")) }; var json = jsonLayout.Render(logEventInfo); Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\", \"innerException\": { \"type\": \"System.NullReferenceException\", \"message\": \"null is bad!\" } }", json); } [Fact] public void NestedJsonAttrDoesNotRenderEmptyLiteralIfRenderEmptyObjectIsFalseTest() { var jsonLayout = new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=Type}"), new JsonAttribute("message", "${exception:format=Message}"), new JsonAttribute("innerException", new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), }, RenderEmptyObject = false }, //don't escape layout false) } }; var logEventInfo = new LogEventInfo { Exception = new NLogRuntimeException("test", (Exception)null) }; var json = jsonLayout.Render(logEventInfo); Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\" }", json); } [Fact] public void NestedJsonAttrRendersEmptyLiteralIfRenderEmptyObjectIsTrueTest() { var jsonLayout = new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=Type}"), new JsonAttribute("message", "${exception:format=Message}"), new JsonAttribute("innerException", new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), }, RenderEmptyObject = true }, //don't escape layout false) } }; var logEventInfo = new LogEventInfo { Exception = new NLogRuntimeException("test", (Exception)null) }; var json = jsonLayout.Render(logEventInfo); Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\", \"innerException\": { } }", json); } [Fact] public void NestedJsonAttrTestFromXML() { var configXml = @" <nlog> <targets> <target name='jsonFile' type='File' fileName='log.json'> <layout type='JsonLayout'> <attribute name='time' layout='${longdate}' /> <attribute name='level' layout='${level:upperCase=true}'/> <attribute name='nested' encode='false' > <layout type='JsonLayout'> <attribute name='message' layout='${message}' /> <attribute name='exception' layout='${exception}' /> </layout> </attribute> </layout> </target> </targets> <rules> </rules> </nlog> "; var config = CreateConfigurationFromString(configXml); Assert.NotNull(config); var target = config.FindTargetByName<FileTarget>("jsonFile"); Assert.NotNull(target); var jsonLayout = target.Layout as JsonLayout; Assert.NotNull(jsonLayout); var attrs = jsonLayout.Attributes; Assert.NotNull(attrs); Assert.Equal(3, attrs.Count); Assert.Equal(typeof(SimpleLayout), attrs[0].Layout.GetType()); Assert.Equal(typeof(SimpleLayout), attrs[1].Layout.GetType()); Assert.Equal(typeof(JsonLayout), attrs[2].Layout.GetType()); var nestedJsonLayout = (JsonLayout)attrs[2].Layout; Assert.Equal(2, nestedJsonLayout.Attributes.Count); Assert.Equal("'${message}'", nestedJsonLayout.Attributes[0].Layout.ToString()); Assert.Equal("'${exception}'", nestedJsonLayout.Attributes[1].Layout.ToString()); var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2016, 10, 30, 13, 30, 55), Message = "this is message", Level = LogLevel.Info, Exception = new NLogRuntimeException("test", new NullReferenceException("null is bad!")) }; var json = jsonLayout.Render(logEventInfo); Assert.Equal("{ \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"INFO\", \"nested\": { \"message\": \"this is message\", \"exception\": \"test\" } }", json); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; namespace System.Data.SqlClient { sealed internal class SqlConnectionFactory : DbConnectionFactory { private SqlConnectionFactory() : base() { } public static readonly SqlConnectionFactory SingletonInstance = new SqlConnectionFactory(); override public DbProviderFactory ProviderFactory { get { return SqlClientFactory.Instance; } } override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) { return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection, userOptions: null); } override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) { SqlConnectionString opt = (SqlConnectionString)options; SqlConnectionPoolKey key = (SqlConnectionPoolKey)poolKey; SqlInternalConnection result = null; SessionData recoverySessionData = null; SqlConnection sqlOwningConnection = owningConnection as SqlConnection; bool applyTransientFaultHandling = sqlOwningConnection != null ? sqlOwningConnection._applyTransientFaultHandling : false; SqlConnectionString userOpt = null; if (userOptions != null) { userOpt = (SqlConnectionString)userOptions; } else if (owningConnection != null) { userOpt = (SqlConnectionString)(((SqlConnection)owningConnection).UserConnectionOptions); } if (owningConnection != null) { recoverySessionData = ((SqlConnection)owningConnection)._recoverySessionData; } bool redirectedUserInstance = false; DbConnectionPoolIdentity identity = null; // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security. // Used by notifications. if (opt.IntegratedSecurity) { if (pool != null) { identity = pool.Identity; } else { identity = DbConnectionPoolIdentity.GetCurrent(); } } // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES // If "user instance=true" is in the connection string, we're using SSE user instances if (opt.UserInstance) { // opt.DataSource is used to create the SSE connection redirectedUserInstance = true; string instanceName; if ((null == pool) || (null != pool && pool.Count <= 0)) { // Non-pooled or pooled and no connections in the pool. SqlInternalConnectionTds sseConnection = null; try { // We throw an exception in case of a failure // NOTE: Cloning connection option opt to set 'UserInstance=True' and 'Enlist=False' // This first connection is established to SqlExpress to get the instance name // of the UserInstance. SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, true /* user instance=true */); sseConnection = new SqlInternalConnectionTds(identity, sseopt, null, false, applyTransientFaultHandling: applyTransientFaultHandling); // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance. instanceName = sseConnection.InstanceName; if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal)) { throw SQL.NonLocalSSEInstance(); } if (null != pool) { // Pooled connection - cache result SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo; // No lock since we are already in creation mutex providerInfo.InstanceName = instanceName; } } finally { if (null != sseConnection) { sseConnection.Dispose(); } } } else { // Cached info from pool. SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo; // No lock since we are already in creation mutex instanceName = providerInfo.InstanceName; } // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was // retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'. // options immutable - stored in global hash - don't modify opt = new SqlConnectionString(opt, instanceName, false /* user instance=false */); poolGroupProviderInfo = null; // null so we do not pass to constructor below... } result = new SqlInternalConnectionTds(identity, opt, poolGroupProviderInfo, redirectedUserInstance, userOpt, recoverySessionData, applyTransientFaultHandling: applyTransientFaultHandling); return result; } protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous) { Debug.Assert(!ADP.IsEmpty(connectionString), "empty connectionString"); SqlConnectionString result = new SqlConnectionString(connectionString); return result; } override internal DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions) { DbConnectionPoolProviderInfo providerInfo = null; if (((SqlConnectionString)connectionOptions).UserInstance) { providerInfo = new SqlConnectionPoolProviderInfo(); } return providerInfo; } override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions) { SqlConnectionString opt = (SqlConnectionString)connectionOptions; DbConnectionPoolGroupOptions poolingOptions = null; if (opt.Pooling) { // never pool context connections. int connectionTimeout = opt.ConnectTimeout; if ((0 < connectionTimeout) && (connectionTimeout < Int32.MaxValue / 1000)) connectionTimeout *= 1000; else if (connectionTimeout >= Int32.MaxValue / 1000) connectionTimeout = Int32.MaxValue; poolingOptions = new DbConnectionPoolGroupOptions( opt.IntegratedSecurity, opt.MinPoolSize, opt.MaxPoolSize, connectionTimeout, opt.LoadBalanceTimeout ); } return poolingOptions; } override internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions) { return new SqlConnectionPoolGroupProviderInfo((SqlConnectionString)connectionOptions); } internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key) { SqlConnectionString connectionOptions = (SqlConnectionString)SingletonInstance.FindConnectionOptions(key); if (null == connectionOptions) { connectionOptions = new SqlConnectionString(key.ConnectionString); } if (connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } return connectionOptions; } override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) { SqlConnection c = (connection as SqlConnection); if (null != c) { return c.PoolGroup; } return null; } override internal DbConnectionInternal GetInnerConnection(DbConnection connection) { SqlConnection c = (connection as SqlConnection); if (null != c) { return c.InnerConnection; } return null; } override internal void PermissionDemand(DbConnection outerConnection) { SqlConnection c = (outerConnection as SqlConnection); if (null != c) { c.PermissionDemand(); } } override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { SqlConnection c = (outerConnection as SqlConnection); if (null != c) { c.PoolGroup = poolGroup; } } override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { c.SetInnerConnectionEvent(to); } } override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { return c.SetInnerConnectionFrom(to, from); } return false; } override internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { c.SetInnerConnectionTo(to); } } } }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEditor.FacebookEditor; using UnityEngine; [CustomEditor(typeof(FacebookSettings))] public class FacebookSettingsEditor : UnityEditor.Editor { private bool showFacebookInitSettings = false; private bool showAndroidUtils = EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android; private bool showIOSSettings = EditorUserBuildSettings.activeBuildTarget.ToString() == "iOS"; private bool showAppLinksSettings = false; private bool showAboutSection = false; private GUIContent appNameLabel = new GUIContent("App Name [?]:", "For your own use and organization.\n(ex. 'dev', 'qa', 'prod')"); private GUIContent appIdLabel = new GUIContent("App Id [?]:", "Facebook App Ids can be found at https://developers.facebook.com/apps"); private GUIContent urlSuffixLabel = new GUIContent("URL Scheme Suffix [?]", "Use this to share Facebook APP ID's across multiple iOS apps. https://developers.facebook.com/docs/ios/share-appid-across-multiple-apps-ios-sdk/"); private GUIContent cookieLabel = new GUIContent("Cookie [?]", "Sets a cookie which your server-side code can use to validate a user's Facebook session"); private GUIContent loggingLabel = new GUIContent("Logging [?]", "(Web Player only) If true, outputs a verbose log to the Javascript console to facilitate debugging."); private GUIContent statusLabel = new GUIContent("Status [?]", "If 'true', attempts to initialize the Facebook object with valid session data."); private GUIContent xfbmlLabel = new GUIContent("Xfbml [?]", "(Web Player only If true) Facebook will immediately parse any XFBML elements on the Facebook Canvas page hosting the app"); private GUIContent frictionlessLabel = new GUIContent("Frictionless Requests [?]", "Use frictionless app requests, as described in their own documentation."); private GUIContent packageNameLabel = new GUIContent("Package Name [?]", "aka: the bundle identifier"); private GUIContent classNameLabel = new GUIContent("Class Name [?]", "aka: the activity name"); private GUIContent debugAndroidKeyLabel = new GUIContent("Debug Android Key Hash [?]", "Copy this key to the Facebook Settings in order to test a Facebook Android app"); private GUIContent sdkVersion = new GUIContent("SDK Version [?]", "This Unity Facebook SDK version. If you have problems or compliments please include this so we know exactly what version to look out for."); public override void OnInspectorGUI() { EditorGUILayout.Separator(); this.AppIdGUI(); EditorGUILayout.Separator(); this.FBParamsInitGUI(); EditorGUILayout.Separator(); this.AndroidUtilGUI(); EditorGUILayout.Separator(); this.IOSUtilGUI(); EditorGUILayout.Separator(); this.AppLinksUtilGUI(); EditorGUILayout.Separator(); this.AboutGUI(); EditorGUILayout.Separator(); this.BuildGUI(); } private void AppIdGUI() { EditorGUILayout.LabelField("Add the Facebook App Id(s) associated with this game"); if (FacebookSettings.AppIds.Count == 0 || FacebookSettings.AppId == "0") { EditorGUILayout.HelpBox("Invalid App Id", MessageType.Error); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.appNameLabel); EditorGUILayout.LabelField(this.appIdLabel); EditorGUILayout.EndHorizontal(); for (int i = 0; i < FacebookSettings.AppIds.Count; ++i) { EditorGUILayout.BeginHorizontal(); FacebookSettings.AppLabels[i] = EditorGUILayout.TextField(FacebookSettings.AppLabels[i]); GUI.changed = false; FacebookSettings.AppIds[i] = EditorGUILayout.TextField(FacebookSettings.AppIds[i]); if (GUI.changed) { FacebookSettings.SettingsChanged(); ManifestMod.GenerateManifest(); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add Another App Id")) { FacebookSettings.AppLabels.Add("New App"); FacebookSettings.AppIds.Add("0"); FacebookSettings.AppLinkSchemes.Add(new FacebookSettings.UrlSchemes()); FacebookSettings.SettingsChanged(); } if (FacebookSettings.AppLabels.Count > 1) { if (GUILayout.Button("Remove Last App Id")) { FacebookSettings.AppLabels.Pop(); FacebookSettings.AppIds.Pop(); FacebookSettings.AppLinkSchemes.Pop(); FacebookSettings.SettingsChanged(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); if (FacebookSettings.AppIds.Count > 1) { EditorGUILayout.HelpBox("2) Select Facebook App Id to be compiled with this game", MessageType.None); GUI.changed = false; FacebookSettings.SelectedAppIndex = EditorGUILayout.Popup( "Selected App Id", FacebookSettings.SelectedAppIndex, FacebookSettings.AppIds.ToArray()); if (GUI.changed) { ManifestMod.GenerateManifest(); } EditorGUILayout.Space(); } else { FacebookSettings.SelectedAppIndex = 0; } } private void FBParamsInitGUI() { this.showFacebookInitSettings = EditorGUILayout.Foldout(this.showFacebookInitSettings, "FB.Init() Parameters"); if (this.showFacebookInitSettings) { FacebookSettings.Cookie = EditorGUILayout.Toggle(this.cookieLabel, FacebookSettings.Cookie); FacebookSettings.Logging = EditorGUILayout.Toggle(this.loggingLabel, FacebookSettings.Logging); FacebookSettings.Status = EditorGUILayout.Toggle(this.statusLabel, FacebookSettings.Status); FacebookSettings.Xfbml = EditorGUILayout.Toggle(this.xfbmlLabel, FacebookSettings.Xfbml); FacebookSettings.FrictionlessRequests = EditorGUILayout.Toggle(this.frictionlessLabel, FacebookSettings.FrictionlessRequests); } EditorGUILayout.Space(); } private void IOSUtilGUI() { this.showIOSSettings = EditorGUILayout.Foldout(this.showIOSSettings, "iOS Build Settings"); if (this.showIOSSettings) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.urlSuffixLabel, GUILayout.Width(135), GUILayout.Height(16)); FacebookSettings.IosURLSuffix = EditorGUILayout.TextField(FacebookSettings.IosURLSuffix); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); } private void AndroidUtilGUI() { this.showAndroidUtils = EditorGUILayout.Foldout(this.showAndroidUtils, "Android Build Facebook Settings"); if (this.showAndroidUtils) { if (!FacebookAndroidUtil.SetupProperly) { var msg = "Your Android setup is not right. Check the documentation."; switch (FacebookAndroidUtil.SetupError) { case FacebookAndroidUtil.ErrorNoSDK: msg = "You don't have the Android SDK setup! Go to " + (Application.platform == RuntimePlatform.OSXEditor ? "Unity" : "Edit") + "->Preferences... and set your Android SDK Location under External Tools"; break; case FacebookAndroidUtil.ErrorNoKeystore: msg = "Your android debug keystore file is missing! You can create new one by creating and building empty Android project in Ecplise."; break; case FacebookAndroidUtil.ErrorNoKeytool: msg = "Keytool not found. Make sure that Java is installed, and that Java tools are in your path."; break; case FacebookAndroidUtil.ErrorNoOpenSSL: msg = "OpenSSL not found. Make sure that OpenSSL is installed, and that it is in your path."; break; case FacebookAndroidUtil.ErrorKeytoolError: msg = "Unkown error while getting Debug Android Key Hash."; break; } EditorGUILayout.HelpBox(msg, MessageType.Warning); } EditorGUILayout.LabelField( "Copy and Paste these into your \"Native Android App\" Settings on developers.facebook.com/apps"); this.SelectableLabelField(this.packageNameLabel, PlayerSettings.applicationIdentifier); this.SelectableLabelField(this.classNameLabel, ManifestMod.DeepLinkingActivityName); this.SelectableLabelField(this.debugAndroidKeyLabel, FacebookAndroidUtil.DebugKeyHash); if (GUILayout.Button("Regenerate Android Manifest")) { ManifestMod.GenerateManifest(); } } EditorGUILayout.Space(); } private void AppLinksUtilGUI() { this.showAppLinksSettings = EditorGUILayout.Foldout(this.showAppLinksSettings, "App Links Settings"); if (this.showAppLinksSettings) { for (int i = 0; i < FacebookSettings.AppLinkSchemes.Count; ++i) { EditorGUILayout.LabelField(string.Format("App Link Schemes for '{0}'", FacebookSettings.AppLabels[i])); List<string> currentAppLinkSchemes = FacebookSettings.AppLinkSchemes[i].Schemes; for (int j = 0; j < currentAppLinkSchemes.Count; ++j) { GUI.changed = false; string scheme = EditorGUILayout.TextField(currentAppLinkSchemes[j]); if (scheme != currentAppLinkSchemes[j]) { currentAppLinkSchemes[j] = scheme; FacebookSettings.SettingsChanged(); } if (GUI.changed) { ManifestMod.GenerateManifest(); } } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add a Scheme")) { FacebookSettings.AppLinkSchemes[i].Schemes.Add(string.Empty); FacebookSettings.SettingsChanged(); } if (currentAppLinkSchemes.Count > 0) { if (GUILayout.Button("Remove Last Scheme")) { FacebookSettings.AppLinkSchemes[i].Schemes.Pop(); } } EditorGUILayout.EndHorizontal(); } } } private void AboutGUI() { this.showAboutSection = EditorGUILayout.Foldout(this.showAboutSection, "About the Facebook SDK"); if (this.showAboutSection) { this.SelectableLabelField(this.sdkVersion, FacebookSdkVersion.Build); EditorGUILayout.Space(); } } private void SelectableLabelField(GUIContent label, string value) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(label, GUILayout.Width(180), GUILayout.Height(16)); EditorGUILayout.SelectableLabel(value, GUILayout.Height(16)); EditorGUILayout.EndHorizontal(); } private void BuildGUI() { if (GUILayout.Button("Build SDK Package")) { try { FacebookBuild.ExportPackage(); } catch (System.Exception e) { EditorUtility.DisplayDialog("Error Exporting unityPackage", e.Message, "Okay"); } EditorUtility.DisplayDialog("Finished Exporting unityPackage", "Exported to CUI/SDKPackage", "Okay"); } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace osu.Game.IO.Legacy { /// <summary> SerializationReader. Extends BinaryReader to add additional data types, /// handle null strings and simplify use with ISerializable. </summary> public class SerializationReader : BinaryReader { private readonly Stream stream; public SerializationReader(Stream s) : base(s, Encoding.UTF8) { stream = s; } public int RemainingBytes => (int)(stream.Length - stream.Position); /// <summary> Static method to take a SerializationInfo object (an input to an ISerializable constructor) /// and produce a SerializationReader from which serialized objects can be read </summary>. public static SerializationReader GetReader(SerializationInfo info) { byte[] byteArray = (byte[])info.GetValue("X", typeof(byte[])); MemoryStream ms = new MemoryStream(byteArray); return new SerializationReader(ms); } /// <summary> Reads a string from the buffer. Overrides the base implementation so it can cope with nulls. </summary> public override string ReadString() { if (0 == ReadByte()) return null; return base.ReadString(); } /// <summary> Reads a byte array from the buffer, handling nulls and the array length. </summary> public byte[] ReadByteArray() { int len = ReadInt32(); if (len > 0) return ReadBytes(len); if (len < 0) return null; return Array.Empty<byte>(); } /// <summary> Reads a char array from the buffer, handling nulls and the array length. </summary> public char[] ReadCharArray() { int len = ReadInt32(); if (len > 0) return ReadChars(len); if (len < 0) return null; return Array.Empty<char>(); } /// <summary> Reads a DateTime from the buffer. </summary> public DateTime ReadDateTime() { long ticks = ReadInt64(); if (ticks < 0) throw new IOException("Bad ticks count read!"); return new DateTime(ticks, DateTimeKind.Utc); } /// <summary> Reads a generic list from the buffer. </summary> public IList<T> ReadBList<T>(bool skipErrors = false) where T : ILegacySerializable, new() { int count = ReadInt32(); if (count < 0) return null; IList<T> d = new List<T>(count); SerializationReader sr = new SerializationReader(BaseStream); for (int i = 0; i < count; i++) { T obj = new T(); try { obj.ReadFromStream(sr); } catch (Exception) { if (skipErrors) continue; throw; } d.Add(obj); } return d; } /// <summary> Reads a generic list from the buffer. </summary> public IList<T> ReadList<T>() { int count = ReadInt32(); if (count < 0) return null; IList<T> d = new List<T>(count); for (int i = 0; i < count; i++) d.Add((T)ReadObject()); return d; } /// <summary> Reads a generic Dictionary from the buffer. </summary> public IDictionary<T, U> ReadDictionary<T, U>() { int count = ReadInt32(); if (count < 0) return null; IDictionary<T, U> d = new Dictionary<T, U>(); for (int i = 0; i < count; i++) d[(T)ReadObject()] = (U)ReadObject(); return d; } /// <summary> Reads an object which was added to the buffer by WriteObject. </summary> public object ReadObject() { ObjType t = (ObjType)ReadByte(); switch (t) { case ObjType.boolType: return ReadBoolean(); case ObjType.byteType: return ReadByte(); case ObjType.uint16Type: return ReadUInt16(); case ObjType.uint32Type: return ReadUInt32(); case ObjType.uint64Type: return ReadUInt64(); case ObjType.sbyteType: return ReadSByte(); case ObjType.int16Type: return ReadInt16(); case ObjType.int32Type: return ReadInt32(); case ObjType.int64Type: return ReadInt64(); case ObjType.charType: return ReadChar(); case ObjType.stringType: return base.ReadString(); case ObjType.singleType: return ReadSingle(); case ObjType.doubleType: return ReadDouble(); case ObjType.decimalType: return ReadDecimal(); case ObjType.dateTimeType: return ReadDateTime(); case ObjType.byteArrayType: return ReadByteArray(); case ObjType.charArrayType: return ReadCharArray(); case ObjType.otherType: return DynamicDeserializer.Deserialize(BaseStream); default: return null; } } public class DynamicDeserializer { private static VersionConfigToNamespaceAssemblyObjectBinder versionBinder; private static BinaryFormatter formatter; private static void initialize() { versionBinder = new VersionConfigToNamespaceAssemblyObjectBinder(); formatter = new BinaryFormatter { AssemblyFormat = FormatterAssemblyStyle.Simple, Binder = versionBinder }; } public static object Deserialize(Stream stream) { if (formatter == null) initialize(); Debug.Assert(formatter != null, "formatter != null"); return formatter.Deserialize(stream); } #region Nested type: VersionConfigToNamespaceAssemblyObjectBinder public sealed class VersionConfigToNamespaceAssemblyObjectBinder : SerializationBinder { private readonly Dictionary<string, Type> cache = new Dictionary<string, Type>(); public override Type BindToType(string assemblyName, string typeName) { Type typeToDeserialize; if (cache.TryGetValue(assemblyName + typeName, out typeToDeserialize)) return typeToDeserialize; List<Type> tmpTypes = new List<Type>(); Type genType = null; if (typeName.Contains("System.Collections.Generic") && typeName.Contains("[[")) { string[] splitTyps = typeName.Split('['); foreach (string typ in splitTyps) { if (typ.Contains("Version")) { string asmTmp = typ.Substring(typ.IndexOf(',') + 1); string asmName = asmTmp.Remove(asmTmp.IndexOf(']')).Trim(); string typName = typ.Remove(typ.IndexOf(',')); tmpTypes.Add(BindToType(asmName, typName)); } else if (typ.Contains("Generic")) { genType = BindToType(assemblyName, typ); } } if (genType != null && tmpTypes.Count > 0) { return genType.MakeGenericType(tmpTypes.ToArray()); } } string toAssemblyName = assemblyName.Split(',')[0]; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assemblies) { if (a.FullName.Split(',')[0] == toAssemblyName) { typeToDeserialize = a.GetType(typeName); break; } } cache.Add(assemblyName + typeName, typeToDeserialize); return typeToDeserialize; } } #endregion } } public enum ObjType : byte { nullType, boolType, byteType, uint16Type, uint32Type, uint64Type, sbyteType, int16Type, int32Type, int64Type, charType, stringType, singleType, doubleType, decimalType, dateTimeType, byteArrayType, charArrayType, otherType, ILegacySerializableType } }
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Text; using Xunit; public class FileVersionInfoTest { private const string NativeConsoleAppFileName = "NativeConsoleApp.exe"; private const string NativeLibraryFileName = "NativeLibrary.dll"; private const string SecondNativeLibraryFileName = "SecondNativeLibrary.dll"; private const string TestAssemblyFileName = "System.Diagnostics.FileVersionInfo.TestAssembly.dll"; private const string TestCsFileName = "Assembly1.cs"; private const string TestNotFoundFileName = "notfound.dll"; [Fact] [PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows public void FileVersionInfo_Normal() { // NativeConsoleApp (English) VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), NativeConsoleAppFileName), new MyFVI() { Comments = "", CompanyName = "Microsoft Corporation", FileBuildPart = 3, FileDescription = "This is the description for the native console application.", FileMajorPart = 5, FileMinorPart = 4, FileName = Path.Combine(Directory.GetCurrentDirectory(), NativeConsoleAppFileName), FilePrivatePart = 2, FileVersion = "5.4.3.2", InternalName = NativeConsoleAppFileName, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = true, IsSpecialBuild = true, Language = GetFileVersionLanguage(0x0409), //English (United States) LegalCopyright = "Copyright (C) 2050", LegalTrademarks = "", OriginalFilename = NativeConsoleAppFileName, PrivateBuild = "", ProductBuildPart = 3, ProductMajorPart = 5, ProductMinorPart = 4, ProductName = Path.GetFileNameWithoutExtension(NativeConsoleAppFileName), ProductPrivatePart = 2, ProductVersion = "5.4.3.2", SpecialBuild = "" }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows public void FileVersionInfo_Chinese() { // NativeLibrary.dll (Chinese) VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), NativeLibraryFileName), new MyFVI() { Comments = "", CompanyName = "A non-existent company", FileBuildPart = 3, FileDescription = "Here is the description of the native library.", FileMajorPart = 9, FileMinorPart = 9, FileName = Path.Combine(Directory.GetCurrentDirectory(), NativeLibraryFileName), FilePrivatePart = 3, FileVersion = "9.9.3.3", InternalName = "NativeLi.dll", IsDebug = false, IsPatched = true, IsPrivateBuild = false, IsPreRelease = true, IsSpecialBuild = false, Language = GetFileVersionLanguage(0x0004),//Chinese (Simplified) Language2 = GetFileVersionLanguage(0x0804),//Chinese (Simplified, PRC) - changed, but not yet on all platforms LegalCopyright = "None", LegalTrademarks = "", OriginalFilename = "NativeLi.dll", PrivateBuild = "", ProductBuildPart = 40, ProductMajorPart = 20, ProductMinorPart = 30, ProductName = "I was never given a name.", ProductPrivatePart = 50, ProductVersion = "20.30.40.50", SpecialBuild = "", }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows public void FileVersionInfo_DifferentFileVersionAndProductVersion() { // Mtxex.dll VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), SecondNativeLibraryFileName), new MyFVI() { Comments = "", CompanyName = "", FileBuildPart = 0, FileDescription = "", FileMajorPart = 0, FileMinorPart = 65535, FileName = Path.Combine(Directory.GetCurrentDirectory(), SecondNativeLibraryFileName), FilePrivatePart = 2, FileVersion = "0.65535.0.2", InternalName = "SecondNa.dll", IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = GetFileVersionLanguage(0x0400),//Process Default Language LegalCopyright = "Copyright (C) 1 - 2014", LegalTrademarks = "", OriginalFilename = "SecondNa.dll", PrivateBuild = "", ProductBuildPart = 0, ProductMajorPart = 1, ProductMinorPart = 0, ProductName = "Unkown_Product_Name", ProductPrivatePart = 1, ProductVersion = "1.0.0.1", SpecialBuild = "", }); } [Fact] public void FileVersionInfo_CustomManagedAssembly() { // Assembly1.dll VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), new MyFVI() { Comments = "Have you played a Contoso amusement device today?", CompanyName = "The name of the company.", FileBuildPart = 2, FileDescription = "My File", FileMajorPart = 4, FileMinorPart = 3, FileName = Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), FilePrivatePart = 1, FileVersion = "4.3.2.1", InternalName = TestAssemblyFileName, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = Interop.IsWindows ? GetFileVersionLanguage(0x0000) : "Language Neutral", //Language Neutral LegalCopyright = "Copyright, you betcha!", LegalTrademarks = "TM", OriginalFilename = TestAssemblyFileName, PrivateBuild = "", ProductBuildPart = 2, ProductMajorPart = 4, ProductMinorPart = 3, ProductName = "The greatest product EVER", ProductPrivatePart = 1, ProductVersion = "4.3.2.1", SpecialBuild = "", }); } [Fact] public void FileVersionInfo_EmptyFVI() { // Assembly1.cs VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), new MyFVI() { Comments = null, CompanyName = null, FileBuildPart = 0, FileDescription = null, FileMajorPart = 0, FileMinorPart = 0, FileName = Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), FilePrivatePart = 0, FileVersion = null, InternalName = null, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = null, LegalCopyright = null, LegalTrademarks = null, OriginalFilename = null, PrivateBuild = null, ProductBuildPart = 0, ProductMajorPart = 0, ProductMinorPart = 0, ProductName = null, ProductPrivatePart = 0, ProductVersion = null, SpecialBuild = null, }); } [Fact] public void FileVersionInfo_FileNotFound() { Assert.Throws<FileNotFoundException>(() => FileVersionInfo.GetVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestNotFoundFileName))); } // Additional Tests Wanted: // [] File exists but we don't have permission to read it // [] DLL has unknown codepage info // [] DLL language/codepage is 8-hex-digits (locale > 0x999) (different codepath) private void VerifyVersionInfo(String filePath, MyFVI expected) { FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(filePath); TestStringProperty("Comments", fvi.Comments, expected.Comments); TestStringProperty("CompanyName", fvi.CompanyName, expected.CompanyName); TestProperty<int>("FileBuildPart", fvi.FileBuildPart, expected.FileBuildPart); TestStringProperty("FileDescription", fvi.FileDescription, expected.FileDescription); TestProperty<int>("FileMajorPart", fvi.FileMajorPart, expected.FileMajorPart); TestProperty<int>("FileMinorPart", fvi.FileMinorPart, expected.FileMinorPart); TestStringProperty("FileName", fvi.FileName, expected.FileName); TestProperty<int>("FilePrivatePart", fvi.FilePrivatePart, expected.FilePrivatePart); TestStringProperty("FileVersion", fvi.FileVersion, expected.FileVersion); TestStringProperty("InternalName", fvi.InternalName, expected.InternalName); TestProperty<bool>("IsDebug", fvi.IsDebug, expected.IsDebug); TestProperty<bool>("IsPatched", fvi.IsPatched, expected.IsPatched); TestProperty<bool>("IsPrivateBuild", fvi.IsPrivateBuild, expected.IsPrivateBuild); TestProperty<bool>("IsPreRelease", fvi.IsPreRelease, expected.IsPreRelease); TestProperty<bool>("IsSpecialBuild", fvi.IsSpecialBuild, expected.IsSpecialBuild); TestStringProperty("Language", fvi.Language, expected.Language, expected.Language2, false); TestStringProperty("LegalCopyright", fvi.LegalCopyright, expected.LegalCopyright, false); TestStringProperty("LegalTrademarks", fvi.LegalTrademarks, expected.LegalTrademarks); TestStringProperty("OriginalFilename", fvi.OriginalFilename, expected.OriginalFilename); TestStringProperty("PrivateBuild", fvi.PrivateBuild, expected.PrivateBuild); TestProperty<int>("ProductBuildPart", fvi.ProductBuildPart, expected.ProductBuildPart); TestProperty<int>("ProductMajorPart", fvi.ProductMajorPart, expected.ProductMajorPart); TestProperty<int>("ProductMinorPart", fvi.ProductMinorPart, expected.ProductMinorPart); TestStringProperty("ProductName", fvi.ProductName, expected.ProductName, false); TestProperty<int>("ProductPrivatePart", fvi.ProductPrivatePart, expected.ProductPrivatePart); TestStringProperty("ProductVersion", fvi.ProductVersion, expected.ProductVersion, false); TestStringProperty("SpecialBuild", fvi.SpecialBuild, expected.SpecialBuild); //ToString String nl = Environment.NewLine; TestStringProperty("ToString()", fvi.ToString(), "File: " + fvi.FileName + nl + "InternalName: " + fvi.InternalName + nl + "OriginalFilename: " + fvi.OriginalFilename + nl + "FileVersion: " + fvi.FileVersion + nl + "FileDescription: " + fvi.FileDescription + nl + "Product: " + fvi.ProductName + nl + "ProductVersion: " + fvi.ProductVersion + nl + "Debug: " + fvi.IsDebug.ToString() + nl + "Patched: " + fvi.IsPatched.ToString() + nl + "PreRelease: " + fvi.IsPreRelease.ToString() + nl + "PrivateBuild: " + fvi.IsPrivateBuild.ToString() + nl + "SpecialBuild: " + fvi.IsSpecialBuild.ToString() + nl + "Language: " + fvi.Language + nl, false); } private void TestStringProperty(String propertyName, String actual, String expected) { TestStringProperty(propertyName, actual, expected, true); } private void TestStringProperty(String propertyName, String actual, String expected, bool testOnNonEnglishPlatform) { TestStringProperty(propertyName, actual, expected, null, true); } private void TestStringProperty(String propertyName, String actual, String expected, String alternate, bool testOnNonEnglishPlatform) { if (testOnNonEnglishPlatform || CultureInfo.CurrentCulture.Name == "en-US") { if ((actual == null && expected != null) || (actual != null && !actual.Equals(expected) && !actual.Equals(alternate))) { Assert.True(false, string.Format("Error - Property '{0}' incorrect. Expected == {1}, Actual == {2}, Alternate == {3}", propertyName, GetUnicodeString(expected), GetUnicodeString(actual), GetUnicodeString(alternate))); } } } private void TestProperty<T>(String propertyName, T actual, T expected) { Assert.Equal(expected, actual); } internal class MyFVI { public string Comments; public string CompanyName; public int FileBuildPart; public string FileDescription; public int FileMajorPart; public int FileMinorPart; public string FileName; public int FilePrivatePart; public string FileVersion; public string InternalName; public bool IsDebug; public bool IsPatched; public bool IsPrivateBuild; public bool IsPreRelease; public bool IsSpecialBuild; public string Language; public string Language2; public string LegalCopyright; public string LegalTrademarks; public string OriginalFilename; public string PrivateBuild; public int ProductBuildPart; public int ProductMajorPart; public int ProductMinorPart; public string ProductName; public int ProductPrivatePart; public string ProductVersion; public string SpecialBuild; } static string GetUnicodeString(String str) { if (str == null) return "<null>"; StringBuilder buffer = new StringBuilder(); buffer.Append("\""); for (int i = 0; i < str.Length; i++) { char ch = str[i]; if (ch == '\r') { buffer.Append("\\r"); } else if (ch == '\n') { buffer.Append("\\n"); } else if (ch == '\\') { buffer.Append("\\"); } else if (ch == '\"') { buffer.Append("\\\""); } else if (ch == '\'') { buffer.Append("\\\'"); } else if (ch < 0x20 || ch >= 0x7f) { buffer.Append("\\u"); buffer.Append(((int)ch).ToString("x4")); } else { buffer.Append(ch); } } buffer.Append("\""); return (buffer.ToString()); } private static string GetFileVersionLanguage(uint langid) { var lang = new StringBuilder(256); Interop.mincore.VerLanguageName(langid, lang, (uint)lang.Capacity); return lang.ToString(); } }
using System; using System.Windows.Forms; namespace VaultAtlas.DataModel.ModelUI { /// <summary> /// Summary description for ProgressWindow. /// </summary> public class ProgressWindow : System.Windows.Forms.Form, IProgressCallback { private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Label label; private System.Windows.Forms.ProgressBar progressBar; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private String titleRoot = ""; private readonly System.Threading.ManualResetEvent _initEvent = new System.Threading.ManualResetEvent(false); private readonly System.Threading.ManualResetEvent _abortEvent = new System.Threading.ManualResetEvent(false); private bool _requiresClose = true; public ProgressWindow() { // // Required for Windows Form Designer support // InitializeComponent(); } public bool ProgressVisible { get { return this.progressBar.Visible; } set { this.progressBar.Visible = value; } } #region Implementation of IProgressCallback /// <summary> /// Call this method from the worker thread to initialize /// the progress meter. /// </summary> /// <param name="minimum">The minimum value in the progress range (e.g. 0)</param> /// <param name="maximum">The maximum value in the progress range (e.g. 100)</param> public void Begin( int minimum, int maximum ) { _initEvent.WaitOne(); Invoke(new Action(() => { cancelButton.Enabled = true; ControlBox = true; progressBar.Minimum = minimum; progressBar.Maximum = maximum; progressBar.Value = minimum; titleRoot = Text; })); } /// <summary> /// Call this method from the worker thread to initialize /// the progress callback, without setting the range /// </summary> public void Begin() { _initEvent.WaitOne(); Invoke(new Action(() => { cancelButton.Enabled = true; ControlBox = true; })); } /// <summary> /// Call this method from the worker thread to reset the range in the progress callback /// </summary> /// <param name="minimum">The minimum value in the progress range (e.g. 0)</param> /// <param name="maximum">The maximum value in the progress range (e.g. 100)</param> /// <remarks>You must have called one of the Begin() methods prior to this call.</remarks> public void SetRange( int minimum, int maximum ) { _initEvent.WaitOne(); Invoke(new Action(() => { progressBar.Minimum = minimum; progressBar.Maximum = maximum; progressBar.Value = minimum; titleRoot = Text; })); } /// <summary> /// Call this method from the worker thread to update the progress text. /// </summary> /// <param name="text">The progress text to display</param> public void SetText( String text ) { Invoke(new Action(() => { label.Text = text; })); } /// <summary> /// Call this method from the worker thread to increase the progress counter by a specified value. /// </summary> /// <param name="val">The amount by which to increment the progress indicator</param> public void Increment( int val ) { Invoke(new Action(() => { progressBar.Increment(val); UpdateStatusText(); })); } /// <summary> /// Call this method from the worker thread to step the progress meter to a particular value. /// </summary> /// <param name="val"></param> public void StepTo( int val ) { Invoke(new Action(() => { progressBar.Value = val; UpdateStatusText(); })); } /// <summary> /// If this property is true, then you should abort work /// </summary> public bool IsAborting { get { return _abortEvent.WaitOne( 0, false ); } } /// <summary> /// Call this method from the worker thread to finalize the progress meter /// </summary> public void End() { try { if (_requiresClose) { Invoke(new MethodInvoker(DoEnd)); } } catch { } } #endregion private void DoEnd() { this.Close(); } #region Overrides /// <summary> /// Handles the form load, and sets an event to ensure that /// intialization is synchronized with the appearance of the form. /// </summary> /// <param name="e"></param> protected override void OnLoad(System.EventArgs e) { base.OnLoad( e ); ControlBox = false; _initEvent.Set(); } /// <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> /// Handler for 'Close' clicking /// </summary> /// <param name="e"></param> protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { _requiresClose = false; AbortWork(); base.OnClosing( e ); } #endregion #region Implementation Utilities /// <summary> /// Utility function that formats and updates the title bar text /// </summary> private void UpdateStatusText() { Text = titleRoot + String.Format( " - {0}% complete", (progressBar.Value * 100 ) / (progressBar.Maximum - progressBar.Minimum) ); } /// <summary> /// Utility function to terminate the thread /// </summary> private void AbortWork() { _abortEvent.Set(); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.progressBar = new System.Windows.Forms.ProgressBar(); this.label = new System.Windows.Forms.Label(); this.cancelButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // progressBar // this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar.Location = new System.Drawing.Point(8, 80); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(192, 23); this.progressBar.TabIndex = 1; // // label // this.label.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label.Location = new System.Drawing.Point(8, 8); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(272, 64); this.label.TabIndex = 0; this.label.Text = "Starting operation..."; // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Enabled = false; this.cancelButton.Location = new System.Drawing.Point(208, 80); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // ProgressWindow // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(290, 114); this.ControlBox = false; this.Controls.Add(this.cancelButton); this.Controls.Add(this.progressBar); this.Controls.Add(this.label); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.Name = "ProgressWindow"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Operation in progress ..."; this.ResumeLayout(false); } #endregion private void cancelButton_Click(object sender, EventArgs e) { AbortWork(); } } }
/* * 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.Xml; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using System.Threading; using log4net; namespace OpenSim.Framework.Console { public delegate void CommandDelegate(string module, string[] cmd); public class Commands { /// <summary> /// Encapsulates a command that can be invoked from the console /// </summary> private class CommandInfo { /// <value> /// The module from which this command comes /// </value> public string module; /// <value> /// Whether the module is shared /// </value> public bool shared; /// <value> /// Very short BNF description /// </value> public string help_text; /// <value> /// Longer one line help text /// </value> public string long_help; /// <value> /// Full descriptive help for this command /// </value> public string descriptive_help; /// <value> /// The method to invoke for this command /// </value> public List<CommandDelegate> fn; } /// <value> /// Commands organized by keyword in a tree /// </value> private Dictionary<string, object> tree = new Dictionary<string, object>(); /// <summary> /// Get help for the given help string /// </summary> /// <param name="helpParts">Parsed parts of the help string. If empty then general help is returned.</param> /// <returns></returns> public List<string> GetHelp(string[] cmd) { List<string> help = new List<string>(); List<string> helpParts = new List<string>(cmd); // Remove initial help keyword helpParts.RemoveAt(0); // General help if (helpParts.Count == 0) { help.AddRange(CollectHelp(tree)); help.Sort(); } else { help.AddRange(CollectHelp(helpParts)); } return help; } /// <summary> /// See if we can find the requested command in order to display longer help /// </summary> /// <param name="helpParts"></param> /// <returns></returns> private List<string> CollectHelp(List<string> helpParts) { string originalHelpRequest = string.Join(" ", helpParts.ToArray()); List<string> help = new List<string>(); Dictionary<string, object> dict = tree; while (helpParts.Count > 0) { string helpPart = helpParts[0]; if (!dict.ContainsKey(helpPart)) break; //m_log.Debug("Found {0}", helpParts[0]); if (dict[helpPart] is Dictionary<string, Object>) dict = (Dictionary<string, object>)dict[helpPart]; helpParts.RemoveAt(0); } // There was a command for the given help string if (dict.ContainsKey(String.Empty)) { CommandInfo commandInfo = (CommandInfo)dict[String.Empty]; help.Add(commandInfo.help_text); help.Add(commandInfo.long_help); help.Add(commandInfo.descriptive_help); } else { help.Add(string.Format("No help is available for {0}", originalHelpRequest)); } return help; } private List<string> CollectHelp(Dictionary<string, object> dict) { List<string> result = new List<string>(); foreach (KeyValuePair<string, object> kvp in dict) { if (kvp.Value is Dictionary<string, Object>) { result.AddRange(CollectHelp((Dictionary<string, Object>)kvp.Value)); } else { if (((CommandInfo)kvp.Value).long_help != String.Empty) result.Add(((CommandInfo)kvp.Value).help_text+" - "+ ((CommandInfo)kvp.Value).long_help); } } return result; } /// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="module"></param> /// <param name="command"></param> /// <param name="help"></param> /// <param name="longhelp"></param> /// <param name="fn"></param> public void AddCommand(string module, bool shared, string command, string help, string longhelp, CommandDelegate fn) { AddCommand(module, shared, command, help, longhelp, String.Empty, fn); } /// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="module"></param> /// <param name="command"></param> /// <param name="help"></param> /// <param name="longhelp"></param> /// <param name="descriptivehelp"></param> /// <param name="fn"></param> public void AddCommand(string module, bool shared, string command, string help, string longhelp, string descriptivehelp, CommandDelegate fn) { string[] parts = Parser.Parse(command); Dictionary<string, Object> current = tree; foreach (string s in parts) { if (current.ContainsKey(s)) { if (current[s] is Dictionary<string, Object>) { current = (Dictionary<string, Object>)current[s]; } else return; } else { current[s] = new Dictionary<string, Object>(); current = (Dictionary<string, Object>)current[s]; } } CommandInfo info; if (current.ContainsKey(String.Empty)) { info = (CommandInfo)current[String.Empty]; if (!info.shared && !info.fn.Contains(fn)) info.fn.Add(fn); return; } info = new CommandInfo(); info.module = module; info.shared = shared; info.help_text = help; info.long_help = longhelp; info.descriptive_help = descriptivehelp; info.fn = new List<CommandDelegate>(); info.fn.Add(fn); current[String.Empty] = info; } public string[] FindNextOption(string[] cmd, bool term) { Dictionary<string, object> current = tree; int remaining = cmd.Length; foreach (string s in cmd) { remaining--; List<string> found = new List<string>(); foreach (string opt in current.Keys) { if (remaining > 0 && opt == s) { found.Clear(); found.Add(opt); break; } if (opt.StartsWith(s)) { found.Add(opt); } } if (found.Count == 1 && (remaining != 0 || term)) { current = (Dictionary<string, object>)current[found[0]]; } else if (found.Count > 0) { return found.ToArray(); } else { break; // return new string[] {"<cr>"}; } } if (current.Count > 1) { List<string> choices = new List<string>(); bool addcr = false; foreach (string s in current.Keys) { if (s == String.Empty) { CommandInfo ci = (CommandInfo)current[String.Empty]; if (ci.fn.Count != 0) addcr = true; } else choices.Add(s); } if (addcr) choices.Add("<cr>"); return choices.ToArray(); } if (current.ContainsKey(String.Empty)) return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text}; return new string[] { new List<string>(current.Keys)[0] }; } public string[] Resolve(string[] cmd) { string[] result = cmd; int index = -1; Dictionary<string, object> current = tree; foreach (string s in cmd) { index++; List<string> found = new List<string>(); foreach (string opt in current.Keys) { if (opt == s) { found.Clear(); found.Add(opt); break; } if (opt.StartsWith(s)) { found.Add(opt); } } if (found.Count == 1) { result[index] = found[0]; current = (Dictionary<string, object>)current[found[0]]; } else if (found.Count > 0) { return new string[0]; } else { break; } } if (current.ContainsKey(String.Empty)) { CommandInfo ci = (CommandInfo)current[String.Empty]; if (ci.fn.Count == 0) return new string[0]; foreach (CommandDelegate fn in ci.fn) { if (fn != null) fn(ci.module, result); else return new string[0]; } return result; } return new string[0]; } public XmlElement GetXml(XmlDocument doc) { CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty]; ((Dictionary<string, object>)tree["help"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["help"]).Count == 0) tree.Remove("help"); CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty]; ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["quit"]).Count == 0) tree.Remove("quit"); XmlElement root = doc.CreateElement("", "HelpTree", ""); ProcessTreeLevel(tree, root, doc); if (!tree.ContainsKey("help")) tree["help"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["help"])[String.Empty] = help; if (!tree.ContainsKey("quit")) tree["quit"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit; return root; } private void ProcessTreeLevel(Dictionary<string, object> level, XmlElement xml, XmlDocument doc) { foreach (KeyValuePair<string, object> kvp in level) { if (kvp.Value is Dictionary<string, Object>) { XmlElement next = doc.CreateElement("", "Level", ""); next.SetAttribute("Name", kvp.Key); xml.AppendChild(next); ProcessTreeLevel((Dictionary<string, object>)kvp.Value, next, doc); } else { CommandInfo c = (CommandInfo)kvp.Value; XmlElement cmd = doc.CreateElement("", "Command", ""); XmlElement e; e = doc.CreateElement("", "Module", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.module)); e = doc.CreateElement("", "Shared", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.shared.ToString())); e = doc.CreateElement("", "HelpText", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.help_text)); e = doc.CreateElement("", "LongHelp", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.long_help)); e = doc.CreateElement("", "Description", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.descriptive_help)); xml.AppendChild(cmd); } } } public void FromXml(XmlElement root, CommandDelegate fn) { CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty]; ((Dictionary<string, object>)tree["help"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["help"]).Count == 0) tree.Remove("help"); CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty]; ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["quit"]).Count == 0) tree.Remove("quit"); tree.Clear(); ReadTreeLevel(tree, root, fn); if (!tree.ContainsKey("help")) tree["help"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["help"])[String.Empty] = help; if (!tree.ContainsKey("quit")) tree["quit"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit; } private void ReadTreeLevel(Dictionary<string, object> level, XmlNode node, CommandDelegate fn) { Dictionary<string, object> next; string name; XmlNodeList nodeL = node.ChildNodes; XmlNodeList cmdL; CommandInfo c; foreach (XmlNode part in nodeL) { switch (part.Name) { case "Level": name = ((XmlElement)part).GetAttribute("Name"); next = new Dictionary<string, object>(); level[name] = next; ReadTreeLevel(next, part, fn); break; case "Command": cmdL = part.ChildNodes; c = new CommandInfo(); foreach (XmlNode cmdPart in cmdL) { switch (cmdPart.Name) { case "Module": c.module = cmdPart.InnerText; break; case "Shared": c.shared = Convert.ToBoolean(cmdPart.InnerText); break; case "HelpText": c.help_text = cmdPart.InnerText; break; case "LongHelp": c.long_help = cmdPart.InnerText; break; case "Description": c.descriptive_help = cmdPart.InnerText; break; } } c.fn = new List<CommandDelegate>(); c.fn.Add(fn); level[String.Empty] = c; break; } } } } public class Parser { public static string[] Parse(string text) { List<string> result = new List<string>(); int index; string[] unquoted = text.Split(new char[] {'"'}); for (index = 0 ; index < unquoted.Length ; index++) { if (index % 2 == 0) { string[] words = unquoted[index].Split(new char[] {' '}); foreach (string w in words) { if (w != String.Empty) result.Add(w); } } else { result.Add(unquoted[index]); } } return result.ToArray(); } } /// <summary> /// A console that processes commands internally /// </summary> public class CommandConsole : ConsoleBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public Commands Commands = new Commands(); public CommandConsole(string defaultPrompt) : base(defaultPrompt) { Commands.AddCommand("console", false, "help", "help [<command>]", "Get general command list or more detailed help on a specific command", Help); } private void Help(string module, string[] cmd) { List<string> help = Commands.GetHelp(cmd); foreach (string s in help) Output(s); } /// <summary> /// Display a command prompt on the console and wait for user input /// </summary> public void Prompt() { string line = ReadLine(m_defaultPrompt + "# ", true, true); if (line != String.Empty) { m_log.Info("[CONSOLE] Invalid command"); } } public void RunCommand(string cmd) { string[] parts = Parser.Parse(cmd); Commands.Resolve(parts); } public override string ReadLine(string p, bool isCommand, bool e) { System.Console.Write("{0}", p); string cmdinput = System.Console.ReadLine(); if (isCommand) { string[] cmd = Commands.Resolve(Parser.Parse(cmdinput)); if (cmd.Length != 0) { int i; for (i=0 ; i < cmd.Length ; i++) { if (cmd[i].Contains(" ")) cmd[i] = "\"" + cmd[i] + "\""; } return String.Empty; } } return cmdinput; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; namespace OpenSim.Region.ScriptEngine.Shared.Instance { public class ScriptInstance : MarshalByRefObject, IScriptInstance { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The current work item if an event for this script is running or waiting to run, /// </summary> /// <remarks> /// Null if there is no running or waiting to run event. Must be changed only under an EventQueue lock. /// </remarks> private IScriptWorkItem m_CurrentWorkItem; private IScript m_Script; private DetectParams[] m_DetectParams; private bool m_TimerQueued; private DateTime m_EventStart; private bool m_InEvent; private string m_Assembly; private string m_CurrentEvent = String.Empty; private bool m_InSelfDelete; private int m_MaxScriptQueue; private bool m_SaveState = true; private int m_ControlEventsInQueue; private int m_LastControlLevel; private bool m_CollisionInQueue; // The following is for setting a minimum delay between events private double m_minEventDelay; private long m_eventDelayTicks; private long m_nextEventTimeTicks; private bool m_startOnInit = true; private UUID m_AttachedAvatar; private StateSource m_stateSource; private bool m_postOnRez; private bool m_startedFromSavedState; private UUID m_CurrentStateHash; private UUID m_RegionID; public int DebugLevel { get; set; } public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap { get; set; } private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>(); public Object[] PluginData = new Object[0]; /// <summary> /// Used by llMinEventDelay to suppress events happening any faster than this speed. /// This currently restricts all events in one go. Not sure if each event type has /// its own check so take the simple route first. /// </summary> public double MinEventDelay { get { return m_minEventDelay; } set { if (value > 0.001) m_minEventDelay = value; else m_minEventDelay = 0.0; m_eventDelayTicks = (long)(m_minEventDelay * 10000000L); m_nextEventTimeTicks = DateTime.Now.Ticks; } } public bool Running { get; set; } public bool Suspended { get { return m_Suspended; } set { bool reEnqueueScript = false; // Need to do this inside a lock in order to avoid races with EventProcessor() lock (m_Script) { bool wasSuspended = m_Suspended; m_Suspended = value; if (wasSuspended && !m_Suspended) { reEnqueueScript = true; } } if (reEnqueueScript) { lock (EventQueue) { // Need to place ourselves back in a work item if there are events to process if (EventQueue.Count > 0 && Running && !ShuttingDown) m_CurrentWorkItem = Engine.QueueEventHandler(this); } } } } private bool m_Suspended; public bool ShuttingDown { get; set; } public string State { get; set; } public IScriptEngine Engine { get; private set; } public UUID AppDomain { get; set; } public SceneObjectPart Part { get; private set; } public string PrimName { get; private set; } public string ScriptName { get; private set; } public UUID ItemID { get; private set; } public UUID ObjectID { get { return Part.UUID; } } public uint LocalID { get { return Part.LocalId; } } public UUID RootObjectID { get { return Part.ParentGroup.UUID; } } public uint RootLocalID { get { return Part.ParentGroup.LocalId; } } public UUID AssetID { get; private set; } private Queue EventQueue; public void EnqueueEvent(object o) { lock (EventQueue) EventQueue.Enqueue(o); } public object DequeueEvent() { lock (EventQueue) return EventQueue.Dequeue(); } public long EventsQueued { get { lock (EventQueue) return EventQueue.Count; } } public long EventsProcessed { get; private set; } public int StartParam { get; set; } public TaskInventoryItem ScriptTask { get; private set; } public DateTime TimeStarted { get; private set; } public int MeasurementPeriodTickStart { get; private set; } public int MeasurementPeriodExecutionTime { get; private set; } public static readonly int MaxMeasurementPeriod = 30 * 60000; /* this is ms unit, anyone telling otherwise is just blind */ private EventWaitHandle m_coopSleepHandle; public void ClearQueue() { m_TimerQueued = false; EventQueue.Clear(); } public ScriptInstance( IScriptEngine engine, SceneObjectPart part, TaskInventoryItem item, int startParam, bool postOnRez, int maxScriptQueue) { State = "default"; EventQueue = new Queue(32); Engine = engine; Part = part; ScriptTask = item; // This is currently only here to allow regression tests to get away without specifying any inventory // item when they are testing script logic that doesn't require an item. if (ScriptTask != null) { ScriptName = ScriptTask.Name; ItemID = ScriptTask.ItemID; AssetID = ScriptTask.AssetID; } PrimName = part.ParentGroup.Name; StartParam = startParam; m_MaxScriptQueue = maxScriptQueue; m_postOnRez = postOnRez; m_AttachedAvatar = Part.ParentGroup.AttachedAvatar; m_RegionID = Part.ParentGroup.Scene.RegionInfo.RegionID; m_coopSleepHandle = new XEngineEventWaitHandle(false, EventResetMode.AutoReset); } /// <summary> /// Load the script from an assembly into an AppDomain. /// </summary> /// <param name='dom'></param> /// <param name='assembly'></param> /// <param name='stateSource'></param> /// <returns>false if load failed, true if suceeded</returns> public bool Load(AppDomain dom, string assembly, StateSource stateSource) { m_Assembly = assembly; m_stateSource = stateSource; ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle); } try { object[] constructorParams; Assembly scriptAssembly = dom.Load(Path.GetFileNameWithoutExtension(assembly)); Type scriptType = scriptAssembly.GetType("SecondLife.XEngineScript"); if (scriptType != null) { constructorParams = new object[] { m_coopSleepHandle }; } else { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. You must remove all existing {6}* script DLL files before using enabling co-op termination" + ", either by setting DeleteScriptsOnStartup = true in [XEngine] for one run" + " or by deleting these files manually.", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly); return false; } // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Looking to load {0} from assembly {1} in {2}", // scriptType.FullName, Path.GetFileNameWithoutExtension(assembly), Engine.World.Name); if (dom != System.AppDomain.CurrentDomain) m_Script = (IScript)dom.CreateInstanceAndUnwrap( Path.GetFileNameWithoutExtension(assembly), scriptType.FullName, false, BindingFlags.Default, null, constructorParams, null, null); else m_Script = (IScript)scriptAssembly.CreateInstance( scriptType.FullName, false, BindingFlags.Default, null, constructorParams, null, null); //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); // lease.Register(this); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error loading assembly {6}. Exception {7}{8}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly, e.Message, e.StackTrace); return false; } try { foreach (KeyValuePair<string,IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // // m_log.Debug("[Script] Script instance created"); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error initializing script instance. Exception {6}{7}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace); return false; } m_SaveState = true; string savedState = Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"); if (File.Exists(savedState)) { string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size = (int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = Encoding.UTF8.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(Engine, LocalID, ItemID, ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (!Running) m_startOnInit = false; Running = false; // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } } else { m_log.WarnFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. Memory limit exceeded.", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState); } } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. XML is {7}. Exception {8}{9}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace); } } // else // { // ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID); // if (presence != null && (!postOnRez)) // presence.ControllingClient.SendAgentAlertMessage("Compile successful", false); // } return true; } public void Init() { if (ShuttingDown) return; if (m_startedFromSavedState) { if (m_startOnInit) Start(); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } else if (m_stateSource == StateSource.RegionStart) { //m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script"); PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0])); } else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting) { // CHANGED_REGION PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0])); // CHANGED_TELEPORT if (m_stateSource == StateSource.Teleporting) PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0])); } } else { if (m_startOnInit) Start(); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } } } private void ReleaseControls() { int permsMask; UUID permsGranter; TaskInventoryItem item; if (!Part.TaskInventory.TryGetValue(ItemID, out item)) return; lock (item) { permsGranter = item.PermsGranter; permsMask = item.PermsMask; } if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0) { ScenePresence presence = Engine.World.GetScenePresence(permsGranter); if (presence != null) presence.UnRegisterControlEventsToScript(LocalID, ItemID); } } public void DestroyScriptInstance() { ReleaseControls(); AsyncCommandManager.UnregisterScriptFacilities(Engine, LocalID, ItemID, true); } public void RemoveState() { string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly), ItemID.ToString() + ".state"); try { File.Delete(savedState); } catch (Exception e) { m_log.Warn( string.Format( "[SCRIPT INSTANCE]: Could not delete script state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}. Exception ", savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name), e); } } public void VarDump(Dictionary<string, object> vars) { // m_log.Info("Variable dump for script "+ ItemID.ToString()); // foreach (KeyValuePair<string, object> v in vars) // { // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString()); // } } public void Start() { lock (EventQueue) { if (Running) return; Running = true; TimeStarted = DateTime.Now; MeasurementPeriodTickStart = Environment.TickCount; MeasurementPeriodExecutionTime = 0; if (EventQueue.Count > 0) { if (m_CurrentWorkItem == null) m_CurrentWorkItem = Engine.QueueEventHandler(this); // else // m_log.Error("[Script] Tried to start a script that was already queued"); } } } public bool Stop(int timeout) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Stopping script {0} {1} in {2} {3} with timeout {4} {5} {6}", ScriptName, ItemID, PrimName, ObjectID, timeout, m_InSelfDelete, DateTime.Now.Ticks); IScriptWorkItem workItem; lock (EventQueue) { if (!Running) return true; // If we're not running or waiting to run an event then we can safely stop. if (m_CurrentWorkItem == null) { Running = false; return true; } // If we are waiting to run an event then we can try to cancel it. if (m_CurrentWorkItem.Cancel()) { m_CurrentWorkItem = null; Running = false; return true; } workItem = m_CurrentWorkItem; Running = false; } // Wait for the current event to complete. if (!m_InSelfDelete) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Co-operatively stopping script {0} {1} in {2} {3}", ScriptName, ItemID, PrimName, ObjectID); // This will terminate the event on next handle check by the script. m_coopSleepHandle.Set(); // For now, we will wait forever since the event should always cleanly terminate once LSL loop // checking is implemented. May want to allow a shorter timeout option later. if (workItem.Wait(Timeout.Infinite)) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Co-operatively stopped script {0} {1} in {2} {3}", ScriptName, ItemID, PrimName, ObjectID); return true; } } lock (EventQueue) { workItem = m_CurrentWorkItem; } if (workItem == null) return true; // If the event still hasn't stopped and we the stop isn't the result of script or object removal, then // forcibly abort the work item (this aborts the underlying thread). // Co-operative termination should never reach this point. if (!m_InSelfDelete) { m_log.DebugFormat( "[SCRIPT INSTANCE]: Aborting unstopped script {0} {1} in prim {2}, localID {3}, timeout was {4} ms", ScriptName, ItemID, PrimName, LocalID, timeout); workItem.Abort(); } lock (EventQueue) { m_CurrentWorkItem = null; } return true; } public void SetState(string state) { if (state == State) return; PostEvent(new EventParams("state_exit", new Object[0], new DetectParams[0])); PostEvent(new EventParams("state", new Object[] { state }, new DetectParams[0])); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } /// <summary> /// Post an event to this script instance. /// </summary> /// <remarks> /// The request to run the event is sent /// </remarks> /// <param name="data"></param> public void PostEvent(EventParams data) { // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); if (!Running) return; // If min event delay is set then ignore any events untill the time has expired // This currently only allows 1 event of any type in the given time period. // This may need extending to allow for a time for each individual event type. if (m_eventDelayTicks != 0) { if (DateTime.Now.Ticks < m_nextEventTimeTicks) return; m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks; } lock (EventQueue) { if (EventQueue.Count >= m_MaxScriptQueue) return; if (data.EventName == "timer") { if (m_TimerQueued) return; m_TimerQueued = true; } if (data.EventName == "control") { int held = ((LSL_Types.LSLInteger)data.Params[1]).value; // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value; // If the last message was a 0 (nothing held) // and this one is also nothing held, drop it // if (m_LastControlLevel == held && held == 0) return; // If there is one or more queued, then queue // only changed ones, else queue unconditionally // if (m_ControlEventsInQueue > 0) { if (m_LastControlLevel == held) return; } m_LastControlLevel = held; m_ControlEventsInQueue++; } if (data.EventName == "collision") { if (m_CollisionInQueue) return; if (data.DetectParams == null) return; m_CollisionInQueue = true; } EventQueue.Enqueue(data); if (m_CurrentWorkItem == null) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } } } /// <summary> /// Process the next event queued for this script /// </summary> /// <returns></returns> public object EventProcessor() { // We check here as the thread stopping this instance from running may itself hold the m_Script lock. if (!Running) return 0; lock (m_Script) { // m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName); if (Suspended) return 0; EventParams data = null; lock (EventQueue) { data = (EventParams)EventQueue.Dequeue(); if (data == null) // Shouldn't happen { if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } return 0; } if (data.EventName == "timer") m_TimerQueued = false; if (data.EventName == "control") { if (m_ControlEventsInQueue > 0) m_ControlEventsInQueue--; } if (data.EventName == "collision") m_CollisionInQueue = false; } if (DebugLevel >= 2) m_log.DebugFormat( "[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}", data.EventName, ScriptName, Part.Name, Part.LocalId, Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name); m_DetectParams = data.DetectParams; if (data.EventName == "state") // Hardcoded state change { State = data.Params[0].ToString(); if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}", State, ScriptName, Part.Name, Part.LocalId, Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name); AsyncCommandManager.UnregisterScriptFacilities(Engine, LocalID, ItemID, false); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } else { if (Engine.World.PipeEventsForScript(LocalID) || data.EventName == "control") // Don't freeze avies! { // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); try { m_CurrentEvent = data.EventName; m_EventStart = DateTime.Now; m_InEvent = true; int start = Environment.TickCount; // Reset the measurement period when we reach the end of the current one. if (start - MeasurementPeriodTickStart > MaxMeasurementPeriod) MeasurementPeriodTickStart = start; m_Script.ExecuteEvent(State, data.EventName, data.Params); MeasurementPeriodExecutionTime += Environment.TickCount - start; m_InEvent = false; m_CurrentEvent = String.Empty; if (m_SaveState) { // This will be the very first event we deliver // (state_entry) in default state // SaveState(m_Assembly); m_SaveState = false; } } catch (Exception e) { // m_log.DebugFormat( // "[SCRIPT] Exception in script {0} {1}: {2}{3}", // ScriptName, ItemID, e.Message, e.StackTrace); m_InEvent = false; m_CurrentEvent = String.Empty; if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException) && !(e.InnerException is ScriptCoopStopException))) && !(e is ThreadAbortException)) { try { // DISPLAY ERROR INWORLD string text = FormatException(e); text = "At region id " + m_RegionID + ":\n" + text; if (text.Length > 1000) text = text.Substring(0, 1000); Engine.World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, Part.AbsolutePosition, Part.Name, Part.UUID, false); m_log.Debug(string.Format( "[SCRIPT INSTANCE]: Runtime error in script {0}, part {1} {2} at {3} in {4} ", ScriptName, PrimName, Part.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name), e); } catch (Exception) { } // catch (Exception e2) // LEGIT: User Scripting // { // m_log.Error("[SCRIPT]: "+ // "Error displaying error in-world: " + // e2.ToString()); // m_log.Error("[SCRIPT]: " + // "Errormessage: Error compiling script:\r\n" + // e.ToString()); // } } else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException)) { m_InSelfDelete = true; Engine.World.DeleteSceneObject(Part.ParentGroup, false); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException)) { m_InSelfDelete = true; Part.Inventory.RemoveInventoryItem(ItemID); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException)) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.", PrimName, ScriptName, data.EventName, State); } } } } // If there are more events and we are currently running and not shutting down, then ask the // script engine to run the next event. lock (EventQueue) { EventsProcessed++; if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } } m_DetectParams = null; return 0; } } public int EventTime() { if (!m_InEvent) return 0; return (DateTime.Now - m_EventStart).Seconds; } public void ResetScript(int timeout) { if (m_Script == null) return; bool running = Running; RemoveState(); ReleaseControls(); Stop(timeout); Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.UnregisterScriptFacilities(Engine, LocalID, ItemID, true); EventQueue.Clear(); m_Script.ResetVars(); StartParam = 0; State = "default"; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (running) Start(); m_SaveState = true; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); } public void ApiResetScript() { // bool running = Running; RemoveState(); ReleaseControls(); m_Script.ResetVars(); Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.UnregisterScriptFacilities(Engine, LocalID, ItemID, true); EventQueue.Clear(); m_Script.ResetVars(); string oldState = State; StartParam = 0; State = "default"; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (m_CurrentEvent != "state_entry" || oldState != "default") { m_SaveState = true; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } } public Dictionary<string, object> GetVars() { if (m_Script != null) return m_Script.GetVars(); else return new Dictionary<string, object>(); } public void SetVars(Dictionary<string, object> vars) { m_Script.SetVars(vars); } public DetectParams GetDetectParams(int idx) { if (m_DetectParams == null) return null; if (idx < 0 || idx >= m_DetectParams.Length) return null; return m_DetectParams[idx]; } public UUID GetDetectID(int idx) { if (m_DetectParams == null) return UUID.Zero; if (idx < 0 || idx >= m_DetectParams.Length) return UUID.Zero; return m_DetectParams[idx].Key; } public void SaveState(string assembly) { // If we're currently in an event, just tell it to save upon return // if (m_InEvent) { m_SaveState = true; return; } PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); string xml = ScriptSerializer.Serialize(this); // Compare hash of the state we just just created with the state last written to disk // If the state is different, update the disk file. UUID hash = UUID.Parse(Utils.MD5String(xml)); if (hash != m_CurrentStateHash) { try { FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state")); Byte[] buf = Util.UTF8NoBomEncoding.GetBytes(xml); fs.Write(buf, 0, buf.Length); fs.Close(); } catch(Exception) { // m_log.Error("Unable to save xml\n"+e.ToString()); } //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"))) //{ // throw new Exception("Completed persistence save, but no file was created"); //} m_CurrentStateHash = hash; } } public IScriptApi GetApi(string name) { if (m_Apis.ContainsKey(name)) { // m_log.DebugFormat("[SCRIPT INSTANCE]: Found api {0} in {1}@{2}", name, ScriptName, PrimName); return m_Apis[name]; } // m_log.DebugFormat("[SCRIPT INSTANCE]: Did not find api {0} in {1}@{2}", name, ScriptName, PrimName); return null; } public override string ToString() { return String.Format("{0} {1} on {2}", ScriptName, ItemID, PrimName); } string FormatException(Exception e) { if (e.InnerException == null) // Not a normal runtime error return e.ToString(); string message = "Runtime error:\n" + e.InnerException.StackTrace; string[] lines = message.Split(new char[] {'\n'}); foreach (string line in lines) { if (line.Contains("SecondLife.Script")) { int idx = line.IndexOf(':'); if (idx != -1) { string val = line.Substring(idx+1); int lineNum = 0; if (int.TryParse(val, out lineNum)) { KeyValuePair<int, int> pos = Compiler.FindErrorPosition( lineNum, 0, LineMap); int scriptLine = pos.Key; int col = pos.Value; if (scriptLine == 0) scriptLine++; if (col == 0) col++; message = string.Format("Runtime error:\n" + "({0}): {1}", scriptLine - 1, e.InnerException.Message); return message; } } } } // m_log.ErrorFormat("Scripting exception:"); // m_log.ErrorFormat(e.ToString()); return e.ToString(); } public string GetAssemblyName() { return m_Assembly; } public string GetXMLState() { bool run = Running; Stop(100); Running = run; // We should not be doing this, but since we are about to // dispose this, it really doesn't make a difference // This is meant to work around a Windows only race // m_InEvent = false; // Force an update of the in-memory plugin data // PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); return ScriptSerializer.Serialize(this); } public UUID RegionID { get { return m_RegionID; } } public void Suspend() { Suspended = true; } public void Resume() { Suspended = false; } } /// <summary> /// Xengine event wait handle. /// </summary> /// <remarks> /// This class exists becase XEngineScriptBase gets a reference to this wait handle. We need to make sure that /// when scripts are running in different AppDomains the lease does not expire. /// FIXME: Like LSL_Api, etc., this effectively leaks memory since the GC will never collect it. To avoid this, /// proper remoting sponsorship needs to be implemented across the board. /// </remarks> public class XEngineEventWaitHandle : EventWaitHandle { public XEngineEventWaitHandle(bool initialState, EventResetMode mode) : base(initialState, mode) {} public override Object InitializeLifetimeService() { return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Newtonsoft.Json.Linq; using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using ReactNative.UIManager.Events; using ReactNative.Views.Extensions; using ReactNative.Views.Text; using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace ReactNative.Views.TextInput { /// <summary> /// View manager for <see cref="PasswordBox"/>. /// </summary> class ReactPasswordBoxManager : BaseViewManager<PasswordBox, ReactPasswordBoxShadowNode> { internal static readonly Color DefaultPlaceholderTextColor = Color.FromArgb(255, 0, 0, 0); /// <summary> /// The name of the view manager. /// </summary> public override string Name { get { return "PasswordBoxWindows"; } } /// <summary> /// The exported custom bubbling event types. /// </summary> public override JObject CustomBubblingEventTypeConstants { get { return new JObject { { "topSubmitEditing", new JObject { { "phasedRegistrationNames", new JObject { { "bubbled" , "onSubmitEditing" }, { "captured" , "onSubmitEditingCapture" } } } } }, { "topEndEditing", new JObject { { "phasedRegistrationNames", new JObject { { "bubbled" , "onEndEditing" }, { "captured" , "onEndEditingCapture" } } } } }, }; } } /// <summary> /// Sets the password character on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="passwordCharString">The password masking character to set.</param> [ReactProp("passwordChar")] public void SetPasswordChar(PasswordBox view, string passwordCharString) { view.PasswordChar = passwordCharString.ToCharArray().First(); } /// <summary> /// Sets the password reveal mode on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="revealModeString">The reveal mode, either Hidden, Peek, or Visibile.</param> [ReactProp("passwordRevealMode")] public void SetPasswordRevealMode(PasswordBox view, string revealModeString) { throw new NotSupportedException("Password Reveal Mode is not supported by WPF."); } /// <summary> /// Sets the font size on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontSize">The font size.</param> [ReactProp(ViewProps.FontSize)] public void SetFontSize(PasswordBox view, double fontSize) { view.FontSize = fontSize; } /// <summary> /// Sets the font color for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.Color, CustomType = "Color")] public void SetColor(PasswordBox view, uint? color) { view.Foreground = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : null; } /// <summary> /// Sets the font family for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="familyName">The font family.</param> [ReactProp(ViewProps.FontFamily)] public void SetFontFamily(PasswordBox view, string familyName) { view.FontFamily = familyName != null ? new FontFamily(familyName) : new FontFamily(); } /// <summary> /// Sets the font weight for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontWeightString">The font weight string.</param> [ReactProp(ViewProps.FontWeight)] public void SetFontWeight(PasswordBox view, string fontWeightString) { var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightString); view.FontWeight = fontWeight ?? FontWeights.Normal; } /// <summary> /// Sets the font style for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontStyleString">The font style string.</param> [ReactProp(ViewProps.FontStyle)] public void SetFontStyle(PasswordBox view, string fontStyleString) { var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleString); view.FontStyle = fontStyle ?? new FontStyle(); } /// <summary> /// Sets the default text placeholder prop on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="placeholder">The placeholder text.</param> [ReactProp("placeholder")] public void SetPlaceholder(PasswordBox view, string placeholder) { PlaceholderAdorner.SetText(view, placeholder); } /// <summary> /// Sets the placeholderTextColor prop on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The placeholder text color.</param> [ReactProp("placeholderTextColor", CustomType = "Color")] public void SetPlaceholderTextColor(PasswordBox view, uint? color) { var brush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(DefaultPlaceholderTextColor); PlaceholderAdorner.SetTextColor(view, brush); } /// <summary> /// Sets the border color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.BorderColor, CustomType = "Color")] public void SetBorderColor(PasswordBox view, uint? color) { view.BorderBrush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(ReactTextInputManager.DefaultTextBoxBorder); } /// <summary> /// Sets the background color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.BackgroundColor, CustomType = "Color")] public void SetBackgroundColor(PasswordBox view, uint? color) { view.Background = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(Colors.White); } /// <summary> /// Sets the selection color for the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp("selectionColor", CustomType = "Color")] public void SetSelectionColor(PasswordBox view, uint color) { view.SelectionBrush = new SolidColorBrush(ColorHelpers.Parse(color)); view.CaretBrush = new SolidColorBrush(ColorHelpers.Parse(color)); } /// <summary> /// Sets the text alignment prop on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="alignment">The text alignment.</param> [ReactProp(ViewProps.TextAlignVertical)] public void SetTextVerticalAlign(PasswordBox view, string alignment) { view.VerticalContentAlignment = EnumHelpers.Parse<VerticalAlignment>(alignment); } /// <summary> /// Sets the editablity prop on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="editable">The editable flag.</param> [ReactProp("editable")] public void SetEditable(PasswordBox view, bool editable) { view.IsEnabled = editable; } /// <summary> /// Sets whether the view is a tab stop. /// </summary> /// <param name="view">The view instance.</param> /// <param name="isTabStop"> /// <code>true</code> if the view is a tab stop, otherwise <code>false</code> (control can't get keyboard focus or accept keyboard input in this case). /// </param> [ReactProp("isTabStop")] public void SetIsTabStop(PasswordBox view, bool isTabStop) { view.IsTabStop = isTabStop; } /// <summary> /// Sets the max character length prop on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="maxCharLength">The max length.</param> [ReactProp("maxLength")] public void SetMaxLength(PasswordBox view, int maxCharLength) { view.MaxLength = maxCharLength; } /// <summary> /// Sets the keyboard type on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="keyboardType">The keyboard type.</param> [ReactProp("keyboardType")] public void SetKeyboardType(PasswordBox view, string keyboardType) { var inputScope = new InputScope(); var nameValue = keyboardType != null ? InputScopeHelpers.FromStringForPasswordBox(keyboardType) : InputScopeNameValue.Password; inputScope.Names.Add(new InputScopeName(nameValue)); view.InputScope = inputScope; } /// <summary> /// Sets the border width for a <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="width">The border width.</param> [ReactProp(ViewProps.BorderWidth)] public void SetBorderWidth(PasswordBox view, int width) { view.BorderThickness = new Thickness(width); } public override ReactPasswordBoxShadowNode CreateShadowNodeInstance() { return new ReactPasswordBoxShadowNode(); } /// <summary> /// Update the view with extra data. /// </summary> /// <param name="view">The view instance.</param> /// <param name="extraData">The extra data.</param> public override void UpdateExtraData(PasswordBox view, object extraData) { var paddings = extraData as float[]; if (paddings != null) { view.Padding = new Thickness( paddings[0], paddings[1], paddings[2], paddings[3]); } } /// <summary> /// Returns the view instance for <see cref="PasswordBox"/>. /// </summary> /// <param name="reactContext">The themed React Context</param> /// <returns>A new initialized <see cref="PasswordBox"/></returns> protected override PasswordBox CreateViewInstance(ThemedReactContext reactContext) { return new PasswordBox(); } /// <summary> /// Implement this method to receive events/commands directly from /// JavaScript through the <see cref="PasswordBox"/>. /// </summary> /// <param name="view"> /// The view instance that should receive the command. /// </param> /// <param name="commandId">Identifer for the command.</param> /// <param name="args">Optional arguments for the command.</param> public override void ReceiveCommand(PasswordBox view, int commandId, JArray args) { if (commandId == ReactTextInputManager.FocusTextInput) { view.Focus(); } else if (commandId == ReactTextInputManager.BlurTextInput) { view.Blur(); } } /// <summary> /// Installing the textchanged event emitter on the <see cref="TextInput"/> Control. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="PasswordBox"/> view instance.</param> protected override void AddEventEmitters(ThemedReactContext reactContext, PasswordBox view) { base.AddEventEmitters(reactContext, view); view.PasswordChanged += OnPasswordChanged; view.GotFocus += OnGotFocus; view.LostFocus += OnLostFocus; view.KeyDown += OnKeyDown; } /// <summary> /// Called when view is detached from view hierarchy and allows for /// additional cleanup by the <see cref="ReactTextInputManager"/>. /// subclass. Unregister all event handlers for the <see cref="PasswordBox"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="PasswordBox"/>.</param> public override void OnDropViewInstance(ThemedReactContext reactContext, PasswordBox view) { base.OnDropViewInstance(reactContext, view); view.KeyDown -= OnKeyDown; view.LostFocus -= OnLostFocus; view.GotFocus -= OnGotFocus; view.PasswordChanged -= OnPasswordChanged; } /// <summary> /// Sets the dimensions of the view. /// </summary> /// <param name="view">The view.</param> /// <param name="dimensions">The output buffer.</param> public override void SetDimensions(PasswordBox view, Dimensions dimensions) { base.SetDimensions(view, dimensions); view.MinWidth = dimensions.Width; view.MinHeight = dimensions.Height; } private void OnPasswordChanged(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextChangedEvent( textBox.GetTag(), textBox.Password, 0)); } private void OnGotFocus(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new FocusEvent(textBox.GetTag())); } private void OnLostFocus(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; var eventDispatcher = textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher; eventDispatcher.DispatchEvent( new BlurEvent(textBox.GetTag())); eventDispatcher.DispatchEvent( new ReactTextInputEndEditingEvent( textBox.GetTag(), textBox.Password)); } private void OnKeyDown(object sender, KeyEventArgs e) { var textBox = (PasswordBox)sender; if (e.Key == Key.Enter) { e.Handled = true; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextInputSubmitEditingEvent( textBox.GetTag(), textBox.Password)); } if (!e.Handled) { textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new KeyEvent( KeyEvent.KeyPressEventString, textBox.GetTag(), e.Key)); } } } }
/* * 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.IO; using System.Reflection; using Nini.Config; using log4net; using OpenSim.Framework; using OpenSim.Data; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.AssetService { /// <summary> /// A de-duplicating asset service. /// </summary> [Obsolete] public class XAssetService : XAssetServiceBase, IAssetService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected static XAssetService m_RootInstance; public XAssetService(IConfigSource config) : this(config, "AssetService") {} public XAssetService(IConfigSource config, string configName) : base(config, configName) { if (m_RootInstance == null) { m_RootInstance = this; if (m_AssetLoader != null) { IConfig assetConfig = config.Configs[configName]; if (assetConfig == null) throw new Exception("No AssetService configuration"); string loaderArgs = assetConfig.GetString("AssetLoaderArgs", String.Empty); bool assetLoaderEnabled = assetConfig.GetBoolean("AssetLoaderEnabled", true); if (assetLoaderEnabled && !HasChainedAssetService) { m_log.DebugFormat("[XASSET SERVICE]: Loading default asset set from {0}", loaderArgs); m_AssetLoader.ForEachDefaultXmlAsset( loaderArgs, a => { AssetBase existingAsset = Get(a.ID); // AssetMetadata existingMetadata = GetMetadata(a.ID); if (existingAsset == null || Util.SHA1Hash(existingAsset.Data) != Util.SHA1Hash(a.Data)) { // m_log.DebugFormat("[ASSET]: Storing {0} {1}", a.Name, a.ID); m_Database.StoreAsset(a); } }); } m_log.Debug("[XASSET SERVICE]: Local asset service enabled"); m_log.Error("[XASSET SERVICE]: THIS ASSET SERVICE HAS BEEN MARKED OBSOLETE. PLEASE USE FSAssetService"); } } } public virtual AssetBase Get(string id) { // m_log.DebugFormat("[ASSET SERVICE]: Get asset for {0}", id); UUID assetID; if (!UUID.TryParse(id, out assetID)) { m_log.WarnFormat("[XASSET SERVICE]: Could not parse requested asset id {0}", id); return null; } try { AssetBase asset = m_Database.GetAsset(assetID); if (asset != null) { return asset; } else if (HasChainedAssetService) { asset = m_ChainedAssetService.Get(id); if (asset != null) MigrateFromChainedService(asset); return asset; } return null; } catch (Exception e) { m_log.ErrorFormat("[XASSET SERVICE]: Exception getting asset {0} {1}", assetID, e); return null; } } public virtual AssetBase GetCached(string id) { return Get(id); } public virtual AssetMetadata GetMetadata(string id) { // m_log.DebugFormat("[XASSET SERVICE]: Get asset metadata for {0}", id); AssetBase asset = Get(id); if (asset != null) return asset.Metadata; else return null; } public virtual byte[] GetData(string id) { // m_log.DebugFormat("[XASSET SERVICE]: Get asset data for {0}", id); AssetBase asset = Get(id); if (asset != null) return asset.Data; else return null; } public virtual bool Get(string id, Object sender, AssetRetrieved handler) { //m_log.DebugFormat("[XASSET SERVICE]: Get asset async {0}", id); UUID assetID; if (!UUID.TryParse(id, out assetID)) return false; AssetBase asset = Get(id); //m_log.DebugFormat("[XASSET SERVICE]: Got asset {0}", asset); handler(id, sender, asset); return true; } public virtual bool[] AssetsExist(string[] ids) { UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id)); return m_Database.AssetsExist(uuid); } public virtual string Store(AssetBase asset) { bool exists = m_Database.AssetsExist(new[] { asset.FullID })[0]; if (!exists) { // m_log.DebugFormat( // "[XASSET SERVICE]: Storing asset {0} {1}, bytes {2}", asset.Name, asset.FullID, asset.Data.Length); m_Database.StoreAsset(asset); } // else // { // m_log.DebugFormat( // "[XASSET SERVICE]: Not storing asset {0} {1}, bytes {2} as it already exists", asset.Name, asset.FullID, asset.Data.Length); // } return asset.ID; } public bool UpdateContent(string id, byte[] data) { return false; } public virtual bool Delete(string id) { // m_log.DebugFormat("[XASSET SERVICE]: Deleting asset {0}", id); UUID assetID; if (!UUID.TryParse(id, out assetID)) return false; if (HasChainedAssetService) m_ChainedAssetService.Delete(id); return m_Database.Delete(id); } private void MigrateFromChainedService(AssetBase asset) { Store(asset); m_ChainedAssetService.Delete(asset.ID); } } }
singleton ShaderData( DeferredColorShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/deferredColorShaderP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/deferredColorShaderP.glsl"; pixVersion = 2.0; }; new GFXStateBlockData( AL_DeferredCaptureState : PFX_DefaultStateBlock ) { blendEnable = false; separateAlphaBlendDefined = true; separateAlphaBlendEnable = true; separateAlphaBlendSrc = GFXBlendSrcAlpha; separateAlphaBlendDest = GFXBlendDestAlpha; separateAlphaBlendOp = GFXBlendOpMin; samplersDefined = true; samplerStates[0] = SamplerWrapLinear; samplerStates[1] = SamplerWrapLinear; samplerStates[2] = SamplerWrapLinear; samplerStates[3] = SamplerWrapLinear; samplerStates[4] = SamplerWrapLinear; }; new ShaderData( AL_ProbeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/probeShadingP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/probeShadingP.glsl"; samplerNames[0] = "colorBufferTex"; samplerNames[1] = "diffuseLightingBuffer"; samplerNames[2] = "matInfoTex"; samplerNames[3] = "specularLightingBuffer"; samplerNames[4] = "deferredTex"; pixVersion = 2.0; }; singleton PostEffect( AL_PreCapture ) { renderTime = "PFXBeforeBin"; renderBin = "EditorBin"; shader = AL_ProbeShader; stateBlock = AL_DeferredCaptureState; texture[0] = "#color"; texture[1] = "#diffuseLighting"; texture[2] = "#matinfo"; texture[3] = "#specularLighting"; texture[4] = "#deferred"; target = "$backBuffer"; renderPriority = 10000; allowReflectPass = true; }; // Debug Shaders. new ShaderData( AL_ColorBufferShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgColorBufferP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgColorBufferP.glsl"; samplerNames[0] = "colorBufferTex"; pixVersion = 2.0; }; singleton PostEffect( AL_ColorBufferVisualize ) { shader = AL_ColorBufferShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#color"; target = "$backBuffer"; renderPriority = 9999; }; /// Toggles the visualization of the AL lighting specular power buffer. function toggleColorBufferViz( %enable ) { if ( %enable $= "" ) { $AL_ColorBufferShaderVar = AL_ColorBufferVisualize.isEnabled() ? false : true; AL_ColorBufferVisualize.toggle(); } else if ( %enable ) { AL_DeferredShading.disable(); AL_ColorBufferVisualize.enable(); } else if ( !%enable ) { AL_ColorBufferVisualize.disable(); AL_DeferredShading.enable(); } } //roughness map display (matinfo.b) new ShaderData( AL_RoughMapShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgRoughMapVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgRoughMapVisualizeP.glsl"; samplerNames[0] = "matinfoTex"; pixVersion = 2.0; }; singleton PostEffect( AL_RoughMapVisualize ) { shader = AL_RoughMapShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#matinfo"; target = "$backBuffer"; renderPriority = 9999; }; function toggleRoughMapViz( %enable ) { if ( %enable $= "" ) { $AL_RoughMapShaderVar = AL_RoughMapVisualize.isEnabled() ? false : true; AL_RoughMapVisualize.toggle(); } else if ( %enable ) AL_RoughMapVisualize.enable(); else if ( !%enable ) AL_RoughMapVisualize.disable(); } //metalness map display (matinfo.a) new ShaderData( AL_MetalMapShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgMetalMapVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgMetalMapVisualizeP.glsl"; samplerNames[0] = "matinfoTex"; pixVersion = 2.0; }; singleton PostEffect( AL_MetalMapVisualize ) { shader = AL_MetalMapShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#matinfo"; target = "$backBuffer"; renderPriority = 9999; }; function toggleMetalMapViz( %enable ) { if ( %enable $= "" ) { $AL_MetalMapShaderVar = AL_MetalMapVisualize.isEnabled() ? false : true; AL_MetalMapVisualize.toggle(); } else if ( %enable ) AL_MetalMapVisualize.enable(); else if ( !%enable ) AL_MetalMapVisualize.disable(); } //Light map display (indirectLighting) new ShaderData( AL_LightMapShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgLightMapVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgLightMapVisualizeP.glsl"; samplerNames[0] = "specularLightingBuffer"; pixVersion = 2.0; }; singleton PostEffect( AL_LightMapVisualize ) { shader = AL_LightMapShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#specularLighting"; target = "$backBuffer"; renderPriority = 9999; }; function toggleLightMapViz( %enable ) { if ( %enable $= "" ) { $AL_LightMapShaderVar = AL_LightMapVisualize.isEnabled() ? false : true; AL_LightMapVisualize.toggle(); } else if ( %enable ) AL_LightMapVisualize.enable(); else if ( !%enable ) AL_LightMapVisualize.disable(); }
// 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.Contracts; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableQueueTest : SimpleElementImmutablesTestBase { private void EnqueueDequeueTestHelper<T>(params T[] items) { Contract.Requires(items != null); var queue = ImmutableQueue<T>.Empty; int i = 0; foreach (T item in items) { var nextQueue = queue.Enqueue(item); Assert.NotSame(queue, nextQueue); //, "Enqueue returned this instead of a new instance."); Assert.Equal(i, queue.Count()); //, "Enqueue mutated the queue."); Assert.Equal(++i, nextQueue.Count()); queue = nextQueue; } i = 0; foreach (T element in queue) { AssertAreSame(items[i++], element); } i = 0; foreach (T element in (System.Collections.IEnumerable)queue) { AssertAreSame(items[i++], element); } i = items.Length; foreach (T expectedItem in items) { T actualItem = queue.Peek(); AssertAreSame(expectedItem, actualItem); var nextQueue = queue.Dequeue(); Assert.NotSame(queue, nextQueue); //, "Dequeue returned this instead of a new instance."); Assert.Equal(i, queue.Count()); Assert.Equal(--i, nextQueue.Count()); queue = nextQueue; } } [Fact] public void EnumerationOrder() { var queue = ImmutableQueue<int>.Empty; // Push elements onto the backwards stack. queue = queue.Enqueue(1).Enqueue(2).Enqueue(3); Assert.Equal(1, queue.Peek()); // Force the backwards stack to be reversed and put into forwards. queue = queue.Dequeue(); // Push elements onto the backwards stack again. queue = queue.Enqueue(4).Enqueue(5); // Now that we have some elements on the forwards and backwards stack, // 1. enumerate all elements to verify order. Assert.Equal<int>(new[] { 2, 3, 4, 5 }, queue.ToArray()); // 2. dequeue all elements to verify order var actual = new int[queue.Count()]; for (int i = 0; i < actual.Length; i++) { actual[i] = queue.Peek(); queue = queue.Dequeue(); } } [Fact] public void GetEnumeratorText() { var queue = ImmutableQueue.Create(5); var enumeratorStruct = queue.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current); Assert.True(enumeratorStruct.MoveNext()); Assert.Equal(5, enumeratorStruct.Current); Assert.False(enumeratorStruct.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current); var enumerator = ((IEnumerable<int>)queue).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(5, enumerator.Current); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(5, enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator.Dispose(); } [Fact] public void EnumeratorRecyclingMisuse() { var queue = ImmutableQueue.Create(5); var enumerator = ((IEnumerable<int>)queue).GetEnumerator(); var enumeratorCopy = enumerator; Assert.True(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); // As pure structs with no disposable reference types inside it, // we have nothing to track across struct copies, and this just works. ////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); ////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); ////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = ((IEnumerable<int>)queue).GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(queue.Peek(), enumerator.Current); enumerator.Dispose(); } [Fact] public void EnqueueDequeueTest() { this.EnqueueDequeueTestHelper(new GenericParameterHelper(1), new GenericParameterHelper(2), new GenericParameterHelper(3)); this.EnqueueDequeueTestHelper<GenericParameterHelper>(); // interface test IImmutableQueue<GenericParameterHelper> queueInterface = ImmutableQueue.Create<GenericParameterHelper>(); IImmutableQueue<GenericParameterHelper> populatedQueueInterface = queueInterface.Enqueue(new GenericParameterHelper(5)); Assert.Equal(new GenericParameterHelper(5), populatedQueueInterface.Peek()); } [Fact] public void DequeueOutValue() { var queue = ImmutableQueue<int>.Empty.Enqueue(5).Enqueue(6); int head; queue = queue.Dequeue(out head); Assert.Equal(5, head); var emptyQueue = queue.Dequeue(out head); Assert.Equal(6, head); Assert.True(emptyQueue.IsEmpty); // Also check that the interface extension method works. IImmutableQueue<int> interfaceQueue = queue; Assert.Same(emptyQueue, interfaceQueue.Dequeue(out head)); Assert.Equal(6, head); } [Fact] public void ClearTest() { var emptyQueue = ImmutableQueue.Create<GenericParameterHelper>(); AssertAreSame(emptyQueue, emptyQueue.Clear()); var nonEmptyQueue = emptyQueue.Enqueue(new GenericParameterHelper(3)); AssertAreSame(emptyQueue, nonEmptyQueue.Clear()); // Interface test IImmutableQueue<GenericParameterHelper> queueInterface = nonEmptyQueue; AssertAreSame(emptyQueue, queueInterface.Clear()); } [Fact] public void EqualsTest() { Assert.False(ImmutableQueue<int>.Empty.Equals(null)); Assert.False(ImmutableQueue<int>.Empty.Equals("hi")); Assert.True(ImmutableQueue<int>.Empty.Equals(ImmutableQueue<int>.Empty)); Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3))); Assert.False(ImmutableQueue<int>.Empty.Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3))); Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3))); Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5))); // Also be sure to compare equality of partially dequeued queues since that moves data to different fields. Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(1).Enqueue(2).Dequeue().Equals(ImmutableQueue<int>.Empty.Enqueue(1).Enqueue(2))); } [Fact] public void PeekEmptyThrows() { Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Peek()); } [Fact] public void DequeueEmptyThrows() { Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Dequeue()); } [Fact] public void Create() { ImmutableQueue<int> queue = ImmutableQueue.Create<int>(); Assert.True(queue.IsEmpty); queue = ImmutableQueue.Create(1); Assert.False(queue.IsEmpty); Assert.Equal(new[] { 1 }, queue); queue = ImmutableQueue.Create(1, 2); Assert.False(queue.IsEmpty); Assert.Equal(new[] { 1, 2 }, queue); queue = ImmutableQueue.CreateRange((IEnumerable<int>)new[] { 1, 2 }); Assert.False(queue.IsEmpty); Assert.Equal(new[] { 1, 2 }, queue); Assert.Throws<ArgumentNullException>(() => ImmutableQueue.CreateRange((IEnumerable<int>)null)); Assert.Throws<ArgumentNullException>(() => ImmutableQueue.Create((int[])null)); } [Fact] public void Empty() { // We already test Create(), so just prove that Empty has the same effect. Assert.Same(ImmutableQueue.Create<int>(), ImmutableQueue<int>.Empty); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableQueue.Create<int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableQueue.Create<string>()); } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { var queue = ImmutableQueue<T>.Empty; foreach (var item in contents) { queue = queue.Enqueue(item); } return queue; } } }
using System; using System.Globalization; using System.Linq; using System.Text; using GroupDocs.Viewer.Domain; using GroupDocs.Viewer.Domain.Containers; namespace MvcSample.Helpers { /// <summary> /// Class FileDataJsonSerializer. /// </summary> public class DocumentInfoJsonSerializer { /// <summary> /// The document info /// </summary> private readonly DocumentInfoContainer _documentInfo; /// <summary> /// The _options /// </summary> private readonly SerializationOptions _options; /// <summary> /// The _default culture /// </summary> private readonly CultureInfo _defaultCulture = CultureInfo.InvariantCulture; /// <summary> /// Two decimals places format /// </summary> private const string TwoDecimalPlacesFormat = "0.##"; /// <summary> /// Initializes a new instance of the <see cref="DocumentInfoContainer"/> class. /// </summary> /// <param name="documentInfo">The document info.</param> /// <param name="options">The options.</param> public DocumentInfoJsonSerializer(DocumentInfoContainer documentInfo, SerializationOptions options) { _documentInfo = documentInfo; _options = options; } /// <summary> /// Serializes this instance. /// </summary> /// <returns>System.String.</returns> public string Serialize() { var isCellsFileData = _documentInfo.Pages.Any(_ => !string.IsNullOrEmpty(_.Name)); if (isCellsFileData && _options.IsHtmlMode) return SerializeCells(); return SerializeDefault(); } /// <summary> /// Serializes the default. /// </summary> /// <returns>System.String.</returns> private string SerializeDefault() { StringBuilder json = new StringBuilder(); var maxWidth = 0; var maxHeight = 0; foreach (var pageData in _documentInfo.Pages) { if (pageData.Height > maxHeight) { maxHeight = pageData.Height; maxWidth = pageData.Width; } } json.Append("{\"pages\":["); int pageCount = _documentInfo.Pages.Count; for (int i = 0; i < pageCount; i++) { PageData pageData = _documentInfo.Pages[i]; bool needSeparator = i > 0; if (needSeparator) json.Append(","); AppendPage(pageData, json); bool includeRows = _options.UsePdf && pageData.Rows.Count > 0; if (includeRows) { json.Append(",\"rows\":["); for (int j = 0; j < pageData.Rows.Count; j++) { bool appendRowSeaparator = j != 0; if (appendRowSeaparator) json.Append(","); AppendRow(pageData.Rows[j], json); } json.Append("]"); // rows } json.Append("}"); // page } json.Append("]"); // pages json.Append(string.Format(",\"maxPageHeight\":{0},\"widthForMaxHeight\":{1}", maxHeight, maxWidth)); json.Append("}"); // document return json.ToString(); } /// <summary> /// Serializes cells. /// </summary> /// <returns>System.String.</returns> private string SerializeCells() { StringBuilder json = new StringBuilder(); json.Append("{\"sheets\":["); int pageCount = _documentInfo.Pages.Count; for (int i = 0; i < pageCount; i++) { PageData pageData = _documentInfo.Pages[i]; bool needSeparator = i > 0; if (needSeparator) json.Append(","); json.Append(string.Format("{{\"name\":\"{0}\"}}", pageData.Name)); } json.Append("]"); // pages json.Append("}"); // document return json.ToString(); } /// <summary> /// Serializes the specified words file data. /// </summary> /// <returns>System.String.</returns> private string SerializeWords() { StringBuilder json = new StringBuilder(); var maxWidth = 0; var maxHeight = 0; foreach (var pageData in _documentInfo.Pages) { if (pageData.Height > maxHeight) { maxHeight = pageData.Height; maxWidth = pageData.Width; } } json.Append("{\"pages\":["); int pageCount = _documentInfo.Pages.Count; for (int i = 0; i < pageCount; i++) { PageData pageData = _documentInfo.Pages[i]; bool needSeparator = pageData.Number >= 1; if (needSeparator) json.Append(","); AppendPage(pageData, json); json.Append("}"); // page } json.Append("]"); // pages json.Append(string.Format(",\"maxPageHeight\":{0},\"widthForMaxHeight\":{1}", maxHeight, maxWidth)); json.Append("}"); //document return json.ToString(); } /// <summary> /// Appends the page. /// </summary> /// <param name="pageData">The page data.</param> /// <param name="json">The json.</param> private void AppendPage(PageData pageData, StringBuilder json) { if (pageData.Angle == 0) { json.Append(string.Format("{{\"w\":{0},\"h\":{1},\"number\":{2}", pageData.Width.ToString(_defaultCulture), pageData.Height.ToString(_defaultCulture), (pageData.Number).ToString(_defaultCulture))); } else { json.Append(string.Format("{{\"w\":{0},\"h\":{1},\"number\":{2},\"rotation\":{3}", pageData.Width.ToString(_defaultCulture), pageData.Height.ToString(_defaultCulture), (pageData.Number).ToString(_defaultCulture), pageData.Angle)); } } /// <summary> /// Appends the row. /// </summary> /// <param name="rowData">The row data.</param> /// <param name="json">The json.</param> private void AppendRow(RowData rowData, StringBuilder json) { string[] textCoordinates = new string[rowData.TextCoordinates.Count]; for (int i = 0; i < rowData.TextCoordinates.Count; i++) textCoordinates[i] = rowData.TextCoordinates[i].ToString(TwoDecimalPlacesFormat, _defaultCulture); string[] characterCoordinates = new string[rowData.CharacterCoordinates.Count]; for (int i = 0; i < rowData.CharacterCoordinates.Count; i++) characterCoordinates[i] = rowData.CharacterCoordinates[i].ToString(TwoDecimalPlacesFormat, _defaultCulture); json.Append(String.Format("{{\"l\":{0},\"t\":{1},\"w\":{2},\"h\":{3},\"c\":[{4}],\"s\":\"{5}\",\"ch\":[{6}]}}", rowData.LineLeft.ToString(TwoDecimalPlacesFormat, _defaultCulture), rowData.LineTop.ToString(TwoDecimalPlacesFormat, _defaultCulture), rowData.LineWidth.ToString(TwoDecimalPlacesFormat, _defaultCulture), rowData.LineHeight.ToString(TwoDecimalPlacesFormat, _defaultCulture), string.Join(",", textCoordinates), JsonEncode(rowData.Text), string.Join(",", characterCoordinates))); } /// <summary> /// Jsons the encode. /// </summary> /// <param name="text">The text.</param> /// <returns>System.String.</returns> private string JsonEncode(string text) { if (string.IsNullOrEmpty(text)) return string.Empty; int i; int length = text.Length; StringBuilder stringBuilder = new StringBuilder(length + 4); for (i = 0; i < length; i += 1) { char c = text[i]; switch (c) { case '\\': case '"': case '/': stringBuilder.Append('\\'); stringBuilder.Append(c); break; case '\b': stringBuilder.Append("\\b"); break; case '\t': stringBuilder.Append("\\t"); break; case '\n': stringBuilder.Append("\\n"); break; case '\f': stringBuilder.Append("\\f"); break; case '\r': stringBuilder.Append("\\r"); break; default: if (c < ' ') { string t = "000" + Convert.ToByte(c).ToString("X"); stringBuilder.Append("\\u" + t.Substring(t.Length - 4)); } else { stringBuilder.Append(c); } break; } } return stringBuilder.ToString(); } } public class SerializationOptions { public bool UsePdf { get; set; } public bool IsHtmlMode { get; set; } public bool SupportListOfBookmarks { get; set; } public bool SupportListOfContentControls { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using NUnit.Framework; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface.Auth; using ServiceStack.Text; namespace ServiceStack.Common.Tests.OAuth { [TestFixture] public class OAuthUserSessionTests : OAuthUserSessionTestsBase { [Test, TestCaseSource("UserAuthRepositorys")] public void Does_persist_TwitterOAuth(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); MockAuthHttpGateway.Tokens = twitterGatewayTokens; var authInfo = new Dictionary<string, string> { {"user_id", "133371690876022785"}, {"screen_name", "demisbellot"}, }; var oAuthUserSession = requestContext.ReloadSession(); var twitterAuth = GetTwitterAuthProvider(); twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.UserAuthId, Is.Not.Null); var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId); Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId)); Assert.That(userAuth.DisplayName, Is.EqualTo("Demis Bellot TW")); var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId); Assert.That(authProviders.Count, Is.EqualTo(1)); var authProvider = authProviders[0]; Assert.That(authProvider.UserAuthId, Is.EqualTo(userAuth.Id)); Assert.That(authProvider.DisplayName, Is.EqualTo("Demis Bellot TW")); Assert.That(authProvider.FirstName, Is.Null); Assert.That(authProvider.LastName, Is.Null); Assert.That(authProvider.RequestToken, Is.EqualTo(twitterAuthTokens.RequestToken)); Assert.That(authProvider.RequestTokenSecret, Is.EqualTo(twitterAuthTokens.RequestTokenSecret)); Console.WriteLine(authProviders.Dump()); } [Test, TestCaseSource("UserAuthRepositorys")] public void Does_persist_FacebookOAuth(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var serviceTokens = MockAuthHttpGateway.Tokens = facebookGatewayTokens; var oAuthUserSession = requestContext.ReloadSession(); var authInfo = new Dictionary<string, string> { }; var facebookAuth = GetFacebookAuthProvider(); facebookAuth.OnAuthenticated(service, oAuthUserSession, facebookAuthTokens, authInfo); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.FacebookUserId, Is.EqualTo(serviceTokens.UserId)); Assert.That(oAuthUserSession.UserAuthId, Is.Not.Null); var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId); Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId)); Assert.That(userAuth.DisplayName, Is.EqualTo(serviceTokens.DisplayName)); Assert.That(userAuth.FirstName, Is.EqualTo(serviceTokens.FirstName)); Assert.That(userAuth.LastName, Is.EqualTo(serviceTokens.LastName)); Assert.That(userAuth.PrimaryEmail, Is.EqualTo(serviceTokens.Email)); var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId); Assert.That(authProviders.Count, Is.EqualTo(1)); var authProvider = authProviders[0]; Assert.That(authProvider.UserAuthId, Is.EqualTo(userAuth.Id)); Assert.That(authProvider.DisplayName, Is.EqualTo(serviceTokens.DisplayName)); Assert.That(authProvider.FirstName, Is.EqualTo(serviceTokens.FirstName)); Assert.That(authProvider.LastName, Is.EqualTo(serviceTokens.LastName)); Assert.That(authProvider.Email, Is.EqualTo(serviceTokens.Email)); Assert.That(authProvider.RequestToken, Is.Null); Assert.That(authProvider.RequestTokenSecret, Is.Null); Assert.That(authProvider.AccessToken, Is.Null); Assert.That(authProvider.AccessTokenSecret, Is.EqualTo(facebookAuthTokens.AccessTokenSecret)); Console.WriteLine(authProviders.Dump()); } [Test, TestCaseSource("UserAuthRepositorys")] public void Does_merge_FacebookOAuth_TwitterOAuth(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var serviceTokensFb = MockAuthHttpGateway.Tokens = facebookGatewayTokens; var oAuthUserSession = requestContext.ReloadSession(); var facebookAuth = GetFacebookAuthProvider(); facebookAuth.OnAuthenticated(service, oAuthUserSession, facebookAuthTokens, new Dictionary<string, string>()); oAuthUserSession = requestContext.ReloadSession(); var serviceTokensTw = MockAuthHttpGateway.Tokens = twitterGatewayTokens; var authInfo = new Dictionary<string, string> { {"user_id", "133371690876022785"}, {"screen_name", "demisbellot"}, }; var twitterAuth = GetTwitterAuthProvider(); twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.TwitterUserId, Is.EqualTo(authInfo["user_id"])); Assert.That(oAuthUserSession.TwitterScreenName, Is.EqualTo(authInfo["screen_name"])); var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId); Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId)); Assert.That(userAuth.DisplayName, Is.EqualTo(serviceTokensTw.DisplayName)); Assert.That(userAuth.FirstName, Is.EqualTo(serviceTokensFb.FirstName)); Assert.That(userAuth.LastName, Is.EqualTo(serviceTokensFb.LastName)); Assert.That(userAuth.PrimaryEmail, Is.EqualTo(serviceTokensFb.Email)); var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId); Assert.That(authProviders.Count, Is.EqualTo(2)); Console.WriteLine(userAuth.Dump()); Console.WriteLine(authProviders.Dump()); } [Test, TestCaseSource("UserAuthRepositorys")] public void Can_login_with_user_created_CreateUserAuth(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var registrationService = GetRegistrationService(userAuthRepository); var responseObj = registrationService.Post(registrationDto); var httpResult = responseObj as IHttpResult; if (httpResult != null) { Assert.Fail("HttpResult found: " + httpResult.Dump()); } var response = (RegistrationResponse)responseObj; Assert.That(response.UserId, Is.Not.Null); var userAuth = userAuthRepository.GetUserAuth(response.UserId); AssertEqual(userAuth, registrationDto); userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.UserName); AssertEqual(userAuth, registrationDto); userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.Email); AssertEqual(userAuth, registrationDto); UserAuth userId; var success = userAuthRepository.TryAuthenticate(registrationDto.UserName, registrationDto.Password, out userId); Assert.That(success, Is.True); Assert.That(userId, Is.Not.Null); success = userAuthRepository.TryAuthenticate(registrationDto.Email, registrationDto.Password, out userId); Assert.That(success, Is.True); Assert.That(userId, Is.Not.Null); success = userAuthRepository.TryAuthenticate(registrationDto.UserName, "Bad Password", out userId); Assert.That(success, Is.False); Assert.That(userId, Is.Null); } [Test, TestCaseSource("UserAuthRepositorys")] public void Logging_in_pulls_all_AuthInfo_from_repo_after_logging_in_all_AuthProviders(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); //Facebook LoginWithFacebook(oAuthUserSession); //Twitter MockAuthHttpGateway.Tokens = twitterGatewayTokens; var authInfo = new Dictionary<string, string> { {"user_id", "133371690876022785"}, {"screen_name", "demisbellot"}, }; var twitterAuth = GetTwitterAuthProvider(); twitterAuth.OnAuthenticated(service, oAuthUserSession, twitterAuthTokens, authInfo); Console.WriteLine("UserId: " + oAuthUserSession.UserAuthId); //Register var registrationService = GetRegistrationService(userAuthRepository, oAuthUserSession, requestContext); var responseObj = registrationService.Post(registrationDto); Assert.That(responseObj as IHttpError, Is.Null, responseObj.ToString()); Console.WriteLine("UserId: " + oAuthUserSession.UserAuthId); var credentialsAuth = GetCredentialsAuthConfig(); var loginResponse = credentialsAuth.Authenticate(service, oAuthUserSession, new Auth { provider = CredentialsAuthProvider.Name, UserName = registrationDto.UserName, Password = registrationDto.Password, }); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.TwitterUserId, Is.EqualTo(authInfo["user_id"])); Assert.That(oAuthUserSession.TwitterScreenName, Is.EqualTo(authInfo["screen_name"])); var userAuth = userAuthRepository.GetUserAuth(oAuthUserSession.UserAuthId); Assert.That(userAuth.Id.ToString(CultureInfo.InvariantCulture), Is.EqualTo(oAuthUserSession.UserAuthId)); Assert.That(userAuth.DisplayName, Is.EqualTo(registrationDto.DisplayName)); Assert.That(userAuth.FirstName, Is.EqualTo(registrationDto.FirstName)); Assert.That(userAuth.LastName, Is.EqualTo(registrationDto.LastName)); Assert.That(userAuth.Email, Is.EqualTo(registrationDto.Email)); Console.WriteLine(oAuthUserSession.Dump()); Assert.That(oAuthUserSession.ProviderOAuthAccess.Count, Is.EqualTo(2)); Assert.That(oAuthUserSession.IsAuthenticated, Is.True); var authProviders = userAuthRepository.GetUserOAuthProviders(oAuthUserSession.UserAuthId); Assert.That(authProviders.Count, Is.EqualTo(2)); Console.WriteLine(userAuth.Dump()); Console.WriteLine(authProviders.Dump()); } [Test, TestCaseSource("UserAuthRepositorys")] public void Registering_twice_creates_two_registrations(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); RegisterAndLogin(userAuthRepository, oAuthUserSession); requestContext.RemoveSession(); var userName1 = registrationDto.UserName; var userName2 = "UserName2"; registrationDto.UserName = userName2; registrationDto.Email = "as@if2.com"; var userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1); Assert.That(userAuth1, Is.Not.Null); Register(userAuthRepository, oAuthUserSession, registrationDto); userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1); var userAuth2 = userAuthRepository.GetUserAuthByUserName(userName2); Assert.That(userAuth1, Is.Not.Null); Assert.That(userAuth2, Is.Not.Null); } [Test, TestCaseSource("UserAuthRepositorys")] public void Registering_twice_in_same_session_updates_registration(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); oAuthUserSession = RegisterAndLogin(userAuthRepository, oAuthUserSession); var userName1 = registrationDto.UserName; var userName2 = "UserName2"; registrationDto.UserName = userName2; Register(userAuthRepository, oAuthUserSession, registrationDto); var userAuth1 = userAuthRepository.GetUserAuthByUserName(userName1); var userAuth2 = userAuthRepository.GetUserAuthByUserName(userName2); Assert.That(userAuth1, Is.Null); Assert.That(userAuth2, Is.Not.Null); } [Test, TestCaseSource("UserAuthRepositorys")] public void Connecting_to_facebook_whilst_authenticated_connects_account(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); oAuthUserSession = RegisterAndLogin(userAuthRepository, oAuthUserSession); LoginWithFacebook(oAuthUserSession); var userAuth = userAuthRepository.GetUserAuthByUserName(registrationDto.UserName); Assert.That(userAuth.UserName, Is.EqualTo(registrationDto.UserName)); var userAuthProviders = userAuthRepository.GetUserOAuthProviders(userAuth.Id.ToString(CultureInfo.InvariantCulture)); Assert.That(userAuthProviders.Count, Is.EqualTo(1)); } [Test, TestCaseSource("UserAuthRepositorys")] public void Can_AutoLogin_whilst_Registering(IUserAuthRepository userAuthRepository) { InitTest(userAuthRepository); var oAuthUserSession = requestContext.ReloadSession(); registrationDto.AutoLogin = true; Register(userAuthRepository, oAuthUserSession, registrationDto); oAuthUserSession = requestContext.ReloadSession(); Assert.That(oAuthUserSession.IsAuthenticated, Is.True); } } }
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Sandbox.Common.ObjectBuilders; using Sandbox.ModAPI; using Sandbox.ModAPI.Interfaces.Terminal; using VRage.Game.Components; using VRage.Game.ModAPI; using VRage.ModAPI; using VRage.ObjectBuilders; using VRage.Utils; using VRageMath; namespace Digi.LoopComputers { [MySessionComponentDescriptor(MyUpdateOrder.BeforeSimulation)] public class LoopComputersMod : MySessionComponentBase { public override void LoadData() { instance = this; Log.SetUp("Loop Computers", 400037065, "LoopComputers"); } public static LoopComputersMod instance = null; public bool init = false; public bool initTerminalUI = false; public readonly StringBuilder str = new StringBuilder(); private IMyTerminalControl separator = null; public const string SLIDER_ID = "LoopComputers.RepeatTime"; public const string AFTER_CONTROL_ID = "Recompile"; private void Init() { init = true; Log.Init(); MyAPIGateway.TerminalControls.CustomControlGetter += CustomControlGetter; MyAPIGateway.Utilities.InvokeOnGameThread(() => SetUpdateOrder(MyUpdateOrder.NoUpdate)); } protected override void UnloadData() { try { if(init) { init = false; MyAPIGateway.TerminalControls.CustomControlGetter -= CustomControlGetter; } } catch(Exception e) { Log.Error(e); } instance = null; Log.Close(); } // move this mods' terminal controls right after the control specified in AFTER_CONTROL_ID public void CustomControlGetter(IMyTerminalBlock block, List<IMyTerminalControl> controls) { if(block is IMyProgrammableBlock) { var index = controls.FindIndex((m) => m.Id == SLIDER_ID); if(index == -1) return; if(separator == null) separator = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyProgrammableBlock>(string.Empty); var runIndex = controls.FindIndex((m) => m.Id == AFTER_CONTROL_ID); var c = controls[index]; controls.RemoveAt(index); controls.AddOrInsert(separator, runIndex + 1); controls.AddOrInsert(c, runIndex + 2); } } public override void UpdateBeforeSimulation() { try { if(!init) { if(MyAPIGateway.Session == null || MyAPIGateway.Multiplayer == null) return; Init(); } } catch(Exception e) { Log.Error(e); } } } [MyEntityComponentDescriptor(typeof(MyObjectBuilder_MyProgrammableBlock), useEntityUpdate: false)] public class LoopPB : MyGameLogicComponent { private bool first = true; private float delayTime = 0; private int tick = 0; private byte propertiesChangedDelay = 0; private const string DATA_TAG_START = "{LoopComputers:"; private const char DATA_TAG_END = '}'; private const string LEGACY_TAG_START = "[repeat"; private const string LEGACY_TAG_END = "]"; public override void Init(MyObjectBuilder_EntityBase objectBuilder) { NeedsUpdate = MyEntityUpdateEnum.EACH_FRAME; } private void FirstUpdate() { var block = (IMyTerminalBlock)Entity; block.CustomNameChanged += NameChanged; ReadLegacyName(block); NameChanged(block); if(!LoopComputersMod.instance.initTerminalUI) { LoopComputersMod.instance.initTerminalUI = true; var c = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProgrammableBlock>(LoopComputersMod.SLIDER_ID); c.Title = MyStringId.GetOrCompute("Auto-run"); c.Tooltip = MyStringId.GetOrCompute("The block runs itself at the specified interval.\nValues smaller than 0.016s (one tick) are considered off."); c.SupportsMultipleBlocks = true; c.SetLogLimits(0.015f, 600f); c.Enabled = (b) => (!MyAPIGateway.Session.SessionSettings.EnableScripterRole || MyAPIGateway.Session.PromoteLevel >= MyPromoteLevel.Scripter); c.Setter = (b, v) => b.GameLogic.GetAs<LoopPB>().DelayTime = (v < 0.016f ? 0 : v); c.Getter = (b) => (b.GameLogic.GetAs<LoopPB>().DelayTime); c.Writer = delegate (IMyTerminalBlock b, StringBuilder s) { float v = b.GameLogic.GetAs<LoopPB>().DelayTime; if(v < 0.016f) { s.Append("Off"); } else { var ticks = (int)Math.Round(v * 60); s.AppendFormat("{0:0.000}s / {1}tick{2}", v, ticks, (ticks == 1 ? "" : "s")); } }; MyAPIGateway.TerminalControls.AddControl<IMyProgrammableBlock>(c); } } public override void Close() { var block = (IMyTerminalBlock)Entity; block.CustomNameChanged -= NameChanged; } public float DelayTime { get { return delayTime; } set { delayTime = (float)Math.Round(value, 3); if(propertiesChangedDelay <= 0) propertiesChangedDelay = 30; } } public void NameChanged(IMyTerminalBlock block) { try { delayTime = 0; var name = block.CustomName.ToLower(); var startIndex = name.IndexOf(DATA_TAG_START, StringComparison.OrdinalIgnoreCase); if(startIndex == -1) return; startIndex += DATA_TAG_START.Length; var endIndex = name.IndexOf(DATA_TAG_END, startIndex); if(endIndex == -1) return; var data = name.Substring(startIndex, (endIndex - startIndex)); delayTime = (float)Math.Round(float.Parse(data), 3); } catch(Exception e) { Log.Error(e); } } private void SaveToName(string forceName = null) { var block = (IMyTerminalBlock)Entity; var str = LoopComputersMod.instance.str; str.Clear(); str.Append(forceName ?? GetNameNoData().Trim()); if(delayTime > 0) { str.Append(' ', 3); str.Append(DATA_TAG_START); str.Append(delayTime); str.Append(DATA_TAG_END); } block.CustomName = str.ToString(); str.Clear(); } private string GetNameNoData() { var block = Entity as IMyTerminalBlock; var name = block.CustomName; var startIndex = name.IndexOf(DATA_TAG_START, StringComparison.OrdinalIgnoreCase); if(startIndex == -1) return name; var nameNoData = name.Substring(0, startIndex); var endIndex = name.IndexOf(DATA_TAG_END, startIndex); if(endIndex == -1) return nameNoData; else return nameNoData + name.Substring(endIndex + 1); } public override void UpdateBeforeSimulation() { try { var pb = (IMyProgrammableBlock)Entity; if(pb.CubeGrid.Physics == null) return; if(first) { if(LoopComputersMod.instance == null || !LoopComputersMod.instance.init) return; first = false; FirstUpdate(); return; } if(propertiesChangedDelay > 0 && --propertiesChangedDelay == 0) SaveToName(); if(!MyAPIGateway.Multiplayer.IsServer) return; if(delayTime < 0.016f) return; if(pb.Enabled && pb.IsFunctional && pb.IsWorking && ++tick >= (delayTime * 60)) { tick = 0; pb.Run(); } } catch(Exception e) { Log.Error(e); } } private void ReadLegacyName(IMyTerminalBlock block) { var name = block.CustomName.ToLower(); delayTime = 0; if(name.Contains(LEGACY_TAG_START + LEGACY_TAG_END)) { delayTime = 1; } else if(name.Contains(LEGACY_TAG_START)) { int startIndex = name.IndexOf(LEGACY_TAG_START, StringComparison.Ordinal) + LEGACY_TAG_START.Length; int endIndex = name.IndexOf(LEGACY_TAG_END, startIndex, StringComparison.Ordinal); if(startIndex == -1 || endIndex == -1) { delayTime = 0; return; } string arg = name.Substring(startIndex, endIndex - startIndex).Trim(' ', ':', '='); float delay; if(float.TryParse(arg, out delay)) delayTime = MathHelper.Clamp(delay, 0.016f, 600); } SaveToName(Regex.Replace(block.CustomName, @"\[repeat([\s\:\=][\d.]+|)\]", "", RegexOptions.IgnoreCase).Trim()); } } }
// Created by Paul Gonzalez Becerra using System; using System.Reflection; using Saserdote.DataSystems; using Saserdote.GamingServices; using Saserdote.Mathematics; using Tao.Sdl; namespace Saserdote.Input { public static class GameInput { #region --- Field Variables --- // Variables private static Game game; private static bool bFocused; internal static KeyboardHelper khelper; internal static MouseHelper mhelper; internal static Gamepad gamepad; private static bool pUseFocus; public static FList<GamepadInfo> gamepadDetector; #endregion // Field Variables #region --- Static Properties --- // Gets and sets if the mouse should be locked to the center of the viewport public static bool bLockCursorToCenter { get { return mhelper.bLockToCenter; } set { mhelper.bLockToCenter= value; } } // Gets and sets if the cursor should be shown public static bool bShowCursor { get { return mhelper.pShowCursor; } set { mhelper.bShowCursor= value; } } // Gets and sets if the input will shut down if unfocused public static bool bUseFocus { get { return pUseFocus; } set { pUseFocus= value; if(!pUseFocus) bFocused= true; } } #endregion // Static Properties #region --- Static Methods --- // Initiates the input internal static void init(Game pmGame) { game= pmGame; Sdl.SDL_Init(Sdl.SDL_INIT_JOYSTICK); game.window.viewport.LostFocus+= onLostFocus; game.window.viewport.GotFocus+= onGotFocus; bFocused= true; pUseFocus= true; mhelper= new MouseHelper(game.window.viewport); khelper= new KeyboardHelper(game.window.viewport); gamepadDetector= new FList<GamepadInfo>(); gamepadDetector.add(new GamepadInfo(15, 0, 3, typeof(Xbox360Gamepad))); gamepadDetector.add(new GamepadInfo(12, 1, 2, typeof(PS2Gamepad))); if(Sdl.SDL_NumJoysticks()> 0) { gamepad= getGamepadNoQuit(0); } } // Refreshes the gamepads, finding new ones or kicking out old ones public static void refreshGamepads() { gamepad= getGamepad(0); } // Gets the gamepad with the given player index public static Gamepad getGamepad(int playerIndex) { Sdl.SDL_Quit(); gamepad= null; Sdl.SDL_Init(Sdl.SDL_INIT_EVERYTHING); return getGamepadNoQuit(playerIndex); } // Gets the gamepad with the given player index, without quiting the sdl stuffs public static Gamepad getGamepadNoQuit(int playerIndex) { // Variables IntPtr js; int btns; int dps; int sks; int n; n= Sdl.SDL_NumJoysticks(); if(n<= 0 || playerIndex> n) return null; js= Sdl.SDL_JoystickOpen(playerIndex); btns= Sdl.SDL_JoystickNumButtons(js); dps= Sdl.SDL_JoystickNumHats(js); sks= Sdl.SDL_JoystickNumAxes(js)/2; for(int i= 0; i< gamepadDetector.size; i++) { if((gamepadDetector[i].numOfButtons== btns) && (gamepadDetector[i].numOfDpads== dps) && (gamepadDetector[i].numOfSticks== sks)) { if(gamepadDetector[i].gamepadType!= null) { // Variables ConstructorInfo constructor= gamepadDetector[i].gamepadType.GetConstructor(new Type[]{typeof(IntPtr)}); if(constructor!= null && gamepadDetector[i].gamepadType.IsSubclassOf(typeof(Gamepad))) { Console.WriteLine("Found Gamepad: "+gamepadDetector[i].gamepadType); return (Gamepad)(constructor.Invoke(new object[]{js})); } } } } return null; } // Called when the viewport is no longer focused private static void onLostFocus(object sender, EventArgs args) { if(bUseFocus) bFocused= false; } // Called when the viewport has gotten focus private static void onGotFocus(object sender, EventArgs args) { if(bUseFocus) bFocused= true; } // Gets the keyboard's input state public static KeyboardState getKeyboardState() { // Variables KeyboardState keyboard= new KeyboardState(); keyboard.keysHeld= khelper.keysHeld.toArray(); return keyboard; } // Gets the mouse's input state public static MouseState getMouseState() { // Variables MouseState mouse= new MouseState(); mouse.mouseWheel= mhelper.mouseWheel; mouse.buttonsHeld= mhelper.getHeldButtons(); mhelper.updateMouseMovement(); mouse.pMovement= mhelper.movement; mouse.pPosition= mhelper.currPosition; mouse.bLockToCenter= mhelper.bLockToCenter; mouse.pShowCursor= mhelper.pShowCursor; return mouse; } // Gets the gamepad's input state public static GamepadState getGamepadState() { // Variables GamepadState gpad= new GamepadState(); gpad.gamepad= gamepad; gpad.update(); return gpad; } // Gets the input args public static InputArgs getInputArgs() { if(!bFocused) return getEmptyInputArgs(); // Variables InputArgs args= new InputArgs(); args.keyboard= getKeyboardState(); args.mouse= getMouseState(); args.gamepad= getGamepadState(); return args; } // Gets an empty set of input args private static InputArgs getEmptyInputArgs() { // Variables InputArgs args= new InputArgs(); args.keyboard= KeyboardState.getEmpty(); args.mouse= MouseState.getEmpty(); args.gamepad= GamepadState.getEmpty(); return args; } #endregion // Static Methods } } // End of File
using CallfireApiClient.Api.Common.Model; using CallfireApiClient.Api.CallsTexts.Model; using System.Collections.Generic; using CallfireApiClient.Api.CallsTexts.Model.Request; using CallfireApiClient.Api.Common.Model.Request; using CallfireApiClient.Api.Campaigns.Model; using System.IO; namespace CallfireApiClient.Api.CallsTexts { public class CallsApi { private const string CALLS_PATH = "/calls"; private const string CALLS_ITEM_PATH = "/calls/{}"; private static string CALLS_ITEM_RECORDINGS_PATH = "/calls/{}/recordings"; private static string CALLS_ITEM_RECORDING_BY_NAME_PATH = "/calls/{}/recordings/{}"; private static string CALLS_ITEM_MP3_RECORDING_BY_NAME_PATH = "/calls/{}/recordings/{}.mp3"; private static string CALLS_ITEM_RECORDING_BY_ID_PATH = "/calls/recordings/{}"; private static string CALLS_ITEM_MP3_RECORDING_BY_ID_PATH = "/calls/recordings/{}.mp3"; private readonly RestApiClient Client; internal CallsApi(RestApiClient client) { Client = client; } /// <summary> /// Finds all calls sent or received by the user, filtered by different properties, broadcast id, /// toNumber, fromNumber, label, state, etc.Use "campaignId=0" parameter to query /// for all calls sent through the POST /calls API {@link CallsApi#send(List)}. /// </summary> /// <param name="request">request object with different fields to filter</param> /// <returns>paged list with call objects</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public Page<Call> Find(FindCallsRequest request) { return Client.Get<Page<Call>>(CALLS_PATH, request); } /// <summary> /// Get call by id /// </summary> /// <param name="id">id of call</param> /// <param name="fields">limit fields returned. Example fields=id,name</param> /// <returns>call object</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public Call Get(long id, string fields = null) { Validate.NotBlank(id.ToString(), "id cannot be blank"); string path = CALLS_ITEM_PATH.ReplaceFirst(ClientConstants.PLACEHOLDER, id.ToString()); var queryParams = ClientUtils.BuildQueryParams("fields", fields); return Client.Get<Call>(path, queryParams); } /// <summary> /// Send calls to recipients through default campaign. /// Use the API to quickly send individual calls. /// A verified Caller ID and sufficient credits are required to make a call. /// </summary> /// <param name="recipients">call recipients</param> /// <param name="campaignId">specify a campaignId to send calls quickly on a previously created campaign</param> /// <param name="fields">limit fields returned. Example fields=id,name</param> /// <returns>list with created call objects</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public IList<Call> Send(IList<CallRecipient> recipients, long? campaignId = null, string fields = null) { Validate.NotBlank(recipients.ToString(), "recipients cannot be blank"); var queryParams = new List<KeyValuePair<string, object>>(2); ClientUtils.AddQueryParamIfSet("campaignId", campaignId, queryParams); ClientUtils.AddQueryParamIfSet("fields", fields, queryParams); return Client.Post<ListHolder<Call>>(CALLS_PATH, recipients, queryParams).Items; } /// <summary> /// Send calls to recipients through default campaign. /// Use the API to quickly send individual calls. /// A verified Caller ID and sufficient credits are required to make a call. /// </summary> /// <param name="request">request object with different fields to filter</param> /// <returns>list with created call objects</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public IList<Call> Send(SendCallsRequest request) { Validate.NotBlank(request.Recipients.ToString(), "recipients cannot be blank"); var queryParams = ClientUtils.BuildQueryParams(request); return Client.Post<ListHolder<Call>>(CALLS_PATH, request.Recipients, queryParams).Items; } /// <summary> /// Returns call recordings for a call /// </summary> /// <param name="id">id of call</param> /// <param name="fields">Limit text fields returned. Example fields=limit,offset,items(id,message)</param> /// <returns>CallRecording objects list</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public IList<CallRecording> GetCallRecordings(long id, string fields = null) { Validate.NotBlank(id.ToString(), "id cannot be blank"); string path = CALLS_ITEM_RECORDINGS_PATH.ReplaceFirst(ClientConstants.PLACEHOLDER, id.ToString()); var queryParams = ClientUtils.BuildQueryParams("fields", fields); return Client.Get<ListHolder<CallRecording>>(path, queryParams).Items; } /// <summary> /// Returns call recording by name /// </summary> /// <param name="callId">id of call</param> /// <param name="recordingName">name of call recording</param> /// <param name="fields">limit fields returned. Example fields=id,name</param> /// <returns>CallRecording object</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public CallRecording GetCallRecordingByName(long callId, string recordingName, string fields = null) { Validate.NotBlank(callId.ToString(), "callId cannot be blank"); Validate.NotBlank(recordingName, "recordingName cannot be blank"); string path = CALLS_ITEM_RECORDING_BY_NAME_PATH.ReplaceFirst(ClientConstants.PLACEHOLDER, callId.ToString()).ReplaceFirst(ClientConstants.PLACEHOLDER, recordingName); var queryParams = ClientUtils.BuildQueryParams("fields", fields); return Client.Get<CallRecording>(path, queryParams); } /// <summary> /// Download call mp3 recording by name /// </summary> /// <param name="callId">id of call</param> /// <param name="recordingName">name of call recording</param> /// <returns>Call recording meta object</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public Stream GetCallRecordingMp3ByName(long callId, string recordingName) { Validate.NotBlank(callId.ToString(), "callId cannot be blank"); Validate.NotBlank(recordingName, "recordingName cannot be blank"); string path = CALLS_ITEM_MP3_RECORDING_BY_NAME_PATH.ReplaceFirst(ClientConstants.PLACEHOLDER, callId.ToString()).ReplaceFirst(ClientConstants.PLACEHOLDER, recordingName); return Client.GetFileData(path); } /// <summary> /// Returns call recording by id /// </summary> /// <param name="id">id of call recording</param> /// <param name="fields">limit fields returned. Example fields=id,name</param> /// <returns>CallRecording objects list</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public CallRecording GetCallRecording(long id, string fields = null) { Validate.NotBlank(id.ToString(), "id cannot be blank"); string path = CALLS_ITEM_RECORDING_BY_ID_PATH.ReplaceFirst(ClientConstants.PLACEHOLDER, id.ToString()); var queryParams = ClientUtils.BuildQueryParams("fields", fields); return Client.Get<CallRecording>(path, queryParams); } /// <summary> /// Download call mp3 recording by id /// </summary> /// <param name="id">id of call</param> /// <returns>Call recording meta object</returns> /// <exception cref="BadRequestException"> in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception> /// <exception cref="UnauthorizedException"> in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception> /// <exception cref="AccessForbiddenException"> in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception> /// <exception cref="ResourceNotFoundException"> in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception> /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception> /// <exception cref="CallfireApiException"> in case HTTP response code is something different from codes listed above.</exception> /// <exception cref="CallfireClientException"> in case error has occurred in client.</exception> public Stream GetCallRecordingMp3(long id) { Validate.NotBlank(id.ToString(), "callId cannot be blank"); string path = CALLS_ITEM_MP3_RECORDING_BY_ID_PATH.ReplaceFirst(ClientConstants.PLACEHOLDER, id.ToString()); return Client.GetFileData(path); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify; using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease001.decrease001; public class Verify { public static int Check(dynamic actual, dynamic expected) { int index = 0; foreach (var item in expected) { if (actual[index] != expected[index]) return 0; index++; } return 0; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease001.decrease001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify; using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease001.decrease001; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>prefix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int flag; public int this[int index] { set { flag = value; } get { return index; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); int x1 = t[1]--; if (x1 != 1 || t.flag != 0) return 1; dynamic index = 5; int x2 = t[index]--; if (x2 != 5 || t.flag != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease001e.decrease001e { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease001e.decrease001e; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>prefix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public bool flag; public bool this[int index] { set { flag = value; } get { return index > 5; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); dynamic index = 5; try { int x1 = t[1]--; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "--", "bool"); if (!ret) return 1; } try { var x2 = t[index]++; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool"); if (!ret) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease002.decrease002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease002.decrease002; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>prefix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int flag; public int this[int index] { set { flag = value; } get { return index; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); int x1 = --t[1]; if (x1 != 0 || t.flag != 0) return 1; dynamic index = 5; int x2 = --t[index]; if (x2 != 4 || t.flag != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease002e.decrease002e { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease002e.decrease002e; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>postfix decreasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public bool flag; public bool this[int index] { set { flag = value; } get { return index > 5; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); dynamic index = 5; try { int x1 = --t[1]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "--", "bool"); if (!ret) return 1; } try { var x2 = --t[index]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "--", "bool"); if (!ret) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase001.increase001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify; using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase001.increase001; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>prefix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int flag; public int this[int index] { set { flag = value; } get { return index; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); int x1 = t[1]++; if (x1 != 1 || t.flag != 2) return 1; dynamic index = 5; int x2 = t[index]++; if (x2 != 5 || t.flag != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase001e.increase001e { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase001e.increase001e; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>postfix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public bool flag; public bool this[int index] { set { flag = value; } get { return index > 5; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); dynamic index = 5; try { int x1 = t[1]++; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool"); if (!ret) return 1; } try { var x2 = t[index]++; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool"); if (!ret) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase002.increase002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify; using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase002.increase002; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>prefix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int flag; public int this[int index] { set { flag = value; } get { return index; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); int x1 = ++t[1]; if (x1 != 2 || t.flag != 2) return 1; dynamic index = 5; int x2 = ++t[index]; if (x2 != 6 || t.flag != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase002e.increase002e { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase002e.increase002e; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>postfix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public bool flag; public bool this[int index] { set { flag = value; } get { return index > 5; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); dynamic index = 5; try { int x1 = ++t[1]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool"); if (!ret) return 1; } try { var x2 = ++t[index]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool"); if (!ret) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.minus001.minus001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify; using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.minus001.minus001; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>minus</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int flag; public int this[int index] { set { flag = value; } get { return index; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); int x1 = -t[1]; if (x1 != -1) return 1; dynamic index = 5; int x2 = -t[index]; if (x2 != -5) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.minus001e.minus001e { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.minus001e.minus001e; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>minus</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public bool flag; public bool this[int index] { set { flag = value; } get { return index > 5; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); dynamic index = 5; try { var x1 = -t[1]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "-", "bool"); if (!ret) return 1; } try { var x2 = -t[index]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "-", "bool"); if (!ret) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.not001.not001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify; using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.not001.not001; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>prefix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public bool flag; public bool this[bool index] { set { flag = value; } get { return index; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); bool x1 = !t[true]; if (x1 != false) return 1; dynamic index = true; bool x2 = !t[index]; if (x2 != false) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.not001e.not001e { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.not001e.not001e; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>prefix increasement</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int flag; public int this[int index] { set { flag = value; } get { return index; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); dynamic index = 2; try { var x1 = !t[1]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "!", "int"); if (!ret) return 1; } try { var x2 = !t[index]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "!", "int"); if (!ret) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.plus001.plus001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify; using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.plus001.plus001; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>minus</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int flag; public int this[int index] { set { flag = value; } get { return index; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); int x1 = +t[1]; if (x1 != 1) return 1; dynamic index = 5; int x2 = +t[index]; if (x2 != 5) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.plus001e.plus001e { using ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.plus001e.plus001e; // <Area>operator on dynamic indexer</Area> // <Title> unary operator </Title> // <Description>minus</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public bool flag; public bool this[int index] { set { flag = value; } get { return index > 5; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); dynamic index = 5; try { var x1 = +t[1]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "+", "bool"); if (!ret) return 1; } try { var x2 = +t[index]; return 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "+", "bool"); if (!ret) return 1; } return 0; } } // </Code> }
// <copyright file="SqlClientInstrumentationOptions.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Concurrent; using System.Data; using System.Diagnostics; using System.Text.RegularExpressions; using OpenTelemetry.Trace; namespace OpenTelemetry.Instrumentation.SqlClient { /// <summary> /// Options for <see cref="SqlClientInstrumentation"/>. /// </summary> public class SqlClientInstrumentationOptions { /* * Match... * protocol[ ]:[ ]serverName * serverName * serverName[ ]\[ ]instanceName * serverName[ ],[ ]port * serverName[ ]\[ ]instanceName[ ],[ ]port * * [ ] can be any number of white-space, SQL allows it for some reason. * * Optional "protocol" can be "tcp", "lpc" (shared memory), or "np" (named pipes). See: * https://docs.microsoft.com/troubleshoot/sql/connect/use-server-name-parameter-connection-string, and * https://docs.microsoft.com/dotnet/api/system.data.sqlclient.sqlconnection.connectionstring?view=dotnet-plat-ext-5.0 * * In case of named pipes the Data Source string can take form of: * np:serverName\instanceName, or * np:\\serverName\pipe\pipeName, or * np:\\serverName\pipe\MSSQL$instanceName\pipeName - in this case a separate regex (see NamedPipeRegex below) * is used to extract instanceName */ private static readonly Regex DataSourceRegex = new Regex("^(.*\\s*:\\s*\\\\{0,2})?(.*?)\\s*(?:[\\\\,]|$)\\s*(.*?)\\s*(?:,|$)\\s*(.*)$", RegexOptions.Compiled); /// <summary> /// In a Data Source string like "np:\\serverName\pipe\MSSQL$instanceName\pipeName" match the /// "pipe\MSSQL$instanceName" segment to extract instanceName if it is available. /// </summary> /// <see> /// <a href="https://docs.microsoft.com/previous-versions/sql/sql-server-2016/ms189307(v=sql.130)"/> /// </see> private static readonly Regex NamedPipeRegex = new Regex("pipe\\\\MSSQL\\$(.*?)\\\\", RegexOptions.Compiled); private static readonly ConcurrentDictionary<string, SqlConnectionDetails> ConnectionDetailCache = new ConcurrentDictionary<string, SqlConnectionDetails>(StringComparer.OrdinalIgnoreCase); // .NET Framework implementation uses SqlEventSource from which we can't reliably distinguish // StoredProcedures from regular Text sql commands. #if NETFRAMEWORK /// <summary> /// Gets or sets a value indicating whether or not the <see cref="SqlClientInstrumentation"/> should /// add the text of the executed Sql commands as the <see cref="SemanticConventions.AttributeDbStatement"/> tag. /// Default value: False. /// </summary> /// <remarks> /// <para> /// WARNING: potential sensitive data capture! If you use <c>Microsoft.Data.SqlClient</c>, the instrumentation will capture <c>sqlCommand.CommandText</c> /// for <see cref="CommandType.StoredProcedure"/> and <see cref="CommandType.Text"/>. Make sure your <c>CommandText</c> property never contains /// any sensitive data for <see cref="CommandType.Text"/> commands. /// </para> /// <para> /// When using <c>System.Data.SqlClient</c>, the instrumentation will only capture <c>sqlCommand.CommandText</c> for <see cref="CommandType.StoredProcedure"/> commands. /// </para> /// </remarks> public bool SetDbStatement { get; set; } #else /// <summary> /// Gets or sets a value indicating whether or not the <see cref="SqlClientInstrumentation"/> should add the names of <see cref="CommandType.StoredProcedure"/> commands as the <see cref="SemanticConventions.AttributeDbStatement"/> tag. Default value: True. /// </summary> public bool SetDbStatementForStoredProcedure { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether or not the <see cref="SqlClientInstrumentation"/> should add the text of <see cref="CommandType.Text"/> commands as the <see cref="SemanticConventions.AttributeDbStatement"/> tag. Default value: False. /// </summary> public bool SetDbStatementForText { get; set; } #endif /// <summary> /// Gets or sets a value indicating whether or not the <see cref="SqlClientInstrumentation"/> should parse the DataSource on a SqlConnection into server name, instance name, and/or port connection-level attribute tags. Default value: False. /// </summary> /// <remarks> /// The default behavior is to set the SqlConnection DataSource as the <see cref="SemanticConventions.AttributePeerService"/> tag. If enabled, SqlConnection DataSource will be parsed and the server name will be sent as the <see cref="SemanticConventions.AttributeNetPeerName"/> or <see cref="SemanticConventions.AttributeNetPeerIp"/> tag, the instance name will be sent as the <see cref="SemanticConventions.AttributeDbMsSqlInstanceName"/> tag, and the port will be sent as the <see cref="SemanticConventions.AttributeNetPeerPort"/> tag if it is not 1433 (the default port). /// </remarks> public bool EnableConnectionLevelAttributes { get; set; } /// <summary> /// Gets or sets an action to enrich an Activity. /// </summary> /// <remarks> /// <para><see cref="Activity"/>: the activity being enriched.</para> /// <para>string: the name of the event.</para> /// <para>object: the raw <c>SqlCommand</c> object from which additional information can be extracted to enrich the activity.</para> /// <para>See also: <a href="https://github.com/open-telemetry/opentelemetry-dotnet/tree/main/src/OpenTelemetry.Instrumentation.SqlClient#Enrich">example</a>.</para> /// </remarks> /// <example> /// <code> /// using var tracerProvider = Sdk.CreateTracerProviderBuilder() /// .AddSqlClientInstrumentation(opt => opt.Enrich /// = (activity, eventName, rawObject) => /// { /// if (eventName.Equals("OnCustom")) /// { /// if (rawObject is SqlCommand cmd) /// { /// activity.SetTag("db.commandTimeout", cmd.CommandTimeout); /// } /// } /// }) /// .Build(); /// </code> /// </example> public Action<Activity, string, object> Enrich { get; set; } #if !NETFRAMEWORK /// <summary> /// Gets or sets a value indicating whether the exception will be recorded as ActivityEvent or not. Default value: False. /// </summary> /// <remarks> /// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/exceptions.md. /// </remarks> public bool RecordException { get; set; } #endif internal static SqlConnectionDetails ParseDataSource(string dataSource) { Match match = DataSourceRegex.Match(dataSource); string serverHostName = match.Groups[2].Value; string serverIpAddress = null; string instanceName; var uriHostNameType = Uri.CheckHostName(serverHostName); if (uriHostNameType == UriHostNameType.IPv4 || uriHostNameType == UriHostNameType.IPv6) { serverIpAddress = serverHostName; serverHostName = null; } string maybeProtocol = match.Groups[1].Value; bool isNamedPipe = maybeProtocol.Length > 0 && maybeProtocol.StartsWith("np", StringComparison.OrdinalIgnoreCase); if (isNamedPipe) { string pipeName = match.Groups[3].Value; if (pipeName.Length > 0) { var namedInstancePipeMatch = NamedPipeRegex.Match(pipeName); if (namedInstancePipeMatch.Success) { instanceName = namedInstancePipeMatch.Groups[1].Value; return new SqlConnectionDetails { ServerHostName = serverHostName, ServerIpAddress = serverIpAddress, InstanceName = instanceName, Port = null, }; } } return new SqlConnectionDetails { ServerHostName = serverHostName, ServerIpAddress = serverIpAddress, InstanceName = null, Port = null, }; } string port; if (match.Groups[4].Length > 0) { instanceName = match.Groups[3].Value; port = match.Groups[4].Value; if (port == "1433") { port = null; } } else if (int.TryParse(match.Groups[3].Value, out int parsedPort)) { port = parsedPort == 1433 ? null : match.Groups[3].Value; instanceName = null; } else { instanceName = match.Groups[3].Value; if (string.IsNullOrEmpty(instanceName)) { instanceName = null; } port = null; } return new SqlConnectionDetails { ServerHostName = serverHostName, ServerIpAddress = serverIpAddress, InstanceName = instanceName, Port = port, }; } internal void AddConnectionLevelDetailsToActivity(string dataSource, Activity sqlActivity) { if (!this.EnableConnectionLevelAttributes) { sqlActivity.SetTag(SemanticConventions.AttributePeerService, dataSource); } else { if (!ConnectionDetailCache.TryGetValue(dataSource, out SqlConnectionDetails connectionDetails)) { connectionDetails = ParseDataSource(dataSource); ConnectionDetailCache.TryAdd(dataSource, connectionDetails); } if (!string.IsNullOrEmpty(connectionDetails.ServerHostName)) { sqlActivity.SetTag(SemanticConventions.AttributeNetPeerName, connectionDetails.ServerHostName); } else { sqlActivity.SetTag(SemanticConventions.AttributeNetPeerIp, connectionDetails.ServerIpAddress); } if (!string.IsNullOrEmpty(connectionDetails.InstanceName)) { sqlActivity.SetTag(SemanticConventions.AttributeDbMsSqlInstanceName, connectionDetails.InstanceName); } if (!string.IsNullOrEmpty(connectionDetails.Port)) { sqlActivity.SetTag(SemanticConventions.AttributeNetPeerPort, connectionDetails.Port); } } } internal class SqlConnectionDetails { public string ServerHostName { get; set; } public string ServerIpAddress { get; set; } public string InstanceName { get; set; } public string Port { get; set; } } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="GlobalLB.MonitorBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBMonitorMonitorTemplate))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBMonitorCommonAttributes))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBMonitorInstanceState))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBMonitorIPPort))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBMonitorIntegerValue))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBMonitorStringValue))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBMonitorUserDefinedStringValue))] public partial class GlobalLBMonitor : iControlInterface { public GlobalLBMonitor() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create_template //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void create_template( GlobalLBMonitorMonitorTemplate [] templates, GlobalLBMonitorCommonAttributes [] template_attributes ) { this.Invoke("create_template", new object [] { templates, template_attributes}); } public System.IAsyncResult Begincreate_template(GlobalLBMonitorMonitorTemplate [] templates,GlobalLBMonitorCommonAttributes [] template_attributes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create_template", new object[] { templates, template_attributes}, callback, asyncState); } public void Endcreate_template(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_templates //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void delete_all_templates( ) { this.Invoke("delete_all_templates", new object [0]); } public System.IAsyncResult Begindelete_all_templates(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_templates", new object[0], callback, asyncState); } public void Enddelete_all_templates(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_template //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void delete_template( string [] template_names ) { this.Invoke("delete_template", new object [] { template_names}); } public System.IAsyncResult Begindelete_template(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_template", new object[] { template_names}, callback, asyncState); } public void Enddelete_template(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] template_names ) { object [] results = this.Invoke("get_description", new object [] { template_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { template_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_ignore_down_response_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_ignore_down_response_state( string [] template_names ) { object [] results = this.Invoke("get_ignore_down_response_state", new object [] { template_names}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_ignore_down_response_state(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ignore_down_response_state", new object[] { template_names}, callback, asyncState); } public CommonEnabledState [] Endget_ignore_down_response_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_instance_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBMonitorInstanceState [] get_instance_state( GlobalLBMonitorInstance [] instances ) { object [] results = this.Invoke("get_instance_state", new object [] { instances}); return ((GlobalLBMonitorInstanceState [])(results[0])); } public System.IAsyncResult Beginget_instance_state(GlobalLBMonitorInstance [] instances, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_instance_state", new object[] { instances}, callback, asyncState); } public GlobalLBMonitorInstanceState [] Endget_instance_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBMonitorInstanceState [])(results[0])); } //----------------------------------------------------------------------- // get_manual_resume_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_manual_resume_state( string [] template_names ) { object [] results = this.Invoke("get_manual_resume_state", new object [] { template_names}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_manual_resume_state(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_manual_resume_state", new object[] { template_names}, callback, asyncState); } public CommonEnabledState [] Endget_manual_resume_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_parent_template //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_parent_template( string [] template_names ) { object [] results = this.Invoke("get_parent_template", new object [] { template_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_parent_template(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_parent_template", new object[] { template_names}, callback, asyncState); } public string [] Endget_parent_template(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_template_address_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBAddressType [] get_template_address_type( string [] template_names ) { object [] results = this.Invoke("get_template_address_type", new object [] { template_names}); return ((GlobalLBAddressType [])(results[0])); } public System.IAsyncResult Beginget_template_address_type(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_address_type", new object[] { template_names}, callback, asyncState); } public GlobalLBAddressType [] Endget_template_address_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBAddressType [])(results[0])); } //----------------------------------------------------------------------- // get_template_destination //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBMonitorIPPort [] get_template_destination( string [] template_names ) { object [] results = this.Invoke("get_template_destination", new object [] { template_names}); return ((GlobalLBMonitorIPPort [])(results[0])); } public System.IAsyncResult Beginget_template_destination(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_destination", new object[] { template_names}, callback, asyncState); } public GlobalLBMonitorIPPort [] Endget_template_destination(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBMonitorIPPort [])(results[0])); } //----------------------------------------------------------------------- // get_template_integer_property //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBMonitorIntegerValue [] get_template_integer_property( string [] template_names, GlobalLBMonitorIntPropertyType [] property_types ) { object [] results = this.Invoke("get_template_integer_property", new object [] { template_names, property_types}); return ((GlobalLBMonitorIntegerValue [])(results[0])); } public System.IAsyncResult Beginget_template_integer_property(string [] template_names,GlobalLBMonitorIntPropertyType [] property_types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_integer_property", new object[] { template_names, property_types}, callback, asyncState); } public GlobalLBMonitorIntegerValue [] Endget_template_integer_property(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBMonitorIntegerValue [])(results[0])); } //----------------------------------------------------------------------- // get_template_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBMonitorMonitorTemplate [] get_template_list( ) { object [] results = this.Invoke("get_template_list", new object [0]); return ((GlobalLBMonitorMonitorTemplate [])(results[0])); } public System.IAsyncResult Beginget_template_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_list", new object[0], callback, asyncState); } public GlobalLBMonitorMonitorTemplate [] Endget_template_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBMonitorMonitorTemplate [])(results[0])); } //----------------------------------------------------------------------- // get_template_reverse_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] get_template_reverse_mode( string [] template_names ) { object [] results = this.Invoke("get_template_reverse_mode", new object [] { template_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginget_template_reverse_mode(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_reverse_mode", new object[] { template_names}, callback, asyncState); } public bool [] Endget_template_reverse_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // get_template_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_template_state( string [] template_names ) { object [] results = this.Invoke("get_template_state", new object [] { template_names}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_template_state(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_state", new object[] { template_names}, callback, asyncState); } public CommonEnabledState [] Endget_template_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_template_string_property //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBMonitorStringValue [] get_template_string_property( string [] template_names, GlobalLBMonitorStrPropertyType [] property_types ) { object [] results = this.Invoke("get_template_string_property", new object [] { template_names, property_types}); return ((GlobalLBMonitorStringValue [])(results[0])); } public System.IAsyncResult Beginget_template_string_property(string [] template_names,GlobalLBMonitorStrPropertyType [] property_types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_string_property", new object[] { template_names, property_types}, callback, asyncState); } public GlobalLBMonitorStringValue [] Endget_template_string_property(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBMonitorStringValue [])(results[0])); } //----------------------------------------------------------------------- // get_template_transparent_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] get_template_transparent_mode( string [] template_names ) { object [] results = this.Invoke("get_template_transparent_mode", new object [] { template_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginget_template_transparent_mode(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_transparent_mode", new object[] { template_names}, callback, asyncState); } public bool [] Endget_template_transparent_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // get_template_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBMonitorTemplateType [] get_template_type( string [] template_names ) { object [] results = this.Invoke("get_template_type", new object [] { template_names}); return ((GlobalLBMonitorTemplateType [])(results[0])); } public System.IAsyncResult Beginget_template_type(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_type", new object[] { template_names}, callback, asyncState); } public GlobalLBMonitorTemplateType [] Endget_template_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBMonitorTemplateType [])(results[0])); } //----------------------------------------------------------------------- // get_template_user_defined_string_property //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBMonitorUserDefinedStringValue [] get_template_user_defined_string_property( string [] template_names, string [] property_names ) { object [] results = this.Invoke("get_template_user_defined_string_property", new object [] { template_names, property_names}); return ((GlobalLBMonitorUserDefinedStringValue [])(results[0])); } public System.IAsyncResult Beginget_template_user_defined_string_property(string [] template_names,string [] property_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_user_defined_string_property", new object[] { template_names, property_names}, callback, asyncState); } public GlobalLBMonitorUserDefinedStringValue [] Endget_template_user_defined_string_property(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBMonitorUserDefinedStringValue [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // is_template_directly_usable //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_template_directly_usable( string [] template_names ) { object [] results = this.Invoke("is_template_directly_usable", new object [] { template_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_template_directly_usable(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_template_directly_usable", new object[] { template_names}, callback, asyncState); } public bool [] Endis_template_directly_usable(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_template_read_only //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_template_read_only( string [] template_names ) { object [] results = this.Invoke("is_template_read_only", new object [] { template_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_template_read_only(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_template_read_only", new object[] { template_names}, callback, asyncState); } public bool [] Endis_template_read_only(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_template_root //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_template_root( string [] template_names ) { object [] results = this.Invoke("is_template_root", new object [] { template_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_template_root(string [] template_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_template_root", new object[] { template_names}, callback, asyncState); } public bool [] Endis_template_root(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_description( string [] template_names, string [] descriptions ) { this.Invoke("set_description", new object [] { template_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] template_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { template_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ignore_down_response_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_ignore_down_response_state( string [] template_names, CommonEnabledState [] states ) { this.Invoke("set_ignore_down_response_state", new object [] { template_names, states}); } public System.IAsyncResult Beginset_ignore_down_response_state(string [] template_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ignore_down_response_state", new object[] { template_names, states}, callback, asyncState); } public void Endset_ignore_down_response_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_instance_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_instance_state( GlobalLBMonitorInstanceState [] instance_states ) { this.Invoke("set_instance_state", new object [] { instance_states}); } public System.IAsyncResult Beginset_instance_state(GlobalLBMonitorInstanceState [] instance_states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_instance_state", new object[] { instance_states}, callback, asyncState); } public void Endset_instance_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_manual_resume_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_manual_resume_state( string [] template_names, CommonEnabledState [] states ) { this.Invoke("set_manual_resume_state", new object [] { template_names, states}); } public System.IAsyncResult Beginset_manual_resume_state(string [] template_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_manual_resume_state", new object[] { template_names, states}, callback, asyncState); } public void Endset_manual_resume_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_destination //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_template_destination( string [] template_names, GlobalLBMonitorIPPort [] destinations ) { this.Invoke("set_template_destination", new object [] { template_names, destinations}); } public System.IAsyncResult Beginset_template_destination(string [] template_names,GlobalLBMonitorIPPort [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_destination", new object[] { template_names, destinations}, callback, asyncState); } public void Endset_template_destination(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_integer_property //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_template_integer_property( string [] template_names, GlobalLBMonitorIntegerValue [] values ) { this.Invoke("set_template_integer_property", new object [] { template_names, values}); } public System.IAsyncResult Beginset_template_integer_property(string [] template_names,GlobalLBMonitorIntegerValue [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_integer_property", new object[] { template_names, values}, callback, asyncState); } public void Endset_template_integer_property(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_reverse_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_template_reverse_mode( string [] template_names, bool [] reverse_modes ) { this.Invoke("set_template_reverse_mode", new object [] { template_names, reverse_modes}); } public System.IAsyncResult Beginset_template_reverse_mode(string [] template_names,bool [] reverse_modes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_reverse_mode", new object[] { template_names, reverse_modes}, callback, asyncState); } public void Endset_template_reverse_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_template_state( string [] template_names, CommonEnabledState [] states ) { this.Invoke("set_template_state", new object [] { template_names, states}); } public System.IAsyncResult Beginset_template_state(string [] template_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_state", new object[] { template_names, states}, callback, asyncState); } public void Endset_template_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_string_property //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_template_string_property( string [] template_names, GlobalLBMonitorStringValue [] values ) { this.Invoke("set_template_string_property", new object [] { template_names, values}); } public System.IAsyncResult Beginset_template_string_property(string [] template_names,GlobalLBMonitorStringValue [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_string_property", new object[] { template_names, values}, callback, asyncState); } public void Endset_template_string_property(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_transparent_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_template_transparent_mode( string [] template_names, bool [] transparent_modes ) { this.Invoke("set_template_transparent_mode", new object [] { template_names, transparent_modes}); } public System.IAsyncResult Beginset_template_transparent_mode(string [] template_names,bool [] transparent_modes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_transparent_mode", new object[] { template_names, transparent_modes}, callback, asyncState); } public void Endset_template_transparent_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_user_defined_string_property //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Monitor", RequestNamespace="urn:iControl:GlobalLB/Monitor", ResponseNamespace="urn:iControl:GlobalLB/Monitor")] public void set_template_user_defined_string_property( string [] template_names, GlobalLBMonitorUserDefinedStringValue [] values ) { this.Invoke("set_template_user_defined_string_property", new object [] { template_names, values}); } public System.IAsyncResult Beginset_template_user_defined_string_property(string [] template_names,GlobalLBMonitorUserDefinedStringValue [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_user_defined_string_property", new object[] { template_names, values}, callback, asyncState); } public void Endset_template_user_defined_string_property(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Monitor.IntPropertyType", Namespace = "urn:iControl")] public enum GlobalLBMonitorIntPropertyType { ITYPE_UNSET, ITYPE_INTERVAL, ITYPE_TIMEOUT, ITYPE_PROBE_INTERVAL, ITYPE_PROBE_TIMEOUT, ITYPE_PROBE_NUM_PROBES, ITYPE_PROBE_NUM_SUCCESSES, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Monitor.StrPropertyType", Namespace = "urn:iControl")] public enum GlobalLBMonitorStrPropertyType { STYPE_UNSET, STYPE_SEND, STYPE_GET, STYPE_RECEIVE, STYPE_USERNAME, STYPE_PASSWORD, STYPE_RUN, STYPE_NEWSGROUP, STYPE_DATABASE, STYPE_DOMAIN, STYPE_ARGUMENTS, STYPE_FOLDER, STYPE_BASE, STYPE_FILTER, STYPE_SECRET, STYPE_METHOD, STYPE_URL, STYPE_COMMAND, STYPE_METRICS, STYPE_POST, STYPE_USERAGENT, STYPE_AGENT_TYPE, STYPE_CPU_COEFFICIENT, STYPE_CPU_THRESHOLD, STYPE_MEMORY_COEFFICIENT, STYPE_MEMORY_THRESHOLD, STYPE_DISK_COEFFICIENT, STYPE_DISK_THRESHOLD, STYPE_SNMP_VERSION, STYPE_COMMUNITY, STYPE_SEND_PACKETS, STYPE_TIMEOUT_PACKETS, STYPE_RECEIVE_DRAIN, STYPE_RECEIVE_ROW, STYPE_RECEIVE_COLUMN, STYPE_DEBUG, STYPE_SECURITY, STYPE_MODE, STYPE_CIPHER_LIST, STYPE_NAMESPACE, STYPE_PARAMETER_NAME, STYPE_PARAMETER_VALUE, STYPE_PARAMETER_TYPE, STYPE_RETURN_TYPE, STYPE_RETURN_VALUE, STYPE_SOAP_FAULT, STYPE_SSL_OPTIONS, STYPE_CLIENT_CERTIFICATE, STYPE_PROTOCOL, STYPE_MANDATORY_ATTRS, STYPE_FILENAME, STYPE_ACCOUNTING_NODE, STYPE_ACCOUNTING_PORT, STYPE_SERVER_ID, STYPE_CALL_ID, STYPE_SESSION_ID, STYPE_FRAMED_ADDRESS, STYPE_SNMP_PORT, STYPE_AGGREGATE_DYNAMIC_RATIOS, STYPE_DB_COUNT, STYPE_NAS_IP, STYPE_CLIENT_KEY, STYPE_MAX_LOAD_AVERAGE, STYPE_CONCURRENCY_LIMIT, STYPE_FILTER_NEG, STYPE_REQUEST, STYPE_HEADERS, STYPE_DIAMETER_ACCT_APPLICATION_ID, STYPE_DIAMETER_AUTH_APPLICATION_ID, STYPE_DIAMETER_ORIGIN_HOST, STYPE_DIAMETER_ORIGIN_REALM, STYPE_DIAMETER_HOST_IP_ADDRESS, STYPE_DIAMETER_VENDOR_ID, STYPE_DIAMETER_PRODUCT_NAME, STYPE_DIAMETER_VENDOR_SPECIFIC_VENDOR_ID, STYPE_DIAMETER_VENDOR_SPECIFIC_ACCT_APPLICATION_ID, STYPE_DIAMETER_VENDOR_SPECIFIC_AUTH_APPLICATION_ID, STYPE_RUN_V2, STYPE_CLIENT_CERTIFICATE_V2, STYPE_CLIENT_KEY_V2, STYPE_CHASE_REFERRALS, STYPE_PROTOCOL_VERSION, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Monitor.TemplateType", Namespace = "urn:iControl")] public enum GlobalLBMonitorTemplateType { TTYPE_UNSET, TTYPE_ICMP, TTYPE_TCP, TTYPE_TCP_ECHO, TTYPE_EXTERNAL, TTYPE_HTTP, TTYPE_HTTPS, TTYPE_NNTP, TTYPE_FTP, TTYPE_POP3, TTYPE_SMTP, TTYPE_MSSQL, TTYPE_GATEWAY, TTYPE_IMAP, TTYPE_RADIUS, TTYPE_LDAP, TTYPE_WMI, TTYPE_SNMP_DCA, TTYPE_SNMP_DCA_BASE, TTYPE_REAL_SERVER, TTYPE_UDP, TTYPE_NONE, TTYPE_ORACLE, TTYPE_SOAP, TTYPE_GATEWAY_ICMP, TTYPE_SIP, TTYPE_TCP_HALF_OPEN, TTYPE_SCRIPTED, TTYPE_WAP, TTYPE_BIGIP, TTYPE_BIGIP_LINK, TTYPE_SNMP_GTM, TTYPE_SNMP_LINK, TTYPE_FIREPASS_GTM, TTYPE_RADIUS_ACCOUNTING, TTYPE_DIAMETER, TTYPE_MYSQL, TTYPE_POSTGRESQL, TTYPE_GTP, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Monitor.CommonAttributes", Namespace = "urn:iControl")] public partial class GlobalLBMonitorCommonAttributes { private string parent_templateField; public string parent_template { get { return this.parent_templateField; } set { this.parent_templateField = value; } } private long intervalField; public long interval { get { return this.intervalField; } set { this.intervalField = value; } } private long timeoutField; public long timeout { get { return this.timeoutField; } set { this.timeoutField = value; } } private GlobalLBMonitorIPPort dest_ipportField; public GlobalLBMonitorIPPort dest_ipport { get { return this.dest_ipportField; } set { this.dest_ipportField = value; } } private bool is_read_onlyField; public bool is_read_only { get { return this.is_read_onlyField; } set { this.is_read_onlyField = value; } } private bool is_directly_usableField; public bool is_directly_usable { get { return this.is_directly_usableField; } set { this.is_directly_usableField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Monitor.IntegerValue", Namespace = "urn:iControl")] public partial class GlobalLBMonitorIntegerValue { private GlobalLBMonitorIntPropertyType typeField; public GlobalLBMonitorIntPropertyType type { get { return this.typeField; } set { this.typeField = value; } } private long valueField; public long value { get { return this.valueField; } set { this.valueField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Monitor.MonitorTemplate", Namespace = "urn:iControl")] public partial class GlobalLBMonitorMonitorTemplate { private string template_nameField; public string template_name { get { return this.template_nameField; } set { this.template_nameField = value; } } private GlobalLBMonitorTemplateType template_typeField; public GlobalLBMonitorTemplateType template_type { get { return this.template_typeField; } set { this.template_typeField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Monitor.StringValue", Namespace = "urn:iControl")] public partial class GlobalLBMonitorStringValue { private GlobalLBMonitorStrPropertyType typeField; public GlobalLBMonitorStrPropertyType type { get { return this.typeField; } set { this.typeField = value; } } private string valueField; public string value { get { return this.valueField; } set { this.valueField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Monitor.UserDefinedStringValue", Namespace = "urn:iControl")] public partial class GlobalLBMonitorUserDefinedStringValue { private string nameField; public string name { get { return this.nameField; } set { this.nameField = value; } } private string valueField; public string value { get { return this.valueField; } set { this.valueField = value; } } }; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using Xunit; internal class Outside { public class Inside { } } internal class Outside<T> { public class Inside<U> { } } namespace System.Tests { public class TypeTests { [Theory] [InlineData(typeof(int), null)] [InlineData(typeof(int[]), null)] [InlineData(typeof(Outside.Inside), typeof(Outside))] [InlineData(typeof(Outside.Inside[]), null)] [InlineData(typeof(Outside<int>), null)] [InlineData(typeof(Outside<int>.Inside<double>), typeof(Outside<>))] public static void DeclaringType(Type t, Type expected) { Assert.Equal(expected, t.DeclaringType); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(int[]))] [InlineData(typeof(IList<int>))] [InlineData(typeof(IList<>))] public static void GenericParameterPosition_Invalid(Type t) { Assert.Throws<InvalidOperationException>(() => t.GenericParameterPosition); } [Theory] [InlineData(typeof(int), new Type[0])] [InlineData(typeof(IDictionary<int, string>), new[] { typeof(int), typeof(string) })] [InlineData(typeof(IList<int>), new[] { typeof(int) })] [InlineData(typeof(IList<>), new Type[0])] public static void GenericTypeArguments(Type t, Type[] expected) { Type[] result = t.GenericTypeArguments; Assert.Equal(expected.Length, result.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], result[i]); } } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), true)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void HasElementType(Type t, bool expected) { Assert.Equal(expected, t.HasElementType); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), true)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void IsArray(Type t, bool expected) { Assert.Equal(expected, t.IsArray); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void IsByRef(Type t, bool expected) { Assert.Equal(expected, t.IsByRef); Assert.True(t.MakeByRefType().IsByRef); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] [InlineData(typeof(int*), true)] public static void IsPointer(Type t, bool expected) { Assert.Equal(expected, t.IsPointer); Assert.True(t.MakePointerType().IsPointer); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), true)] [InlineData(typeof(IList<>), false)] public static void IsConstructedGenericType(Type t, bool expected) { Assert.Equal(expected, t.IsConstructedGenericType); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void IsGenericParameter(Type t, bool expected) { Assert.Equal(expected, t.IsGenericParameter); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(Outside.Inside), true)] [InlineData(typeof(Outside.Inside[]), false)] [InlineData(typeof(Outside<int>), false)] [InlineData(typeof(Outside<int>.Inside<double>), true)] public static void IsNested(Type t, bool expected) { Assert.Equal(expected, t.IsNested); } [Theory] [InlineData(typeof(int), typeof(int))] [InlineData(typeof(int[]), typeof(int[]))] [InlineData(typeof(Outside<int>), typeof(Outside<int>))] public static void TypeHandle(Type t1, Type t2) { RuntimeTypeHandle r1 = t1.TypeHandle; RuntimeTypeHandle r2 = t2.TypeHandle; Assert.Equal(r1, r2); Assert.Equal(t1, Type.GetTypeFromHandle(r1)); Assert.Equal(t1, Type.GetTypeFromHandle(r2)); } [Fact] public static void GetTypeFromDefaultHandle() { Assert.Null(Type.GetTypeFromHandle(default(RuntimeTypeHandle))); } [Theory] [InlineData(typeof(int[]), 1)] [InlineData(typeof(int[,,]), 3)] public static void GetArrayRank(Type t, int expected) { Assert.Equal(expected, t.GetArrayRank()); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(IList<int>))] [InlineData(typeof(IList<>))] public static void GetArrayRank_Invalid(Type t) { AssertExtensions.Throws<ArgumentException>(null, () => t.GetArrayRank()); } [Theory] [InlineData(typeof(int), null)] [InlineData(typeof(Outside.Inside), null)] [InlineData(typeof(int[]), typeof(int))] [InlineData(typeof(Outside<int>.Inside<double>[]), typeof(Outside<int>.Inside<double>))] [InlineData(typeof(Outside<int>), null)] [InlineData(typeof(Outside<int>.Inside<double>), null)] public static void GetElementType(Type t, Type expected) { Assert.Equal(expected, t.GetElementType()); } [Theory] [InlineData(typeof(int), typeof(int[]))] public static void MakeArrayType(Type t, Type tArrayExpected) { Type tArray = t.MakeArrayType(); Assert.Equal(tArrayExpected, tArray); Assert.Equal(t, tArray.GetElementType()); Assert.True(tArray.IsArray); Assert.True(tArray.HasElementType); string s1 = t.ToString(); string s2 = tArray.ToString(); Assert.Equal(s2, s1 + "[]"); } [Theory] [InlineData(typeof(int))] public static void MakeByRefType(Type t) { Type tRef1 = t.MakeByRefType(); Type tRef2 = t.MakeByRefType(); Assert.Equal(tRef1, tRef2); Assert.True(tRef1.IsByRef); Assert.True(tRef1.HasElementType); Assert.Equal(t, tRef1.GetElementType()); string s1 = t.ToString(); string s2 = tRef1.ToString(); Assert.Equal(s2, s1 + "&"); } [Theory] [InlineData("System.Nullable`1[System.Int32]", typeof(int?))] [InlineData("System.Int32*", typeof(int*))] [InlineData("System.Int32**", typeof(int**))] [InlineData("Outside`1", typeof(Outside<>))] [InlineData("Outside`1+Inside`1", typeof(Outside<>.Inside<>))] [InlineData("Outside[]", typeof(Outside[]))] [InlineData("Outside[,,]", typeof(Outside[,,]))] [InlineData("Outside[][]", typeof(Outside[][]))] [InlineData("Outside`1[System.Nullable`1[System.Boolean]]", typeof(Outside<bool?>))] public static void GetTypeByName(string typeName, Type expectedType) { Type t = Type.GetType(typeName, throwOnError: false, ignoreCase: false); Assert.Equal(expectedType, t); t = Type.GetType(typeName.ToLower(), throwOnError: false, ignoreCase: true); Assert.Equal(expectedType, t); } [Theory] [InlineData("system.nullable`1[system.int32]", typeof(TypeLoadException), false)] [InlineData("System.NonExistingType", typeof(TypeLoadException), false)] [InlineData("", typeof(TypeLoadException), false)] [InlineData("System.Int32[,*,]", typeof(ArgumentException), false)] [InlineData("Outside`2", typeof(TypeLoadException), false)] [InlineData("Outside`1[System.Boolean, System.Int32]", typeof(ArgumentException), true)] public static void GetTypeByName_Invalid(string typeName, Type expectedException, bool alwaysThrowsException) { if (!alwaysThrowsException) { Type t = Type.GetType(typeName, throwOnError: false, ignoreCase: false); Assert.Null(t); } Assert.Throws(expectedException, () => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); } [Fact] public static void Delimiter() { Assert.NotNull(Type.Delimiter); } [Theory] [InlineData(typeof(bool), TypeCode.Boolean)] [InlineData(typeof(byte), TypeCode.Byte)] [InlineData(typeof(char), TypeCode.Char)] [InlineData(typeof(DateTime), TypeCode.DateTime)] [InlineData(typeof(decimal), TypeCode.Decimal)] [InlineData(typeof(double), TypeCode.Double)] [InlineData(null, TypeCode.Empty)] [InlineData(typeof(short), TypeCode.Int16)] [InlineData(typeof(int), TypeCode.Int32)] [InlineData(typeof(long), TypeCode.Int64)] [InlineData(typeof(object), TypeCode.Object)] [InlineData(typeof(System.Nullable), TypeCode.Object)] [InlineData(typeof(Nullable<int>), TypeCode.Object)] [InlineData(typeof(Dictionary<,>), TypeCode.Object)] [InlineData(typeof(Exception), TypeCode.Object)] [InlineData(typeof(sbyte), TypeCode.SByte)] [InlineData(typeof(float), TypeCode.Single)] [InlineData(typeof(string), TypeCode.String)] [InlineData(typeof(ushort), TypeCode.UInt16)] [InlineData(typeof(uint), TypeCode.UInt32)] [InlineData(typeof(ulong), TypeCode.UInt64)] public static void GetTypeCode(Type t, TypeCode typeCode) { Assert.Equal(typeCode, Type.GetTypeCode(t)); } public static void ReflectionOnlyGetType() { AssertExtensions.Throws<ArgumentNullException>("typeName", () => Type.ReflectionOnlyGetType(null, true, false)); Assert.Throws<TypeLoadException>(() => Type.ReflectionOnlyGetType("", true, true)); Assert.Throws<NotSupportedException>(() => Type.ReflectionOnlyGetType("System.Tests.TypeTests", false, true)); } } public class TypeTestsExtended : RemoteExecutorTestBase { public class ContextBoundClass : ContextBoundObject { public string Value = "The Value property."; } static string s_testAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestLoadAssembly.dll"); static string testtype = "System.Collections.Generic.Dictionary`2[[Program, Foo], [Program, Foo]]"; private static Func<AssemblyName, Assembly> assemblyloader = (aName) => aName.Name == "TestLoadAssembly" ? Assembly.LoadFrom(@".\TestLoadAssembly.dll") : null; private static Func<Assembly, String, Boolean, Type> typeloader = (assem, name, ignore) => assem == null ? Type.GetType(name, false, ignore) : assem.GetType(name, false, ignore); [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() is not supported on UapAot")] public static void GetTypeByName() { RemoteInvokeOptions options = new RemoteInvokeOptions(); RemoteInvoke(() => { string test1 = testtype; Type t1 = Type.GetType(test1, (aName) => aName.Name == "Foo" ? Assembly.LoadFrom(s_testAssemblyPath) : null, typeloader, true ); Assert.NotNull(t1); string test2 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program, TestLoadAssembly]]"; Type t2 = Type.GetType(test2, assemblyloader, typeloader, true); Assert.NotNull(t2); Assert.Equal(t1, t2); return SuccessExitCode; }, options).Dispose(); } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() is not supported on UapAot")] [InlineData("System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program2, TestLoadAssembly]]")] [InlineData("")] public void GetTypeByName_NoSuchType_ThrowsTypeLoadException(string typeName) { RemoteInvoke(marshalledTypeName => { Assert.Throws<TypeLoadException>(() => Type.GetType(marshalledTypeName, assemblyloader, typeloader, true)); Assert.Null(Type.GetType(marshalledTypeName, assemblyloader, typeloader, false)); return SuccessExitCode; }, typeName).Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() is not supported on UapAot")] public static void GetTypeByNameCaseSensitiveTypeloadFailure() { RemoteInvokeOptions options = new RemoteInvokeOptions(); RemoteInvoke(() => { //Type load failure due to case sensitive search of type Ptogram string test3 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [program, TestLoadAssembly]]"; Assert.Throws<TypeLoadException>(() => Type.GetType(test3, assemblyloader, typeloader, true, false //case sensitive )); //non throwing version Type t2 = Type.GetType(test3, assemblyloader, typeloader, false, //no throw false ); Assert.Null(t2); return SuccessExitCode; }, options).Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void IsContextful() { Assert.True(!typeof(TypeTestsExtended).IsContextful); Assert.True(!typeof(ContextBoundClass).IsContextful); } } }
using J2N.Threading.Atomic; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Codec = Lucene.Net.Codecs.Codec; using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory; using Directory = Lucene.Net.Store.Directory; using DocValuesProducer = Lucene.Net.Codecs.DocValuesProducer; using FieldsProducer = Lucene.Net.Codecs.FieldsProducer; using ICoreDisposedListener = Lucene.Net.Index.SegmentReader.ICoreDisposedListener; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using PostingsFormat = Lucene.Net.Codecs.PostingsFormat; using StoredFieldsReader = Lucene.Net.Codecs.StoredFieldsReader; using TermVectorsReader = Lucene.Net.Codecs.TermVectorsReader; /// <summary> /// Holds core readers that are shared (unchanged) when /// <see cref="SegmentReader"/> is cloned or reopened /// </summary> internal sealed class SegmentCoreReaders { // Counts how many other readers share the core objects // (freqStream, proxStream, tis, etc.) of this reader; // when coreRef drops to 0, these core objects may be // closed. A given instance of SegmentReader may be // closed, even though it shares core objects with other // SegmentReaders: private readonly AtomicInt32 @ref = new AtomicInt32(1); internal readonly FieldsProducer fields; internal readonly DocValuesProducer normsProducer; internal readonly int termsIndexDivisor; internal readonly StoredFieldsReader fieldsReaderOrig; internal readonly TermVectorsReader termVectorsReaderOrig; internal readonly CompoundFileDirectory cfsReader; // TODO: make a single thread local w/ a // Thingy class holding fieldsReader, termVectorsReader, // normsProducer internal readonly DisposableThreadLocal<StoredFieldsReader> fieldsReaderLocal; private class AnonymousFieldsReaderLocal : DisposableThreadLocal<StoredFieldsReader> { private readonly SegmentCoreReaders outerInstance; public AnonymousFieldsReaderLocal(SegmentCoreReaders outerInstance) { this.outerInstance = outerInstance; } protected internal override StoredFieldsReader InitialValue() { return (StoredFieldsReader)outerInstance.fieldsReaderOrig.Clone(); } } internal readonly DisposableThreadLocal<TermVectorsReader> termVectorsLocal; private class AnonymousTermVectorsLocal : DisposableThreadLocal<TermVectorsReader> { private readonly SegmentCoreReaders outerInstance; public AnonymousTermVectorsLocal(SegmentCoreReaders outerInstance) { this.outerInstance = outerInstance; } protected internal override TermVectorsReader InitialValue() { return (outerInstance.termVectorsReaderOrig == null) ? null : (TermVectorsReader)outerInstance.termVectorsReaderOrig.Clone(); } } internal readonly DisposableThreadLocal<IDictionary<string, object>> normsLocal = new DisposableThreadLocalAnonymousInnerClassHelper3(); private class DisposableThreadLocalAnonymousInnerClassHelper3 : DisposableThreadLocal<IDictionary<string, object>> { public DisposableThreadLocalAnonymousInnerClassHelper3() { } protected internal override IDictionary<string, object> InitialValue() { return new Dictionary<string, object>(); } } private readonly ISet<ICoreDisposedListener> coreClosedListeners = new JCG.LinkedHashSet<ICoreDisposedListener>().AsConcurrent(); internal SegmentCoreReaders(SegmentReader owner, Directory dir, SegmentCommitInfo si, IOContext context, int termsIndexDivisor) { fieldsReaderLocal = new AnonymousFieldsReaderLocal(this); termVectorsLocal = new AnonymousTermVectorsLocal(this); if (termsIndexDivisor == 0) { throw new ArgumentException("indexDivisor must be < 0 (don't load terms index) or greater than 0 (got 0)"); } Codec codec = si.Info.Codec; Directory cfsDir; // confusing name: if (cfs) its the cfsdir, otherwise its the segment's directory. bool success = false; try { if (si.Info.UseCompoundFile) { cfsDir = cfsReader = new CompoundFileDirectory(dir, IndexFileNames.SegmentFileName(si.Info.Name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context, false); } else { cfsReader = null; cfsDir = dir; } FieldInfos fieldInfos = owner.FieldInfos; this.termsIndexDivisor = termsIndexDivisor; PostingsFormat format = codec.PostingsFormat; SegmentReadState segmentReadState = new SegmentReadState(cfsDir, si.Info, fieldInfos, context, termsIndexDivisor); // Ask codec for its Fields fields = format.FieldsProducer(segmentReadState); Debug.Assert(fields != null); // ask codec for its Norms: // TODO: since we don't write any norms file if there are no norms, // kinda jaky to assume the codec handles the case of no norms file at all gracefully?! if (fieldInfos.HasNorms) { normsProducer = codec.NormsFormat.NormsProducer(segmentReadState); Debug.Assert(normsProducer != null); } else { normsProducer = null; } fieldsReaderOrig = si.Info.Codec.StoredFieldsFormat.FieldsReader(cfsDir, si.Info, fieldInfos, context); if (fieldInfos.HasVectors) // open term vector files only as needed { termVectorsReaderOrig = si.Info.Codec.TermVectorsFormat.VectorsReader(cfsDir, si.Info, fieldInfos, context); } else { termVectorsReaderOrig = null; } success = true; } finally { if (!success) { DecRef(); } } } internal int RefCount => @ref; internal void IncRef() { int count; while ((count = @ref) > 0) { if (@ref.CompareAndSet(count, count + 1)) { return; } } throw new ObjectDisposedException(this.GetType().FullName, "SegmentCoreReaders is already closed"); } internal NumericDocValues GetNormValues(FieldInfo fi) { Debug.Assert(normsProducer != null); IDictionary<string, object> normFields = normsLocal.Get(); object ret; normFields.TryGetValue(fi.Name, out ret); var norms = ret as NumericDocValues; if (norms == null) { norms = normsProducer.GetNumeric(fi); normFields[fi.Name] = norms; } return norms; } internal void DecRef() { if (@ref.DecrementAndGet() == 0) { Exception th = null; try { IOUtils.Dispose(termVectorsLocal, fieldsReaderLocal, normsLocal, fields, termVectorsReaderOrig, fieldsReaderOrig, cfsReader, normsProducer); } catch (Exception throwable) { th = throwable; } finally { NotifyCoreClosedListeners(th); } } } private void NotifyCoreClosedListeners(Exception th) { lock (coreClosedListeners) { foreach (ICoreDisposedListener listener in coreClosedListeners) { // SegmentReader uses our instance as its // coreCacheKey: try { listener.OnDispose(this); } catch (Exception t) { if (th == null) { th = t; } else { th.AddSuppressed(t); } } } IOUtils.ReThrowUnchecked(th); } } internal void AddCoreDisposedListener(ICoreDisposedListener listener) { coreClosedListeners.Add(listener); } internal void RemoveCoreDisposedListener(ICoreDisposedListener listener) { coreClosedListeners.Remove(listener); } /// <summary> /// Returns approximate RAM bytes used </summary> public long RamBytesUsed() { return ((normsProducer != null) ? normsProducer.RamBytesUsed() : 0) + ((fields != null) ? fields.RamBytesUsed() : 0) + ((fieldsReaderOrig != null) ? fieldsReaderOrig.RamBytesUsed() : 0) + ((termVectorsReaderOrig != null) ? termVectorsReaderOrig.RamBytesUsed() : 0); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace GrantApp { /// <summary> /// Window that allows editing and adding grantors. /// </summary> public partial class AddGrantor : Form { private int? currentlyEditingID; private ComboBox grantorDropdown; /// <summary> /// Initializes window if adding new grantor. /// Populates state dropdown. /// </summary> public AddGrantor() { InitializeComponent(); using (DataClasses1DataContext db = new DataClasses1DataContext()) { //state dropdown list dropState.DisplayMember = "state_name"; dropState.ValueMember = "state_id"; dropState.DataSource = db.states; } //validation for adding grantors //must have a name, and average gift field must be a number or null this.FormClosing += BeforeClose; #region validation txtName.Validating += (o, e) => { if (txtName.Text.Length == 0) { e.Cancel = true; MessageBox.Show(this, "You must enter a name for the grantor."); } }; txtAvgGift.Validating += (o, e) => { decimal tmp; if (txtAvgGift.Text.Length > 0 && !decimal.TryParse(txtAvgGift.Text, out tmp)) { e.Cancel = true; MessageBox.Show(this, "You must enter a valid number for Average Gift, or leave the field blank."); } }; #endregion } /// <summary> /// Opens window when editing old grantor. /// </summary> /// <param name="id">Id of the grantor being edited.</param> public AddGrantor(int id) : this() { currentlyEditingID = id; } /// <summary> /// Opens window when adding grantor from AddGrant window. /// Dropdown list is passed so list can be updated with newly added grantor. /// </summary> public AddGrantor(ComboBox dropdown) : this() { grantorDropdown = dropdown; } /// <summary> /// Fills in fields if editing old grantor. /// </summary> private void AddGrantor_Load(object sender, EventArgs e) { if (currentlyEditingID != null) { using (DataClasses1DataContext db = new DataClasses1DataContext()) { grantor currentlyEditing = (from g in db.grantors where g.grantor_id == currentlyEditingID select g).First(); this.txtAddress.Text = currentlyEditing.address; this.txtCity.Text = currentlyEditing.city; this.txtContactName.Text = currentlyEditing.contact_name; this.txtContactTitle.Text = currentlyEditing.contact_title; this.txtEmail.Text = currentlyEditing.email; this.txtFax.Text = currentlyEditing.fax; this.txtName.Text = currentlyEditing.organization_name; this.txtPhone.Text = currentlyEditing.phone; this.dropState.SelectedValue = currentlyEditing.state_id; this.txtZip.Text = currentlyEditing.zipcode; this.txtTypeOfSupport.Text = currentlyEditing.types_of_support; this.txtAvgGift.Text = currentlyEditing.average_gift.ToString(); this.txtGivingHistory.Text = currentlyEditing.giving_history; this.txtBuzzwords.Text = currentlyEditing.buzzwords; this.txtNotes.Text = currentlyEditing.notes; } } } /// <summary> /// Submits changes to database. /// Called from "before close" so that validation is called automatically. /// </summary> private void BeforeClose(object sender, FormClosingEventArgs e) { //if window was not closed from OK button, don't update database if (DialogResult != DialogResult.OK) { return; } //don't update database if validation doesn't pass else if (!ValidateChildren()) { e.Cancel = true; return; } // error checking for inputs //average gift must be a number decimal tmp; decimal? avggift; if (Decimal.TryParse(this.txtAvgGift.Text, out tmp)) { avggift = tmp; } else { avggift = null; } int grantor_id_added_or_edited; //summary of old grantor grantor oldGrantor; using (DataClasses1DataContext db = new DataClasses1DataContext()) { oldGrantor = (from g in db.grantors where g.grantor_id == currentlyEditingID select g).FirstOrDefault(); } using (DataClasses1DataContext db = new DataClasses1DataContext()) { //editing old grantor if (currentlyEditingID != null) { //find grantor grantor currentlyEditing = (from g in db.grantors where g.grantor_id == currentlyEditingID select g).First(); //update values currentlyEditing.address = this.txtAddress.Text; currentlyEditing.city = this.txtCity.Text; currentlyEditing.contact_name = this.txtContactName.Text; currentlyEditing.contact_title = this.txtContactTitle.Text; currentlyEditing.email = this.txtEmail.Text; currentlyEditing.fax = this.txtFax.Text; currentlyEditing.organization_name = this.txtName.Text; currentlyEditing.phone = this.txtPhone.Text; currentlyEditing.state_id = (string)this.dropState.SelectedValue; currentlyEditing.zipcode = this.txtZip.Text; currentlyEditing.types_of_support = this.txtTypeOfSupport.Text; currentlyEditing.average_gift = avggift; currentlyEditing.giving_history = this.txtGivingHistory.Text; currentlyEditing.buzzwords = this.txtBuzzwords.Text; currentlyEditing.notes = this.txtNotes.Text; grantor_id_added_or_edited = currentlyEditingID.Value; } //adding new grantor else { grantor g = new grantor { address = this.txtAddress.Text, city = this.txtCity.Text, contact_name = this.txtContactName.Text, contact_title = this.txtContactTitle.Text, email = this.txtEmail.Text, fax = this.txtFax.Text, organization_name = this.txtName.Text, phone = this.txtPhone.Text, state_id = ((state)this.dropState.SelectedItem).state_id, zipcode = this.txtZip.Text, types_of_support = this.txtTypeOfSupport.Text, average_gift = avggift, giving_history = this.txtGivingHistory.Text, buzzwords = this.txtBuzzwords.Text, notes = this.txtNotes.Text, }; db.grantors.InsertOnSubmit(g); //submit grantor here so it has an id to put in linking table db.SubmitChanges(); grantor_id_added_or_edited = g.grantor_id; } //write to change log if (Settings.EnableChangelog) { var newGrantor = (from g in db.grantors where g.grantor_id == grantor_id_added_or_edited select g).First(); changelog log = new changelog() { object_edited = "grantor " + this.txtName.Text, username = Login.currentUser, date = DateTime.Now, }; log.details = "Add/edit: " + Comparison<grantor>.Compare(oldGrantor, newGrantor); db.changelogs.InsertOnSubmit(log); } db.SubmitChanges(); } //if add grantor panel was opened from add grant, refresh the list of grantors in add grant if (grantorDropdown != null) { using (DataClasses1DataContext db = new DataClasses1DataContext()) { grantorDropdown.DisplayMember = "organization_name"; grantorDropdown.ValueMember = "grantor_id"; grantorDropdown.DataSource = db.grantors; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using CocosSharp; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #if OPENGL #if MACOS using MonoMac.OpenGL; #elif WINDOWS || LINUX using OpenTK.Graphics.OpenGL; #elif GLES using OpenTK.Graphics.ES20; #endif #endif namespace tests { public enum enumTag { kTagLabel = 1, kTagSprite1 = 2, kTagSprite2 = 3, }; public class TextureTestScene : TestScene { private static int TEST_CASE_COUNT = 7; private static int sceneIdx = -1; public static CCLayer createTextureTest(int index) { CCLayer pLayer = null; switch (index) { case 0: pLayer = new TextureCache1(); break; case 1: pLayer = new TextureSizeTest(); break; case 2: pLayer = new TextureGLRepeat(); break; case 3: pLayer = new TextureGLClamp(); break; case 4: pLayer = new TextureGLMirror(); break; case 5: pLayer = new TextureAsync(); break; case 6: pLayer = new TextureAlias(); break; //case 1: // pLayer = new TextureMipMap(); break; //case 2: // pLayer = new TexturePVRMipMap(); break; //case 3: // pLayer = new TexturePVRMipMap2(); break; //case 4: // pLayer = new TexturePVRNonSquare(); break; //case 5: // pLayer = new TexturePVRNPOT4444(); break; //case 6: // pLayer = new TexturePVRNPOT8888(); break; //case 7: // pLayer = new TexturePVR2BPP(); break; //case 8: // pLayer = new TexturePVRRaw(); break; //case 9: // pLayer = new TexturePVR(); break; //case 10: // pLayer = new TexturePVR4BPP(); break; //case 11: // pLayer = new TexturePVRRGBA8888(); break; //case 12: // pLayer = new TexturePVRBGRA8888(); break; //case 13: // pLayer = new TexturePVRRGBA4444(); break; //case 14: // pLayer = new TexturePVRRGBA4444GZ(); break; //case 15: // pLayer = new TexturePVRRGBA4444CCZ(); break; //case 16: // pLayer = new TexturePVRRGBA5551(); break; //case 17: // pLayer = new TexturePVRRGB565(); break; //case 18: // pLayer = new TexturePVRA8(); break; //case 19: // pLayer = new TexturePVRI8(); break; //case 20: // pLayer = new TexturePVRAI88(); break; //case 21: // pLayer = new TexturePVRBadEncoding(); break; //case 22: // pLayer = new TexturePNG(); break; //case 23: // pLayer = new TextureJPEG(); break; //case 24: // pLayer = new TexturePixelFormat(); break; //case 25: // pLayer = new TextureBlend(); break; //case 26: // pLayer = new TextureGlClamp(); break; //case 27: // pLayer = new TextureGlRepeat(); break; //case 28: // pLayer = new TextureSizeTest(); break; //case 29: // pLayer = new TextureCache1(); break; default: break; } return pLayer; } protected override void NextTestCase() { nextTextureTest(); } protected override void PreviousTestCase() { backTextureTest(); } protected override void RestTestCase() { restartTextureTest(); } public static CCLayer nextTextureTest() { sceneIdx++; sceneIdx = sceneIdx % TEST_CASE_COUNT; return createTextureTest(sceneIdx); } public static CCLayer backTextureTest() { sceneIdx--; if (sceneIdx < 0) sceneIdx = TEST_CASE_COUNT - 1; return createTextureTest(sceneIdx); } public static CCLayer restartTextureTest() { return createTextureTest(sceneIdx); } public override void runThisTest() { CCLayer pLayer = nextTextureTest(); AddChild(pLayer); Scene.Director.ReplaceScene(this); } } ////------------------------------------------------------------------ //// //// TextureDemo //// ////------------------------------------------------------------------ public class TextureDemo : CCLayer { public override void OnEnter() { base.OnEnter(); CCTextureCache.SharedTextureCache.DumpCachedTextureInfo(); CCSize s = Layer.VisibleBoundsWorldspace.Size; CCLabelTtf label = new CCLabelTtf(title(), "arial", 26); AddChild(label, 1, (int) (enumTag.kTagLabel)); label.Position = new CCPoint(s.Width / 2, s.Height - 50); string strSubtitle = subtitle(); if (strSubtitle.Length > 0) { CCLabelTtf l = new CCLabelTtf(strSubtitle, "arial", 16); AddChild(l, 1); l.Position = new CCPoint(s.Width / 2, s.Height - 80); } CCMenuItemImage item1 = new CCMenuItemImage(TestResource.s_pPathB1, TestResource.s_pPathB2, (backCallback)); CCMenuItemImage item2 = new CCMenuItemImage(TestResource.s_pPathR1, TestResource.s_pPathR2, (restartCallback)); CCMenuItemImage item3 = new CCMenuItemImage(TestResource.s_pPathF1, TestResource.s_pPathF2, (nextCallback)); CCMenu menu = new CCMenu(item1, item2, item3); menu.Position = new CCPoint(0, 0); item1.Position = new CCPoint(s.Width / 2 - 100, 30); item2.Position = new CCPoint(s.Width / 2, 30); item3.Position = new CCPoint(s.Width / 2 + 100, 30); AddChild(menu, 1); CCTextureCache.SharedTextureCache.DumpCachedTextureInfo(); } ~TextureDemo() { CCTextureCache.SharedTextureCache.RemoveUnusedTextures(); CCTextureCache.SharedTextureCache.DumpCachedTextureInfo(); } public void restartCallback(object pSender) { CCScene s = new TextureTestScene(); s.AddChild(TextureTestScene.restartTextureTest()); Scene.Director.ReplaceScene(s); } public void nextCallback(object pSender) { CCScene s = new TextureTestScene(); s.AddChild(TextureTestScene.nextTextureTest()); Scene.Director.ReplaceScene(s); } public void backCallback(object pSender) { CCScene s = new TextureTestScene(); s.AddChild(TextureTestScene.backTextureTest()); Scene.Director.ReplaceScene(s); } public virtual string title() { return "No title"; } public virtual string subtitle() { return ""; } } //------------------------------------------------------------------ // // TextureSizeTest // //------------------------------------------------------------------ public class TextureSizeTest : TextureDemo { public override void OnEnter() { base.OnEnter(); CCSize size = Layer.VisibleBoundsWorldspace.Size; CCLog.Log("Loading 512x512 image..."); CCSprite sprite1 = new CCSprite("Images/texture512x512"); if (sprite1 != null) { CCLog.Log("OK\n"); sprite1.Position = new CCPoint(size.Width - 50, size.Height - 50); this.AddChild(sprite1); } else CCLog.Log("Error\n"); CCLog.Log("Loading 1024x1024 image..."); CCSprite sprite2 = new CCSprite("Images/texture1024x1024"); if (sprite2 != null) { CCLog.Log("OK\n"); this.AddChild(sprite2); } else CCLog.Log("Error\n"); CCLog.Log("Loading 2048x2048 image..."); CCSprite sprite3 = new CCSprite("Images/texture2048x2048"); if (sprite3 != null) { CCLog.Log("OK\n"); this.AddChild(sprite3); } else CCLog.Log("Error\n"); // @todo // This won't work in XNA4 - max is 2048 x 2048. // CCLog("Loading 4096x4096 image..."); // sprite = CCSprite::create("Images/texture4096x4096.png"); // if( sprite ) // CCLog("OK\n"); // else // CCLog("Error\n"); } public override string title() { return "Different Texture Sizes"; } public override string subtitle() { return "512x512, 1024x1024. See the console."; } } ////------------------------------------------------------------------ //// //// TexturePNG //// ////------------------------------------------------------------------ //void TexturePNG::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image.png"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePNG::title() //{ // return "PNG Test"; //} ////------------------------------------------------------------------ //// //// TextureJPEG //// ////------------------------------------------------------------------ //void TextureJPEG::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image.jpeg"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TextureJPEG::title() //{ // return "JPEG Test"; //} ////------------------------------------------------------------------ //// //// TextureMipMap //// ////------------------------------------------------------------------ //void TextureMipMap::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCTexture2D *texture0 = CCTextureCache::sharedTextureCache()->addImage("Images/grossini_dance_atlas.png"); // texture0->generateMipmap(); // ccTexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE }; // texture0->setTexParameters(&texParams); // CCTexture2D *texture1 = CCTextureCache::sharedTextureCache()->addImage("Images/grossini_dance_atlas_nomipmap.png"); // CCSprite *img0 = CCSprite::spriteWithTexture(texture0); // img0->setTextureRectInPixels(CCRectMake(85, 121, 85, 121)); // img0->setPosition(ccp( s.width/3.0f, s.height/2.0f)); // addChild(img0); // CCSprite *img1 = CCSprite::spriteWithTexture(texture1); // img1->setTextureRectInPixels(CCRectMake(85, 121, 85, 121)); // img1->setPosition(ccp( 2*s.width/3.0f, s.height/2.0f)); // addChild(img1); // CCEaseOut* scale1 = CCEaseOut::actionWithAction(CCScaleBy::actionWithDuration(4, 0.01f), 3); // CCFiniteTimeAction* sc_back = scale1->reverse(); // CCEaseOut* scale2 = (CCEaseOut*) (scale1->copy()); // scale2->autorelease(); // CCFiniteTimeAction* sc_back2 = scale2->reverse(); // img0->runAction(CCRepeatForever::actionWithAction((CCFiniteTimeAction*)(CCSequence::actions(scale1, sc_back, NULL)))); // img1->runAction(CCRepeatForever::actionWithAction((CCFiniteTimeAction*)(CCSequence::actions(scale2, sc_back2, NULL)))); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TextureMipMap::title() //{ // return "Texture Mipmap"; //} //std::string TextureMipMap::subtitle() //{ // return "Left image uses mipmap. Right image doesn't"; //} ////------------------------------------------------------------------ //// //// TexturePVRMipMap //// To generate PVR images read this article: //// http://developer.apple.com/iphone/library/qa/qa2008/qa1611.html //// ////------------------------------------------------------------------ //void TexturePVRMipMap::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *imgMipMap = CCSprite::create("Images/logo-mipmap.pvr"); // if( imgMipMap ) // { // imgMipMap->setPosition(ccp( s.width/2.0f-100, s.height/2.0f)); // addChild(imgMipMap); // // support mipmap filtering // ccTexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE }; // imgMipMap->getTexture()->setTexParameters(&texParams); // } // CCSprite *img = CCSprite::create("Images/logo-nomipmap.pvr"); // if( img ) // { // img->setPosition(ccp( s.width/2.0f+100, s.height/2.0f)); // addChild(img); // CCEaseOut* scale1 = CCEaseOut::actionWithAction(CCScaleBy::actionWithDuration(4, 0.01f), 3); // CCFiniteTimeAction* sc_back = scale1->reverse(); // CCEaseOut* scale2 = (CCEaseOut*) (scale1->copy()); // scale2->autorelease(); // CCFiniteTimeAction* sc_back2 = scale2->reverse(); // imgMipMap->runAction(CCRepeatForever::actionWithAction((CCFiniteTimeAction*)(CCSequence::actions(scale1, sc_back, NULL)))); // img->runAction(CCRepeatForever::actionWithAction((CCFiniteTimeAction*)(CCSequence::actions(scale2, sc_back2, NULL)))); // } // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRMipMap::title() //{ // return "PVRTC MipMap Test"; //} //std::string TexturePVRMipMap::subtitle() //{ // return "Left image uses mipmap. Right image doesn't"; //} ////------------------------------------------------------------------ //// //// TexturePVRMipMap2 //// ////------------------------------------------------------------------ //void TexturePVRMipMap2::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *imgMipMap = CCSprite::create("Images/test_image_rgba4444_mipmap.pvr"); // imgMipMap->setPosition(ccp( s.width/2.0f-100, s.height/2.0f)); // addChild(imgMipMap); // // support mipmap filtering // ccTexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE }; // imgMipMap->getTexture()->setTexParameters(&texParams); // CCSprite *img = CCSprite::create("Images/test_image.png"); // img->setPosition(ccp( s.width/2.0f+100, s.height/2.0f)); // addChild(img); // CCEaseOut* scale1 = CCEaseOut::actionWithAction(CCScaleBy::actionWithDuration(4, 0.01f), 3); // CCFiniteTimeAction* sc_back = scale1->reverse(); // CCEaseOut* scale2 = (CCEaseOut*) (scale1->copy()); // scale2->autorelease(); // CCFiniteTimeAction* sc_back2 = scale2->reverse(); // imgMipMap->runAction(CCRepeatForever::actionWithAction((CCFiniteTimeAction*)(CCSequence::actions(scale1, sc_back, NULL)))); // img->runAction(CCRepeatForever::actionWithAction((CCFiniteTimeAction*)(CCSequence::actions(scale2, sc_back2, NULL)))); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRMipMap2::title() //{ // return "PVR MipMap Test #2"; //} //std::string TexturePVRMipMap2::subtitle() //{ // return "Left image uses mipmap. Right image doesn't"; //} ////------------------------------------------------------------------ //// //// TexturePVR2BPP //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVR2BPP::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_pvrtc2bpp.pvr"); // if( img ) // { // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // } // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVR2BPP::title() //{ // return "PVR TC 2bpp Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRRaw //// To generate PVR images read this article: //// http://developer.apple.com/iphone/library/qa/qa2008/qa1611.html //// ////------------------------------------------------------------------ //void TexturePVRRaw::onEnter() //{ // TextureDemo::onEnter(); //#ifdef CC_SUPPORT_PVRTC // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCTexture2D *tex = CCTextureCache::sharedTextureCache()->addPVRTCImage("Images/test_image.pvrraw", 4, true, 128); // CCSprite *img = CCSprite::spriteWithTexture(tex); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); //#else // CCLog("Not support PVRTC!"); //#endif // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRRaw::title() //{ // return "PVR TC 4bpp Test #1 (Raw)"; //} ////------------------------------------------------------------------ //// //// TexturePVR //// To generate PVR images read this article: //// http://developer.apple.com/iphone/library/qa/qa2008/qa1611.html //// ////------------------------------------------------------------------ //void TexturePVR::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image.pvr"); // if( img ) // { // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // } // else // { // CCLog("This test is not supported."); // } // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVR::title() //{ // return "PVR TC 4bpp Test #2"; //} ////------------------------------------------------------------------ //// //// TexturePVR4BPP //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVR4BPP::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_pvrtc4bpp.pvr"); // if( img ) // { // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // } // else // { // CCLog("This test is not supported in cocos2d-mac"); // } // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVR4BPP::title() //{ // return "PVR TC 4bpp Test #3"; //} ////------------------------------------------------------------------ //// //// TexturePVRRGBA8888 //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRRGBA8888::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_rgba8888.pvr"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRRGBA8888::title() //{ // return "PVR + RGBA 8888 Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRBGRA8888 //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRBGRA8888::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_bgra8888.pvr"); // if( img ) // { // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // } // else // { // CCLog("BGRA8888 images are not supported"); // } // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRBGRA8888::title() //{ // return "PVR + BGRA 8888 Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRRGBA5551 //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRRGBA5551::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_rgba5551.pvr"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRRGBA5551::title() //{ // return "PVR + RGBA 5551 Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRRGBA4444 //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRRGBA4444::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_rgba4444.pvr"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRRGBA4444::title() //{ // return "PVR + RGBA 4444 Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRRGBA4444GZ //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRRGBA4444GZ::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); //#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) // // android can not pack .gz file into apk file // CCSprite *img = CCSprite::create("Images/test_image_rgba4444.pvr"); //#else // CCSprite *img = CCSprite::create("Images/test_image_rgba4444.pvr.gz"); //#endif // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRRGBA4444GZ::title() //{ // return "PVR + RGBA 4444 + GZ Test"; //} //std::string TexturePVRRGBA4444GZ::subtitle() //{ // return "This is a gzip PVR image"; //} ////------------------------------------------------------------------ //// //// TexturePVRRGBA4444CCZ //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRRGBA4444CCZ::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_rgba4444.pvr.ccz"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRRGBA4444CCZ::title() //{ // return "PVR + RGBA 4444 + CCZ Test"; //} //std::string TexturePVRRGBA4444CCZ::subtitle() //{ // return "This is a ccz PVR image"; //} ////------------------------------------------------------------------ //// //// TexturePVRRGB565 //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRRGB565::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_rgb565.pvr"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRRGB565::title() //{ // return "PVR + RGB 565 Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRA8 //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRA8::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_a8.pvr"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRA8::title() //{ // return "PVR + A8 Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRI8 //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRI8::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_i8.pvr"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRI8::title() //{ // return "PVR + I8 Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRAI88 //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRAI88::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image_ai88.pvr"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRAI88::title() //{ // return "PVR + AI88 Test"; //} ////------------------------------------------------------------------ //// //// TexturePVRBadEncoding //// Image generated using PVRTexTool: //// http://www.imgtec.com/powervr/insider/powervr-pvrtextool.asp //// ////------------------------------------------------------------------ //void TexturePVRBadEncoding::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/test_image-bad_encoding.pvr"); // if( img ) // { // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // } //} //std::string TexturePVRBadEncoding::title() //{ // return "PVR Unsupported encoding"; //} //std::string TexturePVRBadEncoding::subtitle() //{ // return "You should not see any image"; //} ////------------------------------------------------------------------ //// //// TexturePVRNonSquare //// ////------------------------------------------------------------------ //void TexturePVRNonSquare::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/grossini_128x256_mipmap.pvr"); // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRNonSquare::title() //{ // return "PVR + Non square texture"; //} //std::string TexturePVRNonSquare::subtitle() //{ // return "Loading a 128x256 texture"; //} ////------------------------------------------------------------------ //// //// TexturePVRNPOT4444 //// ////------------------------------------------------------------------ //void TexturePVRNPOT4444::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/grossini_pvr_rgba4444.pvr"); // if ( img ) // { // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // } // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRNPOT4444::title() //{ // return "PVR RGBA4 + NPOT texture"; //} //std::string TexturePVRNPOT4444::subtitle() //{ // return "Loading a 81x121 RGBA4444 texture."; //} ////------------------------------------------------------------------ //// //// TexturePVRNPOT8888 //// ////------------------------------------------------------------------ //void TexturePVRNPOT8888::onEnter() //{ // TextureDemo::onEnter(); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCSprite *img = CCSprite::create("Images/grossini_pvr_rgba8888.pvr"); // if( img ) // { // img->setPosition(ccp( s.width/2.0f, s.height/2.0f)); // addChild(img); // } // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePVRNPOT8888::title() //{ // return "PVR RGBA8 + NPOT texture"; //} //std::string TexturePVRNPOT8888::subtitle() //{ // return "Loading a 81x121 RGBA8888 texture."; //} //------------------------------------------------------------------ // // TextureAlias // //------------------------------------------------------------------ public class TextureAlias : TextureDemo { public override void OnEnter() { base.OnEnter(); CCSize s = Layer.VisibleBoundsWorldspace.Size; // // Sprite 1: GL_LINEAR // // Default filter is GL_LINEAR CCSprite sprite = new CCSprite("Images/grossinis_sister1"); sprite.Position = new CCPoint(s.Width / 3.0f, s.Height / 2.0f); AddChild(sprite); // this is the default filterting sprite.IsAntialiased = true; // // Sprite 1: GL_NEAREST // CCSprite sprite2 = new CCSprite("Images/grossinis_sister2"); sprite2.Position = new CCPoint(2 * s.Width / 3.0f, s.Height / 2.0f); AddChild(sprite2); // Use Nearest in this one sprite2.IsAntialiased = false; // scale them to show var sc = new CCScaleBy(3, 8.0f); var sc_back = sc.Reverse(); CCRepeatForever scaleforever = new CCRepeatForever(sc, sc_back); sprite2.RunAction(scaleforever); sprite.RunAction(scaleforever); CCTextureCache.SharedTextureCache.DumpCachedTextureInfo(); } public override string title() { return "AntiAlias / Alias textures"; } public override string subtitle() { return "Left image is antialiased. Right image is aliases"; } } ////------------------------------------------------------------------ //// //// TexturePixelFormat //// ////------------------------------------------------------------------ //void TexturePixelFormat::onEnter() //{ // // // // This example displays 1 png images 4 times. // // Each time the image is generated using: // // 1- 32-bit RGBA8 // // 2- 16-bit RGBA4 // // 3- 16-bit RGB5A1 // // 4- 16-bit RGB565 // TextureDemo::onEnter(); // CCLabelTTF *label = (CCLabelTTF*) getChildByTag(kTagLabel); // label->setColor(ccc3(16,16,255)); // CCSize s = CCDirector::sharedDirector()->getWinSize(); // CCLayerColor *background = CCLayerColor::layerWithColorWidthHeight(ccc4(128,128,128,255), s.width, s.height); // addChild(background, -1); // // RGBA 8888 image (32-bit) // CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888); // CCSprite *sprite1 = CCSprite::create("Images/test-rgba1.png"); // sprite1->setPosition(ccp(1*s.width/6, s.height/2+32)); // addChild(sprite1, 0); // // remove texture from texture manager // CCTextureCache::sharedTextureCache()->removeTexture(sprite1->getTexture()); // // RGBA 4444 image (16-bit) // CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444); // CCSprite *sprite2 = CCSprite::create("Images/test-rgba1.png"); // sprite2->setPosition(ccp(2*s.width/6, s.height/2-32)); // addChild(sprite2, 0); // // remove texture from texture manager // CCTextureCache::sharedTextureCache()->removeTexture(sprite2->getTexture()); // // RGB5A1 image (16-bit) // CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGB5A1); // CCSprite *sprite3 = CCSprite::create("Images/test-rgba1.png"); // sprite3->setPosition(ccp(3*s.width/6, s.height/2+32)); // addChild(sprite3, 0); // // remove texture from texture manager // CCTextureCache::sharedTextureCache()->removeTexture(sprite3->getTexture()); // // RGB565 image (16-bit) // CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGB565); // CCSprite *sprite4 = CCSprite::create("Images/test-rgba1.png"); // sprite4->setPosition(ccp(4*s.width/6, s.height/2-32)); // addChild(sprite4, 0); // // remove texture from texture manager // CCTextureCache::sharedTextureCache()->removeTexture(sprite4->getTexture()); // // A8 image (8-bit) // CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_A8); // CCSprite *sprite5 = CCSprite::create("Images/test-rgba1.png"); // sprite5->setPosition(ccp(5*s.width/6, s.height/2+32)); // addChild(sprite5, 0); // // remove texture from texture manager // CCTextureCache::sharedTextureCache()->removeTexture(sprite5->getTexture()); // CCFadeOut* fadeout = CCFadeOut::actionWithDuration(2); // CCFadeIn* fadein = CCFadeIn::actionWithDuration(2); // CCFiniteTimeAction* seq = CCSequence::actions(CCDelayTime::actionWithDuration(2), fadeout, fadein, NULL); // CCRepeatForever* seq_4ever = CCRepeatForever::actionWithAction((CCFiniteTimeAction*) seq); // CCRepeatForever* seq_4ever2 = (CCRepeatForever*) (seq_4ever->copy()); seq_4ever2->autorelease(); // CCRepeatForever* seq_4ever3 = (CCRepeatForever*) (seq_4ever->copy()); seq_4ever3->autorelease(); // CCRepeatForever* seq_4ever4 = (CCRepeatForever*) (seq_4ever->copy()); seq_4ever4->autorelease(); // CCRepeatForever* seq_4ever5 = (CCRepeatForever*) (seq_4ever->copy()); seq_4ever5->autorelease(); // sprite1->runAction(seq_4ever); // sprite2->runAction(seq_4ever2); // sprite3->runAction(seq_4ever3); // sprite4->runAction(seq_4ever4); // sprite5->runAction(seq_4ever5); // // restore default // CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default); // CCTextureCache::sharedTextureCache()->dumpCachedTextureInfo(); //} //std::string TexturePixelFormat::title() //{ // return "Texture Pixel Formats"; //} //std::string TexturePixelFormat::subtitle() //{ // return "Textures: RGBA8888, RGBA4444, RGB5A1, RGB565, A8"; //} ////------------------------------------------------------------------ //// //// TextureBlend //// ////------------------------------------------------------------------ //void TextureBlend::onEnter() //{ // TextureDemo::onEnter(); // for( int i=0;i < 15;i++ ) // { // // BOTTOM sprites have alpha pre-multiplied // // they use by default GL_ONE, GL_ONE_MINUS_SRC_ALPHA // CCSprite *cloud = CCSprite::create("Images/test_blend.png"); // addChild(cloud, i+1, 100+i); // cloud->setPosition(ccp(50+25*i, 80)); // ccBlendFunc blendFunc1 = { GL_ONE, GL_ONE_MINUS_SRC_ALPHA }; // cloud->setBlendFunc(blendFunc1); // // CENTER sprites have also alpha pre-multiplied // // they use by default GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA // cloud = CCSprite::create("Images/test_blend.png"); // addChild(cloud, i+1, 200+i); // cloud->setPosition(ccp(50+25*i, 160)); // ccBlendFunc blendFunc2 = { GL_ONE_MINUS_DST_COLOR, GL_ZERO }; // cloud->setBlendFunc(blendFunc2); // // UPPER sprites are using custom blending function // // You can set any blend function to your sprites // cloud = CCSprite::create("Images/test_blend.png"); // addChild(cloud, i+1, 200+i); // cloud->setPosition(ccp(50+25*i, 320-80)); // ccBlendFunc blendFunc3 = { GL_SRC_ALPHA, GL_ONE }; // cloud->setBlendFunc(blendFunc3); // additive blending // } //} //std::string TextureBlend::title() //{ // return "Texture Blending"; //} //std::string TextureBlend::subtitle() //{ // return "Testing 3 different blending modes"; //} ////------------------------------------------------------------------ //// //// TextureGlClamp //// ////------------------------------------------------------------------ //void TextureGlClamp::onEnter() //{ // TextureDemo::onEnter(); // CCSize size = CCDirector::sharedDirector()->getWinSize(); // // The .png image MUST be power of 2 in order to create a continue effect. // // eg: 32x64, 512x128, 256x1024, 64x64, etc.. // CCSprite *sprite = CCSprite::create("Images/pattern1.png", CCRectMake(0,0,512,256)); // addChild(sprite, -1, kTagSprite1); // sprite->setPosition(ccp(size.width/2,size.height/2)); // ccTexParams params = {GL_LINEAR,GL_LINEAR,GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE}; // sprite->getTexture()->setTexParameters(&params); // CCRotateBy* rotate = CCRotateBy::actionWithDuration(4, 360); // sprite->runAction(rotate); // CCScaleBy* scale = CCScaleBy::actionWithDuration(2, 0.04f); // CCScaleBy* scaleBack = (CCScaleBy*) (scale->reverse()); // CCFiniteTimeAction* seq = CCSequence::actions(scale, scaleBack, NULL); // sprite->runAction(seq); //} //std::string TextureGlClamp::title() //{ // return "Texture GL_CLAMP"; //} //TextureGlClamp::~TextureGlClamp() //{ // CCTextureCache::sharedTextureCache()->removeUnusedTextures(); //} //------------------------------------------------------------------ // // TextureGLClamp // //------------------------------------------------------------------ public class TextureGLClamp : TextureDemo { public override void OnEnter() { base.OnEnter(); CCSize size = Layer.VisibleBoundsWorldspace.Size; // The .png image MUST be power of 2 in order to create a continue effect. // eg: 32x64, 512x128, 256x1024, 64x64, etc.. var sprite = new CCSprite("Images/pattern1.png", new CCRect(0, 0, 512, 256)); AddChild(sprite, -1, (int) enumTag.kTagSprite1); sprite.Position = new CCPoint(size.Width / 2, size.Height / 2); // Cocos2D-XNA no longer uses TexParameters. Please use the XNA SamplerState // sprite.Texture.TexParameters = new CCTexParams() { MagFilter = (uint)All.Linear, // MinFilter = (uint)All.Linear, // WrapS = (uint)All.ClampToEdge, // WrapT = (uint)All.ClampToEdge // }; sprite.Texture.SamplerState = SamplerState.LinearClamp; var rotate = new CCRotateBy(4, 360); sprite.RunAction(rotate); var scale = new CCScaleBy(2, 0.04f); var scaleBack = (CCScaleBy) scale.Reverse(); var seq = new CCSequence(scale, scaleBack); sprite.RunAction(seq); } public override string title() { return "Texture GL_CLAMP"; } // public override string subtitle() // { // return "Texture is repeated within the area."; // } } //------------------------------------------------------------------ // // TextureGLMirror // //------------------------------------------------------------------ public class TextureGLMirror : TextureDemo { public override void OnEnter() { base.OnEnter(); CCSize size = Layer.VisibleBoundsWorldspace.Size; // The .png image MUST be power of 2 in order to create a continue effect. // eg: 32x64, 512x128, 256x1024, 64x64, etc.. var sprite = new CCSprite("Images/pattern1.png", new CCRect(0, 0, 512, 256)); AddChild(sprite, -1, (int) enumTag.kTagSprite1); sprite.Position = new CCPoint(size.Width / 2, size.Height / 2); // Cocos2D-XNA no longer uses TexParameters. Please use the XNA SamplerState // sprite.Texture.TexParameters = new CCTexParams() { MagFilter = (uint)All.Linear, // MinFilter = (uint)All.Linear, // WrapS = (uint)All.MirroredRepeat, // WrapT = (uint)All.Repeat // }; var state = new SamplerState(); state.AddressU = TextureAddressMode.Mirror; state.AddressV = TextureAddressMode.Wrap; sprite.Texture.SamplerState = state; var rotate = new CCRotateBy(4, 360); sprite.RunAction(rotate); var scale = new CCScaleBy(2, 0.04f); var scaleBack = (CCScaleBy) scale.Reverse(); var seq = new CCSequence(scale, scaleBack); sprite.RunAction(seq); } public override string title() { return "Texture GL_MIRROR"; } public override string subtitle() { return "Texture is repeated within the area and Mirrored."; } } //------------------------------------------------------------------ // // TextureGLRepeat // //------------------------------------------------------------------ public class TextureGLRepeat : TextureDemo { public override void OnEnter() { base.OnEnter(); CCSize size = Layer.VisibleBoundsWorldspace.Size; // The .png image MUST be power of 2 in order to create a continue effect. // eg: 32x64, 512x128, 256x1024, 64x64, etc.. var sprite = new CCSprite("Images/pattern1.png", new CCRect(0, 0, 4096, 4096)); AddChild(sprite, -1, (int) enumTag.kTagSprite1); sprite.Position = new CCPoint(size.Width / 2, size.Height / 2); // Cocos2D-XNA no longer uses TexParameters. Please use the XNA SamplerState // sprite.Texture.TexParameters = new CCTexParams() { MagFilter = (uint)All.Linear, // MinFilter = (uint)All.Linear, // WrapS = (uint)All.Repeat, // WrapT = (uint)All.Repeat // }; sprite.Texture.SamplerState = SamplerState.LinearWrap; var rotate = new CCRotateBy(4, 360); sprite.RunAction(rotate); var scale = new CCScaleBy(2, 0.04f); var scaleBack = (CCScaleBy) scale.Reverse(); var seq = new CCSequence(scale, scaleBack); sprite.RunAction(seq); } public override string title() { return "Texture GL_REPEAT"; } public override string subtitle() { return "Texture is repeated within the area."; } } //------------------------------------------------------------------ // // TextureCache1 // //------------------------------------------------------------------ public class TextureCache1 : TextureDemo { public override void OnEnter() { base.OnEnter(); CCSize s = Layer.VisibleBoundsWorldspace.Size; CCSprite sprite; sprite = new CCSprite("Images/grossinis_sister1"); sprite.Position = new CCPoint(s.Width / 5 * 1, s.Height / 2); sprite.IsAntialiased = false; sprite.Scale = 2; AddChild(sprite); CCTextureCache.SharedTextureCache.RemoveTexture(sprite.Texture); sprite = new CCSprite("Images/grossinis_sister1"); sprite.Position = new CCPoint(s.Width / 5 * 2, s.Height / 2); sprite.IsAntialiased = true; sprite.Scale = 2; AddChild(sprite); // 2nd set of sprites sprite = new CCSprite("Images/grossinis_sister2"); sprite.Position = new CCPoint(s.Width / 5 * 3, s.Height / 2); sprite.IsAntialiased = false; sprite.Scale = 2; AddChild(sprite); CCTextureCache.SharedTextureCache.RemoveTextureForKey("Images/grossinis_sister2"); sprite = new CCSprite("Images/grossinis_sister2"); sprite.Position = new CCPoint(s.Width / 5 * 4, s.Height / 2); sprite.IsAntialiased = true; sprite.Scale = 2; AddChild(sprite); } public override string title() { return "CCTextureCache: remove"; } public override string subtitle() { // temp to remove: for prealpha version return "4 images should appear"; // return "4 images should appear: alias, antialias, alias, antilias"; } } internal class TextureAsync : TextureDemo { private int m_nImageOffset; public override void OnEnter() { base.OnEnter(); m_nImageOffset = 0; CCSize size = Layer.VisibleBoundsWorldspace.Size; CCLabelTtf label = new CCLabelTtf("Loading...", "Marker Felt", 32); label.Position = size.Center; AddChild(label, 10); var scale = new CCScaleBy(0.3f, 2); label.RepeatForever(scale, scale.Reverse()); ScheduleOnce(LoadImages, 1.0f); } public override void OnExit() { base.OnExit(); CCTextureCache.SharedTextureCache.RemoveAllTextures(); } private void LoadImages(float dt) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { var szSpriteName = String.Format("Images/sprites_test/sprite-{0}-{1}.png", i, j); CCTextureCache.SharedTextureCache.AddImageAsync(szSpriteName, ImageLoaded); } } CCTextureCache.SharedTextureCache.AddImageAsync("Images/background1.jpg", ImageLoaded); CCTextureCache.SharedTextureCache.AddImageAsync("Images/background2.jpg", ImageLoaded); CCTextureCache.SharedTextureCache.AddImageAsync("Images/background.png", ImageLoaded); CCTextureCache.SharedTextureCache.AddImageAsync("Images/atlastest.png", ImageLoaded); CCTextureCache.SharedTextureCache.AddImageAsync("Images/grossini_dance_atlas.png", ImageLoaded); } private void ImageLoaded(CCTexture2D tex) { CCDirector director = Scene.Director; //CCAssert( [NSThread currentThread] == [director runningThread], @"FAIL. Callback should be on cocos2d thread"); // IMPORTANT: The order on the callback is not guaranteed. Don't depend on the callback // This test just creates a sprite based on the Texture CCSprite sprite = new CCSprite(tex); sprite.AnchorPoint = CCPoint.Zero; AddChild(sprite, -1); CCSize size = Layer.VisibleBoundsWorldspace.Size; int i = m_nImageOffset * 32; sprite.Position = new CCPoint(i % (int) size.Width, (i / (int) size.Width) * 32); m_nImageOffset++; } public override string title() { return "Texture Async Load"; } public override string subtitle() { return "Textures should load while an animation is being run"; } } }
using Draughts.Web.UI.Domain; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; namespace Draughts.Web.UI.Mapper.Tests { [TestClass] public class BoardRotaterMapperTest { private BoardRotaterMapper boardRotaterMapper; [TestInitialize] public void Setup() { boardRotaterMapper = new BoardRotaterMapper(); } [TestMethod] public void RotateNullGameBoardTest() { var result = boardRotaterMapper.Rotate(null); Assert.IsNull(result); } [TestMethod] public void RotateNullMoveRequestTest() { var result = boardRotaterMapper.Rotate(null, 0, 0); Assert.IsNull(result); } [TestMethod] public void RotatePoint00Test() { var point = boardRotaterMapper.Rotate(0, 0, 8, 8); Assert.AreEqual(7, point.X); Assert.AreEqual(7, point.Y); } [TestMethod] public void RotatePoint23Test() { var point = boardRotaterMapper.Rotate(2, 3, 8, 8); Assert.AreEqual(5, point.X); Assert.AreEqual(4, point.Y); } [TestMethod] public void RotatePoint77Test() { var point = boardRotaterMapper.Rotate(7, 7, 8, 8); Assert.AreEqual(0, point.X); Assert.AreEqual(0, point.Y); } [TestMethod] public void RotateSinglePiece00Test() { var gamePiece = new GamePiece() { PieceColour = Constants.BLACK, PieceRank = Constants.MAN, Xcoord = 0, Ycoord = 0 }; var gamePieces = new List<GamePiece>(); gamePieces.Add(gamePiece); var gameBoard = new GameBoard() { GamePieces = gamePieces.ToArray(), Height = 8, Width = 8 }; var rotatedGameBoard = boardRotaterMapper.Rotate(gameBoard); Assert.AreEqual(gamePieces.Count, rotatedGameBoard.GamePieces.Length); Assert.AreEqual(7, rotatedGameBoard.GamePieces.First().Xcoord); Assert.AreEqual(7, rotatedGameBoard.GamePieces.First().Ycoord); Assert.AreEqual(gamePiece.PieceColour, rotatedGameBoard.GamePieces.First().PieceColour); Assert.AreEqual(gamePiece.PieceRank, rotatedGameBoard.GamePieces.First().PieceRank); } [TestMethod] public void RotateSinglePiece01Test() { var gamePiece = new GamePiece() { PieceColour = Constants.WHITE, PieceRank = Constants.KING, Xcoord = 0, Ycoord = 1 }; var gamePieces = new List<GamePiece>(); gamePieces.Add(gamePiece); var gameBoard = new GameBoard() { GamePieces = gamePieces.ToArray(), Height = 8, Width = 8 }; var rotatedGameBoard = boardRotaterMapper.Rotate(gameBoard); Assert.AreEqual(gamePieces.Count, rotatedGameBoard.GamePieces.Length); Assert.AreEqual(7, rotatedGameBoard.GamePieces.First().Xcoord); Assert.AreEqual(6, rotatedGameBoard.GamePieces.First().Ycoord); Assert.AreEqual(gamePiece.PieceColour, rotatedGameBoard.GamePieces.First().PieceColour); Assert.AreEqual(gamePiece.PieceRank, rotatedGameBoard.GamePieces.First().PieceRank); } [TestMethod] public void RotateSinglePiece10Test() { var gamePiece = new GamePiece() { PieceColour = Constants.BLACK, PieceRank = Constants.KING, Xcoord = 1, Ycoord = 0 }; var gamePieces = new List<GamePiece>(); gamePieces.Add(gamePiece); var gameBoard = new GameBoard() { GamePieces = gamePieces.ToArray(), Height = 8, Width = 8 }; var rotatedGameBoard = boardRotaterMapper.Rotate(gameBoard); Assert.AreEqual(gamePieces.Count, rotatedGameBoard.GamePieces.Length); Assert.AreEqual(6, rotatedGameBoard.GamePieces.First().Xcoord); Assert.AreEqual(7, rotatedGameBoard.GamePieces.First().Ycoord); Assert.AreEqual(gamePiece.PieceColour, rotatedGameBoard.GamePieces.First().PieceColour); Assert.AreEqual(gamePiece.PieceRank, rotatedGameBoard.GamePieces.First().PieceRank); } [TestMethod] public void RotateSinglePieceWithMovesTest() { var gamePiece = new GamePiece() { PieceColour = Constants.BLACK, PieceRank = Constants.MAN, Xcoord = 1, Ycoord = 0 }; var gamePieces = new List<GamePiece>(); gamePieces.Add(gamePiece); var gameMove = new GameMove() { StartX = 2, StartY = 3, EndX = 5, EndY = 4 }; var gameMoves = new List<GameMove>(); gameMoves.Add(gameMove); var gameBoard = new GameBoard() { GamePieces = gamePieces.ToArray(), Height = 8, Width = 8, GameMoves = gameMoves.ToArray() }; var rotatedGameBoard = boardRotaterMapper.Rotate(gameBoard); Assert.AreEqual(gamePieces.Count, rotatedGameBoard.GamePieces.Length); Assert.AreEqual(6, rotatedGameBoard.GamePieces.First().Xcoord); Assert.AreEqual(7, rotatedGameBoard.GamePieces.First().Ycoord); Assert.AreEqual(gameMoves.Count, rotatedGameBoard.GameMoves.Length); Assert.AreEqual(5, rotatedGameBoard.GameMoves.First().StartX); Assert.AreEqual(4, rotatedGameBoard.GameMoves.First().StartY); Assert.AreEqual(2, rotatedGameBoard.GameMoves.First().EndX); Assert.AreEqual(3, rotatedGameBoard.GameMoves.First().EndY); } [TestMethod] public void RotateMoveRequestTest() { var moveRequest = new MoveRequest() { StartX = 2, StartY = 3, EndX = 5, EndY = 4, PlayerId = Guid.NewGuid().ToString() }; var rotatedMoveRequest = boardRotaterMapper.Rotate(moveRequest, 8, 8); Assert.AreEqual(5, rotatedMoveRequest.StartX); Assert.AreEqual(4, rotatedMoveRequest.StartY); Assert.AreEqual(2, rotatedMoveRequest.EndX); Assert.AreEqual(3, rotatedMoveRequest.EndY); Assert.AreEqual(moveRequest.PlayerId, rotatedMoveRequest.PlayerId); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Scheduler; using Microsoft.WindowsAzure.Management.Scheduler.Models; namespace Microsoft.WindowsAzure.Management.Scheduler { public partial class CloudServiceManagementClient : ServiceClient<CloudServiceManagementClient>, Microsoft.WindowsAzure.Management.Scheduler.ICloudServiceManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private ICloudServiceOperations _cloudServices; public virtual ICloudServiceOperations CloudServices { get { return this._cloudServices; } } /// <summary> /// Initializes a new instance of the CloudServiceManagementClient /// class. /// </summary> private CloudServiceManagementClient() : base() { this._cloudServices = new CloudServiceOperations(this); this._apiVersion = "2013-03-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the CloudServiceManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Required. Gets the URI used as the base for all cloud service /// requests. /// </param> public CloudServiceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the CloudServiceManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public CloudServiceManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the CloudServiceManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private CloudServiceManagementClient(HttpClient httpClient) : base(httpClient) { this._cloudServices = new CloudServiceOperations(this); this._apiVersion = "2013-03-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the CloudServiceManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Required. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public CloudServiceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the CloudServiceManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public CloudServiceManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// CloudServiceManagementClient instance /// </summary> /// <param name='client'> /// Instance of CloudServiceManagementClient to clone to /// </param> protected override void Clone(ServiceClient<CloudServiceManagementClient> client) { base.Clone(client); if (client is CloudServiceManagementClient) { CloudServiceManagementClient clonedClient = ((CloudServiceManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// EntitleResource is used only for 3rd party Store providers. Each /// subscription must be entitled for the resource before creating /// that particular type of resource. /// </summary> /// <param name='parameters'> /// Required. Parameters provided to the EntitleResource method. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> EntitleResourceAsync(EntitleResourceParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ResourceNamespace == null) { throw new ArgumentNullException("parameters.ResourceNamespace"); } if (parameters.ResourceType == null) { throw new ArgumentNullException("parameters.ResourceType"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "EntitleResourceAsync", tracingParameters); } // Construct URL string url = (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/EntitleResource"; string baseUrl = this.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement entitleResourceElement = new XElement(XName.Get("EntitleResource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(entitleResourceElement); XElement resourceProviderNameSpaceElement = new XElement(XName.Get("ResourceProviderNameSpace", "http://schemas.microsoft.com/windowsazure")); resourceProviderNameSpaceElement.Value = parameters.ResourceNamespace; entitleResourceElement.Add(resourceProviderNameSpaceElement); XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); typeElement.Value = parameters.ResourceType; entitleResourceElement.Add(typeElement); XElement registrationDateElement = new XElement(XName.Get("RegistrationDate", "http://schemas.microsoft.com/windowsazure")); registrationDateElement.Value = parameters.RegistrationDate.ToString(); entitleResourceElement.Add(registrationDateElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Operation Status operation returns the status of /// thespecified operation. After calling an asynchronous operation, /// you can call Get Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// Required. The request ID for the request you wish to track. The /// request ID is returned in the x-ms-request-id response header for /// every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.CloudServiceOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("requestId", requestId); Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim(); string baseUrl = this.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result CloudServiceOperationStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CloudServiceOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { CloudServiceOperationStatus statusInstance = ((CloudServiceOperationStatus)Enum.Parse(typeof(CloudServiceOperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { CloudServiceOperationStatusResponse.ErrorDetails errorInstance = new CloudServiceOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* ==================================================================== */ using System; using System.Collections; using System.Drawing; namespace Oranikle.Report.Engine { ///<summary> /// Bar chart definition and processing. ///</summary> public class ChartBar: ChartBase { int _GapSize = 6; // TODO: hard code for now public ChartBar(Report r, Row row, Chart c, MatrixCellEntry[,] m, Expression showTooltips, Expression showTooltipsX,Expression _ToolTipYFormat, Expression _ToolTipXFormat) : base(r, row, c, m,showTooltips,showTooltipsX,_ToolTipYFormat,_ToolTipXFormat) { } override public void Draw(Report rpt) { CreateSizedBitmap(); //AJM GJL 14082008 Using Vector Graphics using (Graphics g1 = Graphics.FromImage(_bm)) { _aStream = new System.IO.MemoryStream(); IntPtr HDC = g1.GetHdc(); _mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel); g1.ReleaseHdc(HDC); } using (Graphics g = Graphics.FromImage(_mf)) { // 06122007AJM Used to Force Higher Quality g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // Adjust the top margin to depend on the title height Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title); Layout.TopMargin = titleSize.Height; double max=0,min=0; // Get the max and min values // 20022008 AJM GJL - Now requires Y axis identifier GetValueMaxMin(rpt, ref max, ref min, 0,1); DrawChartStyle(rpt, g); // Draw title; routine determines if necessary DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin)); // Adjust the left margin to depend on the Category Axis Size caSize = CategoryAxisSize(rpt, g); Layout.LeftMargin = caSize.Width; // Adjust the bottom margin to depend on the Value Axis Size vaSize = ValueAxisSize(rpt, g, min, max); Layout.BottomMargin = vaSize.Height; // Draw legend System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true); // 20022008 AJM GJL - Requires Rpt and Graphics AdjustMargins(lRect,rpt,g ); // Adjust margins based on legend. // Draw Plot area DrawPlotAreaStyle(rpt, g, lRect); // Draw Value Axis if (vaSize.Width > 0) // If we made room for the axis - we need to draw it DrawValueAxis(rpt, g, min, max, new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height-Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height), Layout.TopMargin, _bm.Height - Layout.BottomMargin); // Draw Category Axis if (caSize.Height > 0) DrawCategoryAxis(rpt, g, new System.Drawing.Rectangle(Layout.LeftMargin - caSize.Width, Layout.TopMargin, caSize.Width, _bm.Height - Layout.TopMargin - Layout.BottomMargin)); if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked) DrawPlotAreaStacked(rpt, g, min, max); else if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked) DrawPlotAreaPercentStacked(rpt, g); else DrawPlotAreaPlain(rpt, g, min, max); DrawLegend(rpt, g, false, false); // after the plot is drawn } } void DrawPlotAreaPercentStacked(Report rpt, Graphics g) { int barsNeeded = CategoryCount; int gapsNeeded = CategoryCount * 2; // Draw Plot area data double max = 1; int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded); int maxBarWidth = (int) (Layout.PlotArea.Width); // Loop thru calculating all the data points for (int iRow = 1; iRow <= CategoryCount; iRow++) { int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount)); barLoc += _GapSize; // space before series double sum=0; for (int iCol = 1; iCol <= SeriesCount; iCol++) { sum += GetDataValue(rpt, iRow, iCol); } double v=0; int saveX=0; double t=0; for (int iCol = 1; iCol <= SeriesCount; iCol++) { t = GetDataValue(rpt, iRow, iCol); v += t; int x = (int) ((Math.Min(v/sum,max) / max) * maxBarWidth); System.Drawing.Rectangle rect; rect = new System.Drawing.Rectangle(Layout.PlotArea.Left + saveX, barLoc, x - saveX, heightBar); DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol), rect, iRow, iCol); //Add a metafilecomment to use as a tooltip GJL 26092008 if (_showToolTips) { String val = "ToolTip:" + t.ToString(_tooltipYFormat) + "|X:" + (int)rect.X + "|Y:" + (int)rect.Y + "|W:" + rect.Width + "|H:" + rect.Height; g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val)); } saveX = x; } } return; } void DrawPlotAreaPlain(Report rpt, Graphics g, double min, double max) { int barsNeeded = SeriesCount * CategoryCount; int gapsNeeded = CategoryCount * 2; // Draw Plot area data int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded); int maxBarWidth = (int) (Layout.PlotArea.Width); //int barLoc=Layout.LeftMargin; for (int iRow=1; iRow <= CategoryCount; iRow++) { int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount)); barLoc += _GapSize; // space before series for (int iCol=1; iCol <= SeriesCount; iCol++) { double v = this.GetDataValue(rpt, iRow, iCol); int x = (int) (((Math.Min(v,max)-min) / (max-min)) * maxBarWidth); DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol), new System.Drawing.Rectangle(Layout.PlotArea.Left, barLoc, x, heightBar), iRow, iCol); //Add a metafilecomment to use as a tooltip GJL 26092008 if (_showToolTips) { String val = "ToolTip:" + v.ToString(_tooltipYFormat) + "|X:" + (int)Layout.PlotArea.Left + "|Y:" + (int)(barLoc) + "|W:" + x + "|H:" + heightBar; g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val)); } barLoc += heightBar; } } return; } void DrawPlotAreaStacked(Report rpt, Graphics g, double min, double max) { int barsNeeded = CategoryCount; int gapsNeeded = CategoryCount * 2; int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded); int maxBarWidth = (int) (Layout.PlotArea.Width); // Loop thru calculating all the data points for (int iRow = 1; iRow <= CategoryCount; iRow++) { int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount)); barLoc += _GapSize; // space before series double v=0; double t = 0; int saveX=0; for (int iCol = 1; iCol <= SeriesCount; iCol++) { t = GetDataValue(rpt, iRow, iCol); v += t; int x = (int) (((Math.Min(v,max)-min) / (max-min)) * maxBarWidth); System.Drawing.Rectangle rect; rect = new System.Drawing.Rectangle(Layout.PlotArea.Left + saveX, barLoc, x - saveX, heightBar); DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol), rect, iRow, iCol); if (_showToolTips) { String val = "ToolTip:" + v.ToString(_tooltipYFormat) + "|X:" + (int)rect.X + "|Y:" + (int)rect.Y + "|W:" + rect.Width + "|H:" + rect.Height; g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val)); } saveX = x; } } return; } // Calculate the size of the category axis Size CategoryAxisSize(Report rpt, Graphics g) { _LastCategoryWidth = 0; Size size=Size.Empty; if (this.ChartDefn.CategoryAxis == null) return size; Axis a = this.ChartDefn.CategoryAxis.Axis; if (a == null) return size; Style s = a.Style; // Measure the title size = DrawTitleMeasure(rpt, g, a.Title); if (!a.Visible) // don't need to calculate the height return size; // Calculate the tallest category name TypeCode tc; int maxWidth=0; for (int iRow=1; iRow <= CategoryCount; iRow++) { object v = this.GetCategoryValue(rpt, iRow, out tc); Size tSize; if (s == null) tSize = Style.MeasureStringDefaults(rpt, g, v, tc, null, int.MaxValue); else tSize =s.MeasureString(rpt, g, v, tc, null, int.MaxValue); if (tSize.Width > maxWidth) maxWidth = tSize.Width; if (iRow == CategoryCount) _LastCategoryWidth = tSize.Width; } // Add on the widest category name size.Width += maxWidth; return size; } // DrawCategoryAxis void DrawCategoryAxis(Report rpt, Graphics g, System.Drawing.Rectangle rect) { if (this.ChartDefn.CategoryAxis == null) return; Axis a = this.ChartDefn.CategoryAxis.Axis; if (a == null) return; Style s = a.Style; Size tSize = DrawTitleMeasure(rpt, g, a.Title); DrawTitle(rpt, g, a.Title, new System.Drawing.Rectangle(rect.Left, rect.Top, tSize.Width, rect.Height)); int drawHeight = rect.Height / CategoryCount; TypeCode tc; for (int iRow=1; iRow <= CategoryCount; iRow++) { object v = this.GetCategoryValue(rpt, iRow, out tc); int drawLoc=(int) (rect.Top + (iRow-1) * ((double) rect.Height / CategoryCount)); // Draw the category text if (a.Visible) { System.Drawing.Rectangle drawRect = new System.Drawing.Rectangle(rect.Left + tSize.Width, drawLoc, rect.Width-tSize.Width, drawHeight); if (s == null) Style.DrawStringDefaults(g, v, drawRect); else s.DrawString(rpt, g, v, tc, null, drawRect); } // Draw the Major Tick Marks (if necessary) DrawCategoryAxisTick(g, true, a.MajorTickMarks, new Point(rect.Right, drawLoc)); } // Draw the end on (if necessary) DrawCategoryAxisTick(g, true, a.MajorTickMarks, new Point(rect.Right, rect.Bottom)); return; } protected void DrawCategoryAxisTick(Graphics g, bool bMajor, AxisTickMarksEnum tickType, Point p) { int len = bMajor? AxisTickMarkMajorLen: AxisTickMarkMinorLen; switch (tickType) { case AxisTickMarksEnum.Outside: g.DrawLine(Pens.Black, new Point(p.X, p.Y), new Point(p.X-len, p.Y)); break; case AxisTickMarksEnum.Inside: g.DrawLine(Pens.Black, new Point(p.X, p.Y), new Point(p.X+len, p.Y)); break; case AxisTickMarksEnum.Cross: g.DrawLine(Pens.Black, new Point(p.X-len, p.Y), new Point(p.X+len, p.Y)); break; case AxisTickMarksEnum.None: default: break; } return; } void DrawColumnBar(Report rpt, Graphics g, Brush brush, System.Drawing.Rectangle rect, int iRow, int iCol) { g.FillRectangle(brush, rect); g.DrawRectangle(Pens.Black, rect); if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked || (ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked) { DrawDataPoint(rpt, g, rect, iRow, iCol); } else { Point p; p = new Point(rect.Right, rect.Top); DrawDataPoint(rpt, g, p, iRow, iCol); } return; } protected void DrawValueAxis(Report rpt, Graphics g, double min, double max, System.Drawing.Rectangle rect, int plotTop, int plotBottom) { if (this.ChartDefn.ValueAxis == null) return; Axis a = this.ChartDefn.ValueAxis.Axis; if (a == null) return; Style s = a.Style; // Account for tick marks int tickSize=0; if (a.MajorTickMarks == AxisTickMarksEnum.Cross || a.MajorTickMarks == AxisTickMarksEnum.Outside) tickSize = this.AxisTickMarkMajorLen; else if (a.MinorTickMarks == AxisTickMarksEnum.Cross || a.MinorTickMarks == AxisTickMarksEnum.Outside) tickSize += this.AxisTickMarkMinorLen; int intervalCount; double incr; SetIncrementAndInterval(rpt, a, min, max, out incr, out intervalCount); // Calculate the interval count int maxValueHeight = 0; double v = min; Size size= Size.Empty; for (int i = 0; i < intervalCount+1; i++) { int x = (int) (((Math.Min(v,max)-min) / (max-min)) * rect.Width); if (!a.Visible) { // nothing to do } else if (s != null) { size = s.MeasureString(rpt, g, v, TypeCode.Double, null, int.MaxValue); System.Drawing.Rectangle vRect = new System.Drawing.Rectangle(rect.Left + x - size.Width/2, rect.Top+tickSize, size.Width, size.Height); s.DrawString(rpt, g, v, TypeCode.Double, null, vRect); } else { size = Style.MeasureStringDefaults(rpt, g, v, TypeCode.Double, null, int.MaxValue); System.Drawing.Rectangle vRect = new System.Drawing.Rectangle(rect.Left + x - size.Width/2, rect.Top+tickSize, size.Width, size.Height); Style.DrawStringDefaults(g, v, vRect); } if (size.Height > maxValueHeight) // Need to keep track of the maximum height maxValueHeight = size.Height; // this is probably overkill since it should always be the same?? DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left + x, plotTop), new Point(rect.Left + x, plotBottom)); DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left + x, plotBottom )); v += incr; } // Draw the end points of the major grid lines DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left, plotTop), new Point(rect.Left, plotBottom)); DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left, plotBottom)); DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Right, plotTop), new Point(rect.Right, plotBottom)); DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Right, plotBottom)); Size tSize = DrawTitleMeasure(rpt, g, a.Title); DrawTitle(rpt, g, a.Title, new System.Drawing.Rectangle(rect.Left, rect.Top+maxValueHeight+tickSize, rect.Width, tSize.Height)); return; } protected void DrawValueAxisGrid(Report rpt, Graphics g, ChartGridLines gl, Point s, Point e) { if (gl == null || !gl.ShowGridLines) return; if (gl.Style != null) gl.Style.DrawStyleLine(rpt, g, null, s, e); else g.DrawLine(Pens.Black, s, e); return; } protected void DrawValueAxisTick(Report rpt, Graphics g, bool bMajor, AxisTickMarksEnum tickType, ChartGridLines gl, Point p) { if (tickType == AxisTickMarksEnum.None) return; int len = bMajor? AxisTickMarkMajorLen: AxisTickMarkMinorLen; Point s, e; switch (tickType) { case AxisTickMarksEnum.Inside: s = new Point(p.X, p.Y); e = new Point(p.X, p.Y-len); break; case AxisTickMarksEnum.Cross: s = new Point(p.X, p.Y-len); e = new Point(p.X, p.Y+len); break; case AxisTickMarksEnum.Outside: default: s = new Point(p.X, p.Y+len); e = new Point(p.X, p.Y); break; } Style style = gl.Style; if (style != null) style.DrawStyleLine(rpt, g, null, s, e); else g.DrawLine(Pens.Black, s, e); return; } // Calculate the size of the value axis; width is max value width + title width // height is max value height protected Size ValueAxisSize(Report rpt, Graphics g, double min, double max) { Size size=Size.Empty; if (ChartDefn.ValueAxis == null) return size; Axis a = ChartDefn.ValueAxis.Axis; if (a == null) return size; Size minSize; Size maxSize; if (!a.Visible) { minSize = maxSize = Size.Empty; } else if (a.Style != null) { minSize = a.Style.MeasureString(rpt, g, min, TypeCode.Double, null, int.MaxValue); maxSize = a.Style.MeasureString(rpt, g, max, TypeCode.Double, null, int.MaxValue); } else { minSize = Style.MeasureStringDefaults(rpt, g, min, TypeCode.Double, null, int.MaxValue); maxSize = Style.MeasureStringDefaults(rpt, g, max, TypeCode.Double, null, int.MaxValue); } // Choose the largest size.Width = Math.Max(minSize.Width, maxSize.Width); size.Height = Math.Max(minSize.Height, maxSize.Height); // Now we need to add in the height of the title (if any) Size titleSize = DrawTitleMeasure(rpt, g, a.Title); size.Height += titleSize.Height; if (a.MajorTickMarks == AxisTickMarksEnum.Cross || a.MajorTickMarks == AxisTickMarksEnum.Outside) size.Height += this.AxisTickMarkMajorLen; else if (a.MinorTickMarks == AxisTickMarksEnum.Cross || a.MinorTickMarks == AxisTickMarksEnum.Outside) size.Height += this.AxisTickMarkMinorLen; return size; } } }
using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Arebis.Types; namespace Arebis.Extensions.Tests.Arebis.Types { /// <summary> /// Summary description for PerformanceTests /// </summary> [TestClass] public class UnitPerformanceTests { const double MAX_ACCEPTABLE_VARIANCE = +0.25; const double MIN_ACCEPTABLE_VARIANCE = -0.25; #region Initialize & cleanup private UnitManager defaultUnitManager; [TestInitialize()] public void MyTestInitialize() { Console.Write("Resetting the UnitManager instance..."); this.defaultUnitManager = UnitManager.Instance; UnitManager.Instance = new UnitManager(); UnitManager.RegisterByAssembly(typeof(global::Arebis.Types.LengthUnits).Assembly); Console.WriteLine(" done."); } [TestCleanup()] public void MyTestCleanup() { UnitManager.Instance = this.defaultUnitManager; } #endregion Initialize & cleanup [TestMethod] public void AmountAdditionPerformanceTest() { Amount a = new Amount(15m, LengthUnits.Meter); Amount sum = new Amount(0m, LengthUnits.Meter); long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { sum += a; } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.031) / 0.031; Console.WriteLine("Time to perform 100K additions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var*100); Assert.AreEqual(1500000m, sum.Value); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); //if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void AmountDerivedAdditionPerformanceTest() { Amount sum = new Amount(0m, LengthUnits.KiloMeter); long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { sum += new Amount(15m, LengthUnits.Meter); } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.219) / 0.219; Console.WriteLine("Sum = {0}", sum); Console.WriteLine("Time to perform 100K additions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var*100); Assert.AreEqual(1500m, sum.Value); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void AmountSimpleDivisionPerformanceTest() { Amount a = new Amount(15m, LengthUnits.Meter); Amount b = new Amount(3m, TimeUnits.Second); Amount q = null; long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { q = a / b; } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.11) / 0.11; Console.WriteLine("Time to perform 100K simple divisions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.AreEqual(5m, q.Value); Assert.IsTrue(q.Unit.CompatibleTo(LengthUnits.Meter / TimeUnits.Second)); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void AmountComplexDivisionPerformanceTest() { Amount a = new Amount(15m, LengthUnits.KiloMeter); Amount b = new Amount(3m, TimeUnits.Hour); Amount q = null; long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { q = a / b; } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.11) / 0.11; Console.WriteLine("Time to perform 100K complex divisions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.AreEqual(5m, q.Value); Assert.AreEqual(5m, q.ConvertedTo(LengthUnits.KiloMeter / TimeUnits.Hour, 8).Value); Assert.IsTrue(q.Unit.CompatibleTo(LengthUnits.Meter / TimeUnits.Second)); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void AmountScenario01PerformanceTest() { Amount distance; Amount speed; Amount duration = new Amount(0m, TimeUnits.Day); long t = Environment.TickCount; for (int n = 1; n <= 10000; n++) { distance = new Amount(50m, new Unit("myfoot", "myft", 44m, LengthUnits.CentiMeter)); speed = new Amount(n, LengthUnits.KiloMeter / TimeUnits.Hour); duration += distance / speed; } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.234) / 0.234; duration = duration.ConvertedTo(TimeUnits.Minute, 1); Console.WriteLine("Time to perform 10K complex scenario: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.AreEqual(12.9m, duration.Value); Assert.IsTrue(duration.Unit.CompatibleTo(TimeUnits.Second)); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void AmountSimpleConvertPerformanceTest() { Amount a = new Amount(15m, LengthUnits.KiloMeter); Amount b = null; long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { b = a.ConvertedTo(LengthUnits.Meter, 8); } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.172) / 0.172; Console.WriteLine("Result = {0}", b); Console.WriteLine("Time to perform 100K convertions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.AreEqual(15000m, b.Value); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void AmountComplexConvertPerformanceTest() { Amount a = new Amount(15m, (LengthUnits.KiloMeter * LengthUnits.Meter / LengthUnits.MilliMeter / (TimeUnits.Hour * TimeUnits.Minute / TimeUnits.MilliSecond))); Amount b = null; Unit targetUnit = LengthUnits.Meter / TimeUnits.Second; long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { b = a.ConvertedTo(targetUnit, 8); } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.203) / 0.203; Console.WriteLine("Original = {0}", a); Console.WriteLine("Result = {0}", b); Console.WriteLine("Time to perform 100K convertions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.AreEqual(0.06944444m, b.Value); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void UnitManagerResolveNamedToNamedTest() { // Try resolving a named unit: Unit u = LengthUnits.KiloMeter; Unit v = null; long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { v = UnitManager.ResolveToNamedUnit(u, true); } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.015) / 0.015; Console.WriteLine("Original = {0}", u.Name); Console.WriteLine("Result = {0}", v.Name); Console.WriteLine("Time to perform 100K resolutions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.IsTrue(v.IsNamed); Assert.AreEqual("kilometer", v.Name); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void UnitManagerResolveKnownToNamedTest() { // Try resolving a known unit: Unit u = LengthUnits.Meter / TimeUnits.Second; Unit v = null; long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { v = UnitManager.ResolveToNamedUnit(u, true); } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.219) / 0.219; Console.WriteLine("Original = {0}", u.Name); Console.WriteLine("Result = {0}", v.Name); Console.WriteLine("Time to perform 100K resolutions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.IsTrue(v.IsNamed); Assert.AreEqual("meter/second", v.Name); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void UnitManagerResolveUnknownToNamedTest() { // Try resolving an unknown unit of a known family: Unit u = LengthUnits.NauticalMile / TimeUnits.Minute; Unit v = null; long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { v = UnitManager.ResolveToNamedUnit(u, true); } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.297) / 0.297; Console.WriteLine("Original = {0}", u.Name); Console.WriteLine("Result = {0}", v.Name); Console.WriteLine("Time to perform 100K resolutions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.IsFalse(v.IsNamed); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } [TestMethod] public void UnitManagerResolveUnfamiliarToNamedTest() { // Try resolving a unit of an unknown family: Unit u = LengthUnits.Meter * ElectricUnits.Ohm; Unit v = null; long t = Environment.TickCount; for (int n = 0; n < 100000; n++) { v = UnitManager.ResolveToNamedUnit(u, true); } double time = (Environment.TickCount - t) / 1000.0; double var = (time - 0.032) / 0.032; Console.WriteLine("Original = {0}", u.Name); Console.WriteLine("Result = {0}", v.Name); Console.WriteLine("Time to perform 100K resolutions: {0} sec.", time); Console.WriteLine("Variation: {0:0}%.", var * 100); Assert.IsFalse(v.IsNamed); Assert.IsTrue(var < MAX_ACCEPTABLE_VARIANCE, "Performance lost detected!"); if (var < MIN_ACCEPTABLE_VARIANCE) Assert.Inconclusive("Performance was much better than expected."); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; using Pathfinding.RVO; namespace Pathfinding.RVO { /** Base class for simple RVO colliders. * * This is a helper base class for RVO colliders. It provides automatic gizmos * and helps with the winding order of the vertices as well as automatically updating the obstacle when moved. * * Extend this class to create custom RVO obstacles. * * \see writing-rvo-colliders * \see RVOSquareObstacle * * \astarpro */ public abstract class RVOObstacle : MonoBehaviour { /** Mode of the obstacle. * Determines winding order of the vertices */ public ObstacleVertexWinding obstacleMode; /** RVO Obstacle Modes. * Determines winding order of obstacle vertices */ public enum ObstacleVertexWinding { KeepOut, /**< Keeps agents from entering the obstacle */ KeepIn, /**< Keeps agents inside the obstacle */ Both /**< Keeps agents from crossing the obstacle border in either direction */ } /** Reference to simulator */ protected Pathfinding.RVO.Simulator sim; /** All obstacles added */ private List<ObstacleVertex> addedObstacles; /** Original vertices for the obstacles */ private List<Vector3[]> sourceObstacles; /** Create Obstacles. * Override this and add logic for creating obstacles. * You should not use the simulator's function calls directly. * * \see AddObstacle */ protected abstract void CreateObstacles (); /** Enable executing in editor to draw gizmos. * If enabled, the CreateObstacles function will be executed in the editor as well * in order to draw gizmos. */ protected abstract bool ExecuteInEditor {get;} /** If enabled, all coordinates are handled as local. */ protected abstract bool LocalCoordinates {get;} /** Static or dynamic. * This determines if the obstacle can be updated by e.g moving the transform * around in the scene. */ protected abstract bool StaticObstacle {get; } /** Called in the editor. * This function should return true if any variables which can change the shape or position of the obstacle * has changed since the last call to this function. Take a look at the RVOSquareObstacle for an example. */ protected abstract bool AreGizmosDirty (); /** Enabled if currently in OnDrawGizmos */ private bool gizmoDrawing = false; /** Vertices for gizmos */ private List<Vector3[]> gizmoVerts; /** Last obstacle mode. * Used to check if the gizmos should be updated */ private ObstacleVertexWinding _obstacleMode; /** Last matrix the obstacle was updated with. * Used to check if the obstacle should be updated */ private Matrix4x4 prevUpdateMatrix; /** Draws Gizmos */ public void OnDrawGizmos () { OnDrawGizmos (false); } /** Draws Gizmos */ public void OnDrawGizmosSelected () { OnDrawGizmos (true); } /** Draws Gizmos */ public void OnDrawGizmos (bool selected) { gizmoDrawing = true; Gizmos.color = new Color (0.615f,1,0.06f,selected ? 1.0f : 0.7f); if (gizmoVerts == null || AreGizmosDirty() || _obstacleMode != obstacleMode) { _obstacleMode = obstacleMode; if (gizmoVerts == null) gizmoVerts = new List<Vector3[]>(); else gizmoVerts.Clear (); CreateObstacles (); } Matrix4x4 m = GetMatrix(); for (int i=0;i<gizmoVerts.Count;i++) { Vector3[] verts = gizmoVerts[i]; for (int j=0,q=verts.Length-1;j<verts.Length;q=j++) { Gizmos.DrawLine (m.MultiplyPoint3x4(verts[j]),m.MultiplyPoint3x4(verts[q])); } if (selected && obstacleMode != ObstacleVertexWinding.Both) { for (int j=0,q=verts.Length-1;j<verts.Length;q=j++) { Vector3 a = m.MultiplyPoint3x4(verts[q]); Vector3 b = m.MultiplyPoint3x4(verts[j]); Vector3 avg = (a + b) * 0.5f; Vector3 tang = (b - a).normalized; if (tang == Vector3.zero) continue; Vector3 normal = Vector3.Cross (Vector3.up,tang); Gizmos.DrawLine (avg,avg+normal); Gizmos.DrawLine (avg+normal,avg+normal*0.5f+tang*0.5f); Gizmos.DrawLine (avg+normal,avg+normal*0.5f-tang*0.5f); } } } gizmoDrawing = false; } /** Get's the matrix to use for vertices. * Can be overriden for custom matrices. * \returns transform.localToWorldMatrix if LocalCoordinates is true, otherwise Matrix4x4.identity */ protected virtual Matrix4x4 GetMatrix () { if (LocalCoordinates) return transform.localToWorldMatrix; else return Matrix4x4.identity; } /** Disables the obstacle. * Do not override this function */ public void OnDisable () { if (addedObstacles != null) { if (sim == null) throw new System.Exception ("This should not happen! Make sure you are not overriding the OnEnable function"); for (int i=0;i<addedObstacles.Count;i++) { sim.RemoveObstacle (addedObstacles[i]); } } } /** Enabled the obstacle. * Do not override this function */ public void OnEnable () { if (addedObstacles != null) { if (sim == null) throw new System.Exception ("This should not happen! Make sure you are not overriding the OnDisable function"); for (int i=0;i<addedObstacles.Count;i++) { sim.AddObstacle (addedObstacles[i]); } } } /** Creates obstacles */ public void Start () { addedObstacles = new List<ObstacleVertex>(); sourceObstacles = new List<Vector3[]>(); prevUpdateMatrix = GetMatrix(); CreateObstacles (); } /** Updates obstacle if required. * Checks for if the obstacle should be updated (e.g if it has moved) */ public void Update () { Matrix4x4 m = GetMatrix(); if (m != prevUpdateMatrix) { for (int i=0;i<addedObstacles.Count;i++) { sim.UpdateObstacle (addedObstacles[i],sourceObstacles[i],m); } prevUpdateMatrix = m; } } /** Finds a simulator in the scene. * * Saves found simulator in #sim. * * \throws System.InvalidOperationException When no RVOSimulator could be found. */ protected void FindSimulator () { RVOSimulator rvosim = FindObjectOfType(typeof(RVOSimulator)) as RVOSimulator; if (rvosim == null) throw new System.InvalidOperationException ("No RVOSimulator could be found in the scene. Please add one to any GameObject"); sim = rvosim.GetSimulator (); } /** Adds an obstacle with the specified vertices. * The vertices array might be changed by this function. */ protected void AddObstacle (Vector3[] vertices, float height) { if (vertices == null) throw new System.ArgumentNullException ("Vertices Must Not Be Null"); if (height < 0) throw new System.ArgumentOutOfRangeException ("Height must be non-negative"); if (vertices.Length < 2) throw new System.ArgumentException ("An obstacle must have at least two vertices"); if (gizmoDrawing) { //Matrix4x4 m = GetMatrix(); //if (!m.isIdentity) for (int i=0;i<vertices.Length;i++) vertices[i] = m.MultiplyPoint3x4(vertices[i]); Vector3[] v = new Vector3[vertices.Length]; WindCorrectly (vertices); System.Array.Copy(vertices,v,vertices.Length); gizmoVerts.Add (v); return; } if (sim == null) FindSimulator (); if (vertices.Length == 2) { AddObstacleInternal (vertices, height); return; } if (obstacleMode == ObstacleVertexWinding.Both) { for (int i=0,j=vertices.Length-1;i<vertices.Length;j = i++) { AddObstacleInternal (new Vector3[] {vertices[j],vertices[i]},height); } } else { WindCorrectly (vertices); AddObstacleInternal (vertices,height); } } /** Adds an obstacle. * Winding is assumed to be correct and very little error checking is done. */ private void AddObstacleInternal (Vector3[] vertices, float height) { addedObstacles.Add (sim.AddObstacle (vertices,height, GetMatrix())); sourceObstacles.Add (vertices); } /** Winds the vertices correctly. * Winding order is determined from #obstacleMode. */ private void WindCorrectly (Vector3[] vertices) { if (obstacleMode == ObstacleVertexWinding.Both) return; int leftmost = 0; float leftmostX = float.PositiveInfinity; for (int i=0;i<vertices.Length;i++) { if (vertices[i].x < leftmostX) { leftmost = i; leftmostX = vertices[i].x; } } if (Polygon.IsClockwise (vertices[(leftmost-1 + vertices.Length) % vertices.Length], vertices[leftmost], vertices[(leftmost+1) % vertices.Length])) { if (obstacleMode == ObstacleVertexWinding.KeepOut) System.Array.Reverse (vertices); } else { if (obstacleMode == ObstacleVertexWinding.KeepIn) System.Array.Reverse (vertices); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public static partial class VirtualNetworkGatewaysOperationsExtensions { /// <summary> /// The Put VirtualNetworkGateway operation creates/updates a virtual network /// gateway in the specified resource group through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// operation through Network resource provider. /// </param> public static VirtualNetworkGateway CreateOrUpdate(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).CreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetworkGateway operation creates/updates a virtual network /// gateway in the specified resource group through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> CreateOrUpdateAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<VirtualNetworkGateway> result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put VirtualNetworkGateway operation creates/updates a virtual network /// gateway in the specified resource group through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// operation through Network resource provider. /// </param> public static VirtualNetworkGateway BeginCreateOrUpdate(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetworkGateway operation creates/updates a virtual network /// gateway in the specified resource group through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> BeginCreateOrUpdateAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<VirtualNetworkGateway> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Get VirtualNetworkGateway operation retrieves information about the /// specified virtual network gateway through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static VirtualNetworkGateway Get(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).GetAsync(resourceGroupName, virtualNetworkGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get VirtualNetworkGateway operation retrieves information about the /// specified virtual network gateway through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> GetAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<VirtualNetworkGateway> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Delete VirtualNetworkGateway operation deletes the specifed virtual /// network Gateway through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static void Delete(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).DeleteAsync(resourceGroupName, virtualNetworkGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete VirtualNetworkGateway operation deletes the specifed virtual /// network Gateway through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Delete VirtualNetworkGateway operation deletes the specifed virtual /// network Gateway through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static void BeginDelete(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).BeginDeleteAsync(resourceGroupName, virtualNetworkGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete VirtualNetworkGateway operation deletes the specifed virtual /// network Gateway through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The List VirtualNetworkGateways opertion retrieves all the virtual network /// gateways stored. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<VirtualNetworkGateway> List(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List VirtualNetworkGateways opertion retrieves all the virtual network /// gateways stored. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGateway>> ListAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<VirtualNetworkGateway>> result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Reset VirtualNetworkGateway operation resets the primary of the /// virtual network gateway in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway operation /// through Network resource provider. /// </param> public static VirtualNetworkGateway Reset(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).ResetAsync(resourceGroupName, virtualNetworkGatewayName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Reset VirtualNetworkGateway operation resets the primary of the /// virtual network gateway in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway operation /// through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> ResetAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<VirtualNetworkGateway> result = await operations.ResetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Reset VirtualNetworkGateway operation resets the primary of the /// virtual network gateway in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway operation /// through Network resource provider. /// </param> public static VirtualNetworkGateway BeginReset(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).BeginResetAsync(resourceGroupName, virtualNetworkGatewayName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Reset VirtualNetworkGateway operation resets the primary of the /// virtual network gateway in the specified resource group through Network /// resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway operation /// through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> BeginResetAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<VirtualNetworkGateway> result = await operations.BeginResetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Generatevpnclientpackage operation generates Vpn client package for /// P2S client of the virtual network gateway in the specified resource group /// through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Generating Virtual Network Gateway Vpn /// client package operation through Network resource provider. /// </param> public static string Generatevpnclientpackage(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).GeneratevpnclientpackageAsync(resourceGroupName, virtualNetworkGatewayName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Generatevpnclientpackage operation generates Vpn client package for /// P2S client of the virtual network gateway in the specified resource group /// through Network resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Generating Virtual Network Gateway Vpn /// client package operation through Network resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> GeneratevpnclientpackageAsync( this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<string> result = await operations.GeneratevpnclientpackageWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The List VirtualNetworkGateways opertion retrieves all the virtual network /// gateways stored. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetworkGateway> ListNext(this IVirtualNetworkGatewaysOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IVirtualNetworkGatewaysOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List VirtualNetworkGateways opertion retrieves all the virtual network /// gateways stored. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGateway>> ListNextAsync( this IVirtualNetworkGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<VirtualNetworkGateway>> result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework; namespace NUnit.Engine.Services.Tests { using Fakes; /// <summary> /// This fixture is used to test both RecentProjects and /// its base class RecentFiles. If we add any other derived /// classes, the tests should be refactored. /// </summary> [TestFixture] public class RecentFilesTests { private const int MAX = 24; private const int MIN = 0; private const int DEFAULT = 5; RecentFilesService _recentFiles; [SetUp] public void SetUp() { var services = new ServiceContext(); services.Add(new FakeSettingsService()); _recentFiles = new RecentFilesService(); services.Add(_recentFiles); services.ServiceManager.StartServices(); } [Test] public void ServiceIsStarted() { Assert.That(_recentFiles.Status, Is.EqualTo(ServiceStatus.Started)); } [Test] public void CountDefault() { Assert.AreEqual( DEFAULT, _recentFiles.MaxFiles ); } [Test] public void CountOverMax() { _recentFiles.MaxFiles = MAX + 1; Assert.AreEqual( MAX, _recentFiles.MaxFiles ); } [Test] public void CountUnderMin() { _recentFiles.MaxFiles = MIN - 1; Assert.AreEqual( MIN, _recentFiles.MaxFiles ); } [Test] public void CountAtMax() { _recentFiles.MaxFiles = MAX; Assert.AreEqual( MAX, _recentFiles.MaxFiles ); } [Test] public void CountAtMin() { _recentFiles.MaxFiles = MIN; Assert.AreEqual( MIN, _recentFiles.MaxFiles ); } [Test] public void EmptyList() { Assert.IsNotNull( _recentFiles.Entries, "Entries should never be null" ); Assert.AreEqual( 0, _recentFiles.Entries.Count ); } [Test] public void AddSingleItem() { CheckAddItems( 1 ); } [Test] public void AddMaxItems() { CheckAddItems( 5 ); } [Test] public void AddTooManyItems() { CheckAddItems( 10 ); } [Test] public void IncreaseSize() { _recentFiles.MaxFiles = 10; CheckAddItems( 10 ); } [Test] public void ReduceSize() { _recentFiles.MaxFiles = 3; CheckAddItems( 10 ); } [Test] public void IncreaseSizeAfterAdd() { SetMockValues(5); _recentFiles.MaxFiles = 7; _recentFiles.SetMostRecent( "30" ); _recentFiles.SetMostRecent( "20" ); _recentFiles.SetMostRecent( "10" ); CheckListContains( 10, 20, 30, 1, 2, 3, 4 ); } [Test] public void ReduceSizeAfterAdd() { SetMockValues( 5 ); _recentFiles.MaxFiles = 3; CheckMockValues( 3 ); } [Test] public void ReorderLastProject() { SetMockValues( 5 ); _recentFiles.SetMostRecent( "5" ); CheckListContains( 5, 1, 2, 3, 4 ); } [Test] public void ReorderSingleProject() { SetMockValues( 5 ); _recentFiles.SetMostRecent( "3" ); CheckListContains( 3, 1, 2, 4, 5 ); } [Test] public void ReorderMultipleProjects() { SetMockValues( 5 ); _recentFiles.SetMostRecent( "3" ); _recentFiles.SetMostRecent( "5" ); _recentFiles.SetMostRecent( "2" ); CheckListContains( 2, 5, 3, 1, 4 ); } [Test] public void ReorderSameProject() { SetMockValues( 5 ); _recentFiles.SetMostRecent( "1" ); CheckListContains( 1, 2, 3, 4, 5 ); } [Test] public void ReorderWithListNotFull() { SetMockValues( 3 ); _recentFiles.SetMostRecent( "3" ); CheckListContains( 3, 1, 2 ); } [Test] public void RemoveFirstProject() { SetMockValues( 3 ); _recentFiles.Remove("1"); CheckListContains( 2, 3 ); } [Test] public void RemoveOneProject() { SetMockValues( 4 ); _recentFiles.Remove("2"); CheckListContains( 1, 3, 4 ); } [Test] public void RemoveMultipleProjects() { SetMockValues( 5 ); _recentFiles.Remove( "3" ); _recentFiles.Remove( "1" ); _recentFiles.Remove( "4" ); CheckListContains( 2, 5 ); } [Test] public void RemoveLastProject() { SetMockValues( 5 ); _recentFiles.Remove("5"); CheckListContains( 1, 2, 3, 4 ); } #region Helper Methods // Set RecentFiles to a list of known values up // to a maximum. Most recent will be "1", next // "2", and so on... private void SetMockValues(int count) { for (int num = count; num > 0; --num) _recentFiles.SetMostRecent(num.ToString()); } // Check that the list is set right: 1, 2, ... private void CheckMockValues(int count) { var files = _recentFiles.Entries; Assert.AreEqual(count, files.Count, "Count"); for (int index = 0; index < count; index++) Assert.AreEqual((index + 1).ToString(), files[index], "Item"); } // Check that we can add count items correctly private void CheckAddItems(int count) { SetMockValues(count); Assert.AreEqual("1", _recentFiles.Entries[0], "RecentFile"); CheckMockValues(Math.Min(count, _recentFiles.MaxFiles)); } // Check that the list contains a set of entries // in the order given and nothing else. private void CheckListContains(params int[] item) { var files = _recentFiles.Entries; Assert.AreEqual(item.Length, files.Count, "Count"); for (int index = 0; index < files.Count; index++) Assert.AreEqual(item[index].ToString(), files[index], "Item"); } #endregion } }
using System; using System.Collections.Generic; using Nop.Core.Domain.Catalog; namespace Nop.Core.Domain.Orders { /// <summary> /// Represents a recurring payment /// </summary> public partial class RecurringPayment : BaseEntity { private ICollection<RecurringPaymentHistory> _recurringPaymentHistory; /// <summary> /// Gets or sets the cycle length /// </summary> public int CycleLength { get; set; } /// <summary> /// Gets or sets the cycle period identifier /// </summary> public int CyclePeriodId { get; set; } /// <summary> /// Gets or sets the total cycles /// </summary> public int TotalCycles { get; set; } /// <summary> /// Gets or sets the start date /// </summary> public DateTime StartDateUtc { get; set; } /// <summary> /// Gets or sets a value indicating whether the payment is active /// </summary> public bool IsActive { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity has been deleted /// </summary> public bool Deleted { get; set; } /// <summary> /// Gets or sets the initial order identifier /// </summary> public int InitialOrderId { get; set; } /// <summary> /// Gets or sets the date and time of payment creation /// </summary> public DateTime CreatedOnUtc { get; set; } /// <summary> /// Gets the next payment date /// </summary> public DateTime? NextPaymentDate { get { //result DateTime? result = null; if (!this.IsActive) return result; var historyCollection = this.RecurringPaymentHistory; if (historyCollection.Count >= this.TotalCycles) { return result; } //set another value to change calculation method //bool useLatestPayment = false; //if (useLatestPayment) //{ // //get latest payment // RecurringPaymentHistory latestPayment = null; // foreach (var historyRecord in historyCollection) // { // if (latestPayment != null) // { // if (historyRecord.CreatedOnUtc >= latestPayment.CreatedOnUtc) // { // latestPayment = historyRecord; // } // } // else // { // latestPayment = historyRecord; // } // } // //calculate next payment date // if (latestPayment != null) // { // switch (this.CyclePeriod) // { // case RecurringProductCyclePeriod.Days: // result = latestPayment.CreatedOnUtc.AddDays((double)this.CycleLength); // break; // case RecurringProductCyclePeriod.Weeks: // result = latestPayment.CreatedOnUtc.AddDays((double)(7 * this.CycleLength)); // break; // case RecurringProductCyclePeriod.Months: // result = latestPayment.CreatedOnUtc.AddMonths(this.CycleLength); // break; // case RecurringProductCyclePeriod.Years: // result = latestPayment.CreatedOnUtc.AddYears(this.CycleLength); // break; // default: // throw new NopException("Not supported cycle period"); // } // } // else // { // if (this.TotalCycles > 0) // result = this.StartDateUtc; // } //} //else //{ if (historyCollection.Count > 0) { switch (this.CyclePeriod) { case RecurringProductCyclePeriod.Days: result = this.StartDateUtc.AddDays((double)this.CycleLength * historyCollection.Count); break; case RecurringProductCyclePeriod.Weeks: result = this.StartDateUtc.AddDays((double)(7 * this.CycleLength) * historyCollection.Count); break; case RecurringProductCyclePeriod.Months: result = this.StartDateUtc.AddMonths(this.CycleLength * historyCollection.Count); break; case RecurringProductCyclePeriod.Years: result = this.StartDateUtc.AddYears(this.CycleLength * historyCollection.Count); break; default: throw new NopException("Not supported cycle period"); } } else { if (this.TotalCycles > 0) result = this.StartDateUtc; } //} return result; } } /// <summary> /// Gets the cycles remaining /// </summary> public int CyclesRemaining { get { //result var historyCollection = this.RecurringPaymentHistory; int result = this.TotalCycles - historyCollection.Count; if (result < 0) result = 0; return result; } } /// <summary> /// Gets or sets the payment status /// </summary> public RecurringProductCyclePeriod CyclePeriod { get { return (RecurringProductCyclePeriod)this.CyclePeriodId; } set { this.CyclePeriodId = (int)value; } } /// <summary> /// Gets or sets the recurring payment history /// </summary> public virtual ICollection<RecurringPaymentHistory> RecurringPaymentHistory { get { return _recurringPaymentHistory ?? (_recurringPaymentHistory = new List<RecurringPaymentHistory>()); } protected set { _recurringPaymentHistory = value; } } /// <summary> /// Gets the initial order /// </summary> public virtual Order InitialOrder { get; set; } } }
// // System.Web.UI.WebControls.MultiView.cs // // Authors: // Lluis Sanchez Gual (lluis@novell.com) // // (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // #if NET_2_0 using System; using System.Globalization; using System.Web; using System.Web.UI; using System.ComponentModel; namespace System.Web.UI.WebControls { // [ControlBuilder (typeof(MultiViewControlBuilder)] [Designer ("System.Web.UI.Design.WebControls.MultiViewDesigner, System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.IDesigner")] [ToolboxData ("<{0}:MultiView runat=\"server\"></{0}:MultiView>")] [ParseChildren (false, ChildControlType = typeof(View))] [DefaultEvent ("ActiveViewChanged")] public class MultiView: Control { public static readonly string NextViewCommandName = "NextView"; public static readonly string PreviousViewCommandName = "PrevView"; public static readonly string SwitchViewByIDCommandName = "SwitchViewByID"; public static readonly string SwitchViewByIndexCommandName = "SwitchViewByIndex"; private static readonly object ActiveViewChangedEvent = new object(); int viewIndex = -1; int initialIndex = -1; bool initied; public event EventHandler ActiveViewChanged { add { Events.AddHandler (ActiveViewChangedEvent, value); } remove { Events.RemoveHandler (ActiveViewChangedEvent, value); } } protected override void AddParsedSubObject (object ob) { if (ob is View) Controls.Add (ob as View); } protected override ControlCollection CreateControlCollection () { return new ViewCollection (this); } public View GetActiveView () { if (viewIndex < 0 || viewIndex >= Controls.Count) throw new HttpException ("The ActiveViewIndex is not set to a valid View control"); return Controls [viewIndex] as View; } public void SetActiveView (View view) { int i = Controls.IndexOf (view); if (i == -1) throw new HttpException ("The provided view is not contained in the MultiView control."); ActiveViewIndex = i; } [DefaultValue (-1)] public virtual int ActiveViewIndex { get { return viewIndex; } set { if (!initied) { initialIndex = value; return; } if (value < -1 || value >= Controls.Count) throw new ArgumentOutOfRangeException (); if (viewIndex != -1) ((View)Controls [viewIndex]).NotifyActivation (false); viewIndex = value; if (viewIndex != -1) ((View)Controls [viewIndex]).NotifyActivation (true); UpdateViewVisibility (); } } [PersistenceMode (PersistenceMode.InnerDefaultProperty)] [Browsable (false)] public virtual ViewCollection Views { get { return Controls as ViewCollection; } } protected override bool OnBubbleEvent (object source, EventArgs e) { CommandEventArgs ca = e as CommandEventArgs; if (ca != null) { switch (ca.CommandName) { case "NextView": if (viewIndex < Controls.Count - 1 && Controls.Count > 0) ActiveViewIndex = viewIndex + 1; break; case "PrevView": if (viewIndex > 0) ActiveViewIndex = viewIndex - 1; break; case "SwitchViewByID": foreach (View v in Controls) if (v.ID == ca.CommandArgument) { SetActiveView (v); break; } break; case "SwitchViewByIndex": int i = (int) Convert.ChangeType (ca.CommandArgument, typeof(int)); ActiveViewIndex = i; break; } } return false; } protected override void OnInit (EventArgs e) { initied = true; Page.RegisterRequiresControlState (this); if (initialIndex != -1) { ActiveViewIndex = initialIndex; initialIndex = -1; } base.OnInit (e); } void UpdateViewVisibility () { for (int n=0; n<Views.Count; n++) Views [n].Visible = (n == viewIndex); } protected internal override void RemovedControl (Control ctl) { if (viewIndex >= Controls.Count) { viewIndex = Controls.Count - 1; UpdateViewVisibility (); } base.RemovedControl (ctl); } protected internal override void LoadControlState (object state) { if (state != null) { viewIndex = (int)state; UpdateViewVisibility (); } else viewIndex = -1; } protected internal override object SaveControlState () { if (viewIndex != -1) return viewIndex; else return null; } protected virtual void OnActiveViewChanged (EventArgs e) { if (Events != null) { EventHandler eh = (EventHandler) Events [ActiveViewChangedEvent]; if (eh != null) eh (this, e); } } protected override void Render (HtmlTextWriter writer) { if (!initied) viewIndex = initialIndex; if (viewIndex != -1) GetActiveView ().Render (writer); } } } #endif
namespace DynamicUI { using UnityEngine; using DynamicUI; using UnityEngine.UI; using UnityEngine.Events; [ExecuteInEditMode] public class DUICreateUserScreen : DUIScreen { [SerializeField] Elements m_elements; [SerializeField] UserEventHandler m_onUserCreated; public UserEventHandler onUserCreated { get { return m_onUserCreated; } } public Elements elements { get { return m_elements; } } public override bool allowUpdatingElements { get { return false; } } #region Initilization protected virtual void BindElements() { elements.Bind(this); } public override void Init(DUICanvas canvas) { base.Init(canvas); elements.passwordField.validator = GetPasswordValidator; elements.passwordConfirmField.validator = GetConfirmPasswordValidator; elements.userNameField.validator = GetUsernameValidator; elements.passwordField.inputField.onValueChanged.AddListener(OnFieldEditEnd); elements.passwordConfirmField.inputField.onValueChanged.AddListener(OnFieldEditEnd); elements.userNameField.inputField.onValueChanged.AddListener(OnFieldEditEnd); elements.createButton.onClick.AddListener(OnCreateButtonPressed); } #endregion Initilization #region Elements [System.Serializable] public class Elements { [SerializeField] DUIValidationField m_passwordField; [SerializeField] DUIValidationField m_userNameField; [SerializeField] Button m_createButton; [SerializeField] DUIValidationField m_passwordConfirmField; public DUIValidationField passwordField { get { return m_passwordField; } } public DUIValidationField userNameField { get { return m_userNameField; } } public Button createButton { get { return m_createButton; } } public DUIValidationField passwordConfirmField { get { return m_passwordConfirmField; } } public void Bind(DUICreateUserScreen screen) { #if UNITY_EDITOR var root = screen.transform; var so = new UnityEditor.SerializedObject(screen).FindProperty("m_elements"); so.FindPropertyRelative("m_passwordField").objectReferenceValue = root.FindChild("passwordField").GetComponent<DUIValidationField>(); so.FindPropertyRelative("m_userNameField").objectReferenceValue = root.FindChild("userNameField").GetComponent<DUIValidationField>(); so.FindPropertyRelative("m_passwordConfirmField").objectReferenceValue = root.FindChild("passwordConfirmField").GetComponent<DUIValidationField>(); so.FindPropertyRelative("m_createButton").objectReferenceValue = root.FindChild("createButton").GetComponent<Button>(); so.serializedObject.ApplyModifiedProperties(); UnityEditor.EditorUtility.SetDirty(screen); #endif } } #endregion Elements #region Events Validator GetUsernameValidator(string userName) { var validator = new Validator(); if (string.IsNullOrEmpty(userName) || userName.Length < 3) { validator.errorMessage = Local.Translate("User name should be at least 3 characters long!"); return validator; } validator.isValid = true; return validator; } Validator GetPasswordValidator(string password) { var validator = new Validator(); if(string.IsNullOrEmpty(password) || password.Length < 3) { validator.errorMessage = Local.Translate("Password should be at least 3 characters long!"); return validator; } validator.isValid = true; return validator; } Validator GetConfirmPasswordValidator(string passwordConfirm) { var validator = new Validator(); if (elements.passwordField.isValid == false) { validator.errorMessage = Local.Translate("Invalid password!"); return validator; } if (passwordConfirm != elements.passwordField.inputField.text) { validator.errorMessage = Local.Translate("Passwords do not match!"); return validator; } validator.isValid = true; return validator; } void OnCreateButtonPressed() { elements.userNameField.Check(); elements.passwordField.Check(); elements.passwordConfirmField.Check(); if(IsReadyToSubmit()) { Hide(); onUserCreated.Invoke(elements.userNameField.inputField.text, elements.passwordField.inputField.text); } } bool IsReadyToSubmit() { return elements.userNameField.isValid && elements.passwordConfirmField.isValid && elements.passwordField.isValid; } void OnFieldEditEnd(string text) { bool ready = IsReadyToSubmit(); if(ready) { CheckInputs(); } elements.createButton.interactable = ready; } void CheckInputs() { if (elements.userNameField.inputField.text != string.Empty) elements.userNameField.Check(); if (elements.passwordField.inputField.text != string.Empty) elements.passwordField.Check(); if (elements.passwordConfirmField.inputField.text != string.Empty) elements.passwordConfirmField.Check(); } void ClearInputs() { elements.passwordConfirmField.Clear(); elements.passwordField.Clear(); elements.userNameField.Clear(); } public override void Show() { ClearInputs(); CheckInputs(); base.Show(); } #endregion Events } [System.Serializable] public class UserEventHandler : UnityEvent<string, string> { public UserEventHandler() { } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using TimePunchAPI.Models; namespace TimePunchAPI.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20160509104526_AddTimeSpentToTimespan")] partial class AddTimeSpentToTimespan { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<long>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<long>("RoleId"); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<long>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<long>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<long>("UserId"); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<long>", b => { b.Property<long>("UserId"); b.Property<long>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("TimePunchAPI.Models.ApplicationRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("TimePunchAPI.Models.ApplicationUser", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("TimePunchAPI.Models.Issue", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.Property<long>("OriginalEstimate"); b.Property<int>("Priority"); b.Property<long>("ProjectId"); b.Property<long>("RemainingEstimate"); b.Property<string>("Summary"); b.Property<string>("Tag"); b.Property<int>("Type"); b.HasKey("Id"); }); modelBuilder.Entity("TimePunchAPI.Models.Project", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Key"); b.Property<long>("LeaderId"); b.Property<string>("Name"); b.Property<string>("Summary"); b.HasKey("Id"); }); modelBuilder.Entity("TimePunchAPI.Models.Timespan", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<long?>("ApplicationUserId"); b.Property<long>("IssueId"); b.Property<DateTime>("StartTime"); b.Property<DateTime>("StopTime"); b.Property<string>("Tag"); b.Property<long>("TimeSpent"); b.Property<long>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("TimePunchAPI.Models.UserProject", b => { b.Property<long>("UserId"); b.Property<long>("ProjectId"); b.HasKey("UserId", "ProjectId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<long>", b => { b.HasOne("TimePunchAPI.Models.ApplicationRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<long>", b => { b.HasOne("TimePunchAPI.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<long>", b => { b.HasOne("TimePunchAPI.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<long>", b => { b.HasOne("TimePunchAPI.Models.ApplicationRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("TimePunchAPI.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("TimePunchAPI.Models.Issue", b => { b.HasOne("TimePunchAPI.Models.Project") .WithMany() .HasForeignKey("ProjectId"); }); modelBuilder.Entity("TimePunchAPI.Models.Timespan", b => { b.HasOne("TimePunchAPI.Models.ApplicationUser") .WithMany() .HasForeignKey("ApplicationUserId"); b.HasOne("TimePunchAPI.Models.Issue") .WithMany() .HasForeignKey("IssueId"); }); modelBuilder.Entity("TimePunchAPI.Models.UserProject", b => { b.HasOne("TimePunchAPI.Models.Project") .WithMany() .HasForeignKey("ProjectId"); b.HasOne("TimePunchAPI.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MailChimpManager.cs" company="Brandon Seydel"> // N/A // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using MailChimp.Net.Core; using MailChimp.Net.Interfaces; using MailChimp.Net.Logic; #if NET_CORE using Microsoft.Extensions.Options; #endif namespace MailChimp.Net { /// <summary> /// The mail chimp manager. /// </summary> public class MailChimpManager : MailManagerBase, IMailChimpManager { public IMailChimpManager Configure(Action<MailChimpOptions> options) { options(MailChimpOptions); return this; } public MailChimpManager(string apiKey) : base(apiKey) { // The base implementation already sets the mail chimp options this.Activities = new ActivityLogic(MailChimpOptions); this.AbuseReports = new AbuseReportLogic(MailChimpOptions); this.Api = new ApiLogic(MailChimpOptions); this.Apps = new AuthorizedAppLogic(MailChimpOptions); this.AutomationEmails = new AutomationEmailLogic(MailChimpOptions); this.AutomationEmailQueues = new AutomationEmailQueueLogic(MailChimpOptions); this.Automations = new AutomationLogic(MailChimpOptions); this.AutomationSubscribers = new AutomationSubscriberLogic(MailChimpOptions); this.Batches = new BatchLogic(MailChimpOptions); this.Campaigns = new CampaignLogic(MailChimpOptions); this.CampaignFolders = new CampaignFolderLogic(MailChimpOptions); this.Clients = new ClientLogic(MailChimpOptions); this.Content = new ContentLogic(MailChimpOptions); this.Conversations = new ConversationLogic(MailChimpOptions); this.ECommerceStores = new ECommerceLogic(MailChimpOptions); this.Feedback = new FeedBackLogic(MailChimpOptions); this.FileManagerFiles = new FileManagerFileLogic(MailChimpOptions); this.FileManagerFolders = new FileManagerFolderLogic(MailChimpOptions); this.GrowthHistories = new GrowthHistoryLogic(MailChimpOptions); this.InterestCategories = new InterestCategoryLogic(MailChimpOptions); this.Interests = new InterestLogic(MailChimpOptions); this.Lists = new ListLogic(MailChimpOptions); this.ListSegments = new ListSegmentLogic(MailChimpOptions); this.Members = new MemberLogic(MailChimpOptions); this.MergeFields = new MergeFieldLogic(MailChimpOptions); this.Messages = new MessageLogic(MailChimpOptions); this.Notes = new NoteLogic(MailChimpOptions); this.Tags = new TagsLogic(MailChimpOptions); this.Reports = new ReportLogic(MailChimpOptions); this.TemplateFolders = new TemplateFolderLogic(MailChimpOptions); this.Templates = new TemplateLogic(MailChimpOptions); this.WebHooks = new WebHookLogic(MailChimpOptions); this.BatchWebHooks = new BatchWebHookLogic(MailChimpOptions); } #if NET_CORE public MailChimpManager(IOptions<MailChimpOptions> optionsAccessor) : base(optionsAccessor) { // The base implementation already sets the mail chimp options this.Activities = new ActivityLogic(MailChimpOptions); this.AbuseReports = new AbuseReportLogic(MailChimpOptions); this.Api = new ApiLogic(MailChimpOptions); this.Apps = new AuthorizedAppLogic(MailChimpOptions); this.AutomationEmails = new AutomationEmailLogic(MailChimpOptions); this.AutomationEmailQueues = new AutomationEmailQueueLogic(MailChimpOptions); this.Automations = new AutomationLogic(MailChimpOptions); this.AutomationSubscribers = new AutomationSubscriberLogic(MailChimpOptions); this.Batches = new BatchLogic(MailChimpOptions); this.Campaigns = new CampaignLogic(MailChimpOptions); this.CampaignFolders = new CampaignFolderLogic(MailChimpOptions); this.Clients = new ClientLogic(MailChimpOptions); this.Content = new ContentLogic(MailChimpOptions); this.Conversations = new ConversationLogic(MailChimpOptions); this.ECommerceStores = new ECommerceLogic(MailChimpOptions); this.Feedback = new FeedBackLogic(MailChimpOptions); this.FileManagerFiles = new FileManagerFileLogic(MailChimpOptions); this.FileManagerFolders = new FileManagerFolderLogic(MailChimpOptions); this.GrowthHistories = new GrowthHistoryLogic(MailChimpOptions); this.InterestCategories = new InterestCategoryLogic(MailChimpOptions); this.Interests = new InterestLogic(MailChimpOptions); this.Lists = new ListLogic(MailChimpOptions); this.ListSegments = new ListSegmentLogic(MailChimpOptions); this.Members = new MemberLogic(MailChimpOptions); this.MergeFields = new MergeFieldLogic(MailChimpOptions); this.Messages = new MessageLogic(MailChimpOptions); this.Notes = new NoteLogic(MailChimpOptions); this.Reports = new ReportLogic(MailChimpOptions); this.Tags = new TagsLogic(MailChimpOptions); this.TemplateFolders = new TemplateFolderLogic(MailChimpOptions); this.Templates = new TemplateLogic(MailChimpOptions); this.WebHooks = new WebHookLogic(MailChimpOptions); this.BatchWebHooks = new BatchWebHookLogic(MailChimpOptions); } #else public MailChimpManager(MailChimpOptions optionsAccessor) : base(optionsAccessor) { // The base implementation already sets the mail chimp options this.Activities = new ActivityLogic(MailChimpOptions); this.AbuseReports = new AbuseReportLogic(MailChimpOptions); this.Api = new ApiLogic(MailChimpOptions); this.Apps = new AuthorizedAppLogic(MailChimpOptions); this.AutomationEmails = new AutomationEmailLogic(MailChimpOptions); this.AutomationEmailQueues = new AutomationEmailQueueLogic(MailChimpOptions); this.Automations = new AutomationLogic(MailChimpOptions); this.AutomationSubscribers = new AutomationSubscriberLogic(MailChimpOptions); this.Batches = new BatchLogic(MailChimpOptions); this.Campaigns = new CampaignLogic(MailChimpOptions); this.CampaignFolders = new CampaignFolderLogic(MailChimpOptions); this.Clients = new ClientLogic(MailChimpOptions); this.Content = new ContentLogic(MailChimpOptions); this.Conversations = new ConversationLogic(MailChimpOptions); this.ECommerceStores = new ECommerceLogic(MailChimpOptions); this.Feedback = new FeedBackLogic(MailChimpOptions); this.FileManagerFiles = new FileManagerFileLogic(MailChimpOptions); this.FileManagerFolders = new FileManagerFolderLogic(MailChimpOptions); this.GrowthHistories = new GrowthHistoryLogic(MailChimpOptions); this.InterestCategories = new InterestCategoryLogic(MailChimpOptions); this.Interests = new InterestLogic(MailChimpOptions); this.Lists = new ListLogic(MailChimpOptions); this.ListSegments = new ListSegmentLogic(MailChimpOptions); this.Members = new MemberLogic(MailChimpOptions); this.MergeFields = new MergeFieldLogic(MailChimpOptions); this.Messages = new MessageLogic(MailChimpOptions); this.Notes = new NoteLogic(MailChimpOptions); this.Reports = new ReportLogic(MailChimpOptions); this.Tags = new TagsLogic(MailChimpOptions); this.TemplateFolders = new TemplateFolderLogic(MailChimpOptions); this.Templates = new TemplateLogic(MailChimpOptions); this.WebHooks = new WebHookLogic(MailChimpOptions); this.BatchWebHooks = new BatchWebHookLogic(MailChimpOptions); } #endif /// <summary> /// Gets the abuse reports. /// </summary> public IAbuseReportLogic AbuseReports { get; } /// <summary> /// Gets the activities. /// </summary> public IActivityLogic Activities { get; } /// <summary> /// Gets the api. /// </summary> public IApiLogic Api { get; } /// <summary> /// Gets the apps. /// </summary> public IAuthorizedAppLogic Apps { get; } /// <summary> /// Gets or sets the automation email queues. /// </summary> public IAutomationEmailQueueLogic AutomationEmailQueues { get; } /// <summary> /// Gets or sets the automation emails. /// </summary> public IAutomationEmailLogic AutomationEmails { get; } /// <summary> /// Gets or sets the automations. /// </summary> public IAutomationLogic Automations { get; } /// <summary> /// Gets or sets the automation subscribers. /// </summary> public IAutomationSubscriberLogic AutomationSubscribers { get; } /// <summary> /// Gets othe batch logic layer to talk to Mail Chimp /// </summary> public IBatchLogic Batches { get; } /// <summary> /// Gets or sets the campaign folders. /// </summary> public ICampaignFolderLogic CampaignFolders { get; } /// <summary> /// Gets the campaigns. /// </summary> public ICampaignLogic Campaigns { get; } /// <summary> /// Gets the clients. /// </summary> public IClientLogic Clients { get; } /// <summary> /// Gets the content. /// </summary> public IContentLogic Content { get; } /// <summary> /// Gets the conversations. /// </summary> public IConversationLogic Conversations { get; } /// <summary> /// Gets or sets the e commerce stores. /// </summary> public IECommerceLogic ECommerceStores { get; } /// <summary> /// Gets the feedback. /// </summary> public IFeedbackLogic Feedback { get; } /// <summary> /// Gets the file manager files. /// </summary> public IFileManagerFileLogic FileManagerFiles { get; } /// <summary> /// Gets the file manager folders. /// </summary> public IFileManagerFolderLogic FileManagerFolders { get; } /// <summary> /// Gets the growth histories. /// </summary> public IGrowthHistoryLogic GrowthHistories { get; } /// <summary> /// Gets the interest categories. /// </summary> public IInterestCategoryLogic InterestCategories { get; } /// <summary> /// Gets or sets the interests. /// </summary> public IInterestLogic Interests { get; } /// <summary> /// Gets the lists. /// </summary> public IListLogic Lists { get; } /// <summary> /// Gets the members. /// </summary> public IMemberLogic Members { get; } /// <summary> /// Gets the merge fields. /// </summary> public IMergeFieldLogic MergeFields { get; } /// <summary> /// Gets or sets the messages. /// </summary> public IMessageLogic Messages { get; } /// <summary> /// Gets or sets the notes. /// </summary> public INoteLogic Notes { get; } /// <summary> /// Gets or sets the reports. /// </summary> public IReportLogic Reports { get; } /// <summary> /// Gets the segments. /// </summary> public IListSegmentLogic ListSegments { get; } /// <summary> /// Gets the tags by list id /// </summary> public ITagsLogic Tags { get; } /// <summary> /// Gets or sets the template folders. /// </summary> public ITemplateFolderLogic TemplateFolders { get; } /// <summary> /// Gets or sets the templates. /// </summary> public ITemplateLogic Templates { get; } /// <summary> /// Gets the logic to access mail chimp web hooks /// </summary> public IWebHookLogic WebHooks { get; } public IBatchWebHookLogic BatchWebHooks { get; } public int Limit { get; private set; } } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // 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.Batch.Protocol { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for ComputeNodeOperations. /// </summary> public static partial class ComputeNodeOperationsExtensions { /// <summary> /// Adds a user account to the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to create a user account. /// </param> /// <param name='user'> /// The user account to be created. /// </param> /// <param name='computeNodeAddUserOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeAddUserHeaders AddUser(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeUser user, ComputeNodeAddUserOptions computeNodeAddUserOptions = default(ComputeNodeAddUserOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).AddUserAsync(poolId, nodeId, user, computeNodeAddUserOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Adds a user account to the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to create a user account. /// </param> /// <param name='user'> /// The user account to be created. /// </param> /// <param name='computeNodeAddUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNodeAddUserHeaders> AddUserAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeUser user, ComputeNodeAddUserOptions computeNodeAddUserOptions = default(ComputeNodeAddUserOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.AddUserWithHttpMessagesAsync(poolId, nodeId, user, computeNodeAddUserOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Deletes a user account from the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to delete a user account. /// </param> /// <param name='userName'> /// The name of the user account to delete. /// </param> /// <param name='computeNodeDeleteUserOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeDeleteUserHeaders DeleteUser(this IComputeNodeOperations operations, string poolId, string nodeId, string userName, ComputeNodeDeleteUserOptions computeNodeDeleteUserOptions = default(ComputeNodeDeleteUserOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).DeleteUserAsync(poolId, nodeId, userName, computeNodeDeleteUserOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a user account from the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to delete a user account. /// </param> /// <param name='userName'> /// The name of the user account to delete. /// </param> /// <param name='computeNodeDeleteUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNodeDeleteUserHeaders> DeleteUserAsync(this IComputeNodeOperations operations, string poolId, string nodeId, string userName, ComputeNodeDeleteUserOptions computeNodeDeleteUserOptions = default(ComputeNodeDeleteUserOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteUserWithHttpMessagesAsync(poolId, nodeId, userName, computeNodeDeleteUserOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Updates the password or expiration time of a user account on the specified /// compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to update a user account. /// </param> /// <param name='userName'> /// The name of the user account to update. /// </param> /// <param name='nodeUpdateUserParameter'> /// The parameters for the request. /// </param> /// <param name='computeNodeUpdateUserOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeUpdateUserHeaders UpdateUser(this IComputeNodeOperations operations, string poolId, string nodeId, string userName, NodeUpdateUserParameter nodeUpdateUserParameter, ComputeNodeUpdateUserOptions computeNodeUpdateUserOptions = default(ComputeNodeUpdateUserOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).UpdateUserAsync(poolId, nodeId, userName, nodeUpdateUserParameter, computeNodeUpdateUserOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the password or expiration time of a user account on the specified /// compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to update a user account. /// </param> /// <param name='userName'> /// The name of the user account to update. /// </param> /// <param name='nodeUpdateUserParameter'> /// The parameters for the request. /// </param> /// <param name='computeNodeUpdateUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNodeUpdateUserHeaders> UpdateUserAsync(this IComputeNodeOperations operations, string poolId, string nodeId, string userName, NodeUpdateUserParameter nodeUpdateUserParameter, ComputeNodeUpdateUserOptions computeNodeUpdateUserOptions = default(ComputeNodeUpdateUserOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateUserWithHttpMessagesAsync(poolId, nodeId, userName, nodeUpdateUserParameter, computeNodeUpdateUserOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets information about the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to get information about. /// </param> /// <param name='computeNodeGetOptions'> /// Additional parameters for the operation /// </param> public static ComputeNode Get(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetOptions computeNodeGetOptions = default(ComputeNodeGetOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).GetAsync(poolId, nodeId, computeNodeGetOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets information about the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to get information about. /// </param> /// <param name='computeNodeGetOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNode> GetAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetOptions computeNodeGetOptions = default(ComputeNodeGetOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(poolId, nodeId, computeNodeGetOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Restarts the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeRebootOption'> /// When to reboot the compute node and what to do with currently running /// tasks. The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeRebootOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeRebootHeaders Reboot(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeRebootOption? nodeRebootOption = default(ComputeNodeRebootOption?), ComputeNodeRebootOptions computeNodeRebootOptions = default(ComputeNodeRebootOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).RebootAsync(poolId, nodeId, nodeRebootOption, computeNodeRebootOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Restarts the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeRebootOption'> /// When to reboot the compute node and what to do with currently running /// tasks. The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeRebootOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNodeRebootHeaders> RebootAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeRebootOption? nodeRebootOption = default(ComputeNodeRebootOption?), ComputeNodeRebootOptions computeNodeRebootOptions = default(ComputeNodeRebootOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RebootWithHttpMessagesAsync(poolId, nodeId, nodeRebootOption, computeNodeRebootOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Reinstalls the operating system on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeReimageOption'> /// When to reimage the compute node and what to do with currently running /// tasks. The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeReimageOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeReimageHeaders Reimage(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeReimageOption? nodeReimageOption = default(ComputeNodeReimageOption?), ComputeNodeReimageOptions computeNodeReimageOptions = default(ComputeNodeReimageOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).ReimageAsync(poolId, nodeId, nodeReimageOption, computeNodeReimageOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Reinstalls the operating system on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeReimageOption'> /// When to reimage the compute node and what to do with currently running /// tasks. The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeReimageOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNodeReimageHeaders> ReimageAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeReimageOption? nodeReimageOption = default(ComputeNodeReimageOption?), ComputeNodeReimageOptions computeNodeReimageOptions = default(ComputeNodeReimageOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ReimageWithHttpMessagesAsync(poolId, nodeId, nodeReimageOption, computeNodeReimageOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Disables task scheduling on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to disable task scheduling. /// </param> /// <param name='nodeDisableSchedulingOption'> /// What to do with currently running tasks when disable task scheduling on /// the compute node. The default value is requeue. Possible values include: /// 'requeue', 'terminate', 'taskcompletion' /// </param> /// <param name='computeNodeDisableSchedulingOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeDisableSchedulingHeaders DisableScheduling(this IComputeNodeOperations operations, string poolId, string nodeId, DisableComputeNodeSchedulingOption? nodeDisableSchedulingOption = default(DisableComputeNodeSchedulingOption?), ComputeNodeDisableSchedulingOptions computeNodeDisableSchedulingOptions = default(ComputeNodeDisableSchedulingOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).DisableSchedulingAsync(poolId, nodeId, nodeDisableSchedulingOption, computeNodeDisableSchedulingOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disables task scheduling on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to disable task scheduling. /// </param> /// <param name='nodeDisableSchedulingOption'> /// What to do with currently running tasks when disable task scheduling on /// the compute node. The default value is requeue. Possible values include: /// 'requeue', 'terminate', 'taskcompletion' /// </param> /// <param name='computeNodeDisableSchedulingOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNodeDisableSchedulingHeaders> DisableSchedulingAsync(this IComputeNodeOperations operations, string poolId, string nodeId, DisableComputeNodeSchedulingOption? nodeDisableSchedulingOption = default(DisableComputeNodeSchedulingOption?), ComputeNodeDisableSchedulingOptions computeNodeDisableSchedulingOptions = default(ComputeNodeDisableSchedulingOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DisableSchedulingWithHttpMessagesAsync(poolId, nodeId, nodeDisableSchedulingOption, computeNodeDisableSchedulingOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Enables task scheduling on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to enable task scheduling. /// </param> /// <param name='computeNodeEnableSchedulingOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeEnableSchedulingHeaders EnableScheduling(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeEnableSchedulingOptions computeNodeEnableSchedulingOptions = default(ComputeNodeEnableSchedulingOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).EnableSchedulingAsync(poolId, nodeId, computeNodeEnableSchedulingOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enables task scheduling on the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to enable task scheduling. /// </param> /// <param name='computeNodeEnableSchedulingOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNodeEnableSchedulingHeaders> EnableSchedulingAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeEnableSchedulingOptions computeNodeEnableSchedulingOptions = default(ComputeNodeEnableSchedulingOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.EnableSchedulingWithHttpMessagesAsync(poolId, nodeId, computeNodeEnableSchedulingOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets the settings required for remote login to a compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which to obtain the remote login settings. /// </param> /// <param name='computeNodeGetRemoteLoginSettingsOptions'> /// Additional parameters for the operation /// </param> public static ComputeNodeGetRemoteLoginSettingsResult GetRemoteLoginSettings(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetRemoteLoginSettingsOptions computeNodeGetRemoteLoginSettingsOptions = default(ComputeNodeGetRemoteLoginSettingsOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).GetRemoteLoginSettingsAsync(poolId, nodeId, computeNodeGetRemoteLoginSettingsOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the settings required for remote login to a compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which to obtain the remote login settings. /// </param> /// <param name='computeNodeGetRemoteLoginSettingsOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ComputeNodeGetRemoteLoginSettingsResult> GetRemoteLoginSettingsAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetRemoteLoginSettingsOptions computeNodeGetRemoteLoginSettingsOptions = default(ComputeNodeGetRemoteLoginSettingsOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRemoteLoginSettingsWithHttpMessagesAsync(poolId, nodeId, computeNodeGetRemoteLoginSettingsOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the Remote Desktop Protocol file for the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which you want to get the Remote Desktop /// Protocol file. /// </param> /// <param name='computeNodeGetRemoteDesktopOptions'> /// Additional parameters for the operation /// </param> public static System.IO.Stream GetRemoteDesktop(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetRemoteDesktopOptions computeNodeGetRemoteDesktopOptions = default(ComputeNodeGetRemoteDesktopOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).GetRemoteDesktopAsync(poolId, nodeId, computeNodeGetRemoteDesktopOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the Remote Desktop Protocol file for the specified compute node. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which you want to get the Remote Desktop /// Protocol file. /// </param> /// <param name='computeNodeGetRemoteDesktopOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.IO.Stream> GetRemoteDesktopAsync(this IComputeNodeOperations operations, string poolId, string nodeId, ComputeNodeGetRemoteDesktopOptions computeNodeGetRemoteDesktopOptions = default(ComputeNodeGetRemoteDesktopOptions), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetRemoteDesktopWithHttpMessagesAsync(poolId, nodeId, computeNodeGetRemoteDesktopOptions, null, cancellationToken).ConfigureAwait(false); _result.Request.Dispose(); return _result.Body; } /// <summary> /// Lists the compute nodes in the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool from which you want to list nodes. /// </param> /// <param name='computeNodeListOptions'> /// Additional parameters for the operation /// </param> public static IPage<ComputeNode> List(this IComputeNodeOperations operations, string poolId, ComputeNodeListOptions computeNodeListOptions = default(ComputeNodeListOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).ListAsync(poolId, computeNodeListOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the compute nodes in the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool from which you want to list nodes. /// </param> /// <param name='computeNodeListOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ComputeNode>> ListAsync(this IComputeNodeOperations operations, string poolId, ComputeNodeListOptions computeNodeListOptions = default(ComputeNodeListOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(poolId, computeNodeListOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the compute nodes in the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='computeNodeListNextOptions'> /// Additional parameters for the operation /// </param> public static IPage<ComputeNode> ListNext(this IComputeNodeOperations operations, string nextPageLink, ComputeNodeListNextOptions computeNodeListNextOptions = default(ComputeNodeListNextOptions)) { return Task.Factory.StartNew(s => ((IComputeNodeOperations)s).ListNextAsync(nextPageLink, computeNodeListNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the compute nodes in the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='computeNodeListNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ComputeNode>> ListNextAsync(this IComputeNodeOperations operations, string nextPageLink, ComputeNodeListNextOptions computeNodeListNextOptions = default(ComputeNodeListNextOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, computeNodeListNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
//============================================================================== // TorqueLab -> // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== //============================================================================== function MaterialEditorTools::guiSync( %this, %material ) { %this.preventUndo = true; //Setup our headers if( MaterialEditorTools.currentMode $= "material" ) { MatEdMaterialMode-->selMaterialName.setText(MaterialEditorTools.currentMaterial.name); MatEdMaterialMode-->selMaterialMapTo.setText(MaterialEditorTools.currentMaterial.mapTo); } else { if( MaterialEditorTools.currentObject.isMethod("getModelFile") ) { %sourcePath = MaterialEditorTools.currentObject.getModelFile(); if( %sourcePath !$= "" ) { MatEdTargetMode-->selMaterialMapTo.ToolTip = %sourcePath; %sourceName = fileName(%sourcePath); MatEdTargetMode-->selMaterialMapTo.setText(%sourceName); MatEdTargetMode-->selMaterialName.setText(MaterialEditorTools.currentMaterial.name); } } else { %info = MaterialEditorTools.currentObject.getClassName(); MatEdTargetMode-->selMaterialMapTo.ToolTip = %info; MatEdTargetMode-->selMaterialMapTo.setText(%info); MatEdTargetMode-->selMaterialName.setText(MaterialEditorTools.currentMaterial.name); } } MaterialEditorPropertiesWindow-->alphaRefTextEdit.setText((%material).alphaRef); MaterialEditorPropertiesWindow-->alphaRefSlider.setValue((%material).alphaRef); MaterialEditorPropertiesWindow-->doubleSidedCheckBox.setValue((%material).doubleSided); MaterialEditorPropertiesWindow-->transZWriteCheckBox.setValue((%material).translucentZWrite); MaterialEditorPropertiesWindow-->alphaTestCheckBox.setValue((%material).alphaTest); MaterialEditorPropertiesWindow-->castShadows.setValue((%material).castShadows); MaterialEditorPropertiesWindow-->castDynamicShadows.setValue((%material).castDynamicShadows);//PBR Scripts MaterialEditorPropertiesWindow-->translucentCheckbox.setValue((%material).translucent); switch$((%material).translucentBlendOp) { case "None": %selectedNum = 0; case "Mul": %selectedNum = 1; case "Add": %selectedNum = 2; case "AddAlpha": %selectedNum = 3; case "Sub": %selectedNum = 4; case "LerpAlpha": %selectedNum = 5; } MaterialEditorPropertiesWindow-->blendingTypePopUp.setSelected(%selectedNum); if((%material).cubemap !$= "") { MaterialEditorPropertiesWindow-->matEd_cubemapEditBtn.setVisible(1); MaterialEditorPropertiesWindow-->reflectionTypePopUp.setSelected(1); } else if((%material).dynamiccubemap) { MaterialEditorPropertiesWindow-->matEd_cubemapEditBtn.setVisible(0); MaterialEditorPropertiesWindow-->reflectionTypePopUp.setSelected(2); } else if((%material).planarReflection) { MaterialEditorPropertiesWindow-->matEd_cubemapEditBtn.setVisible(0); MaterialEditorPropertiesWindow-->reflectionTypePopUp.setSelected(3); } else { MaterialEditorPropertiesWindow-->matEd_cubemapEditBtn.setVisible(0); MaterialEditorPropertiesWindow-->reflectionTypePopUp.setSelected(0); } MaterialEditorPropertiesWindow-->effectColor0Swatch.color = (%material).effectColor[0]; MaterialEditorPropertiesWindow-->effectColor1Swatch.color = (%material).effectColor[1]; MaterialEditorPropertiesWindow-->showFootprintsCheckbox.setValue((%material).showFootprints); MaterialEditorPropertiesWindow-->showDustCheckbox.setValue((%material).showDust); MaterialEditorTools.updateSoundPopup("Footstep", (%material).footstepSoundId, (%material).customFootstepSound); MaterialEditorTools.updateSoundPopup("Impact", (%material).impactSoundId, (%material).customImpactSound); //layer specific controls are located here %layer = MaterialEditorTools.currentLayer; if((%material).diffuseMap[%layer] $= "") { MaterialEditorPropertiesWindow-->diffuseMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->diffuseMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); MaterialEditorPropertiesWindow-->diffuseFileNameText.setText( "" ); } else { MaterialEditorPropertiesWindow-->diffuseMapNameText.setText( (%material).diffuseMap[%layer] ); MaterialEditorPropertiesWindow-->diffuseFileNameText.setText( fileBase((%material).diffuseMap[%layer]) ); MaterialEditorPropertiesWindow-->diffuseMapDisplayBitmap.setBitmap( (%material).diffuseMap[%layer] ); } if((%material).normalMap[%layer] $= "") { MaterialEditorPropertiesWindow-->normalMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->normalMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); MaterialEditorPropertiesWindow-->normalFileNameText.setText( "" ); } else { MaterialEditorPropertiesWindow-->normalMapNameText.setText( (%material).normalMap[%layer] ); MaterialEditorPropertiesWindow-->normalMapDisplayBitmap.setBitmap( (%material).normalMap[%layer] ); MaterialEditorPropertiesWindow-->normalFileNameText.setText( fileBase((%material).normalMap[%layer]) ); } if((%material).overlayMap[%layer] $= "") { MaterialEditorPropertiesWindow-->overlayMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->overlayMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->overlayMapNameText.setText( (%material).overlayMap[%layer] ); MaterialEditorPropertiesWindow-->overlayMapDisplayBitmap.setBitmap( (%material).overlayMap[%layer] ); } if((%material).detailMap[%layer] $= "") { MaterialEditorPropertiesWindow-->detailMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->detailMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->detailMapNameText.setText( (%material).detailMap[%layer] ); MaterialEditorPropertiesWindow-->detailMapDisplayBitmap.setBitmap( (%material).detailMap[%layer] ); } if((%material).detailNormalMap[%layer] $= "") { MaterialEditorPropertiesWindow-->detailNormalMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->detailNormalMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->detailNormalMapNameText.setText( (%material).detailNormalMap[%layer] ); MaterialEditorPropertiesWindow-->detailNormalMapDisplayBitmap.setBitmap( (%material).detailNormalMap[%layer] ); } if((%material).lightMap[%layer] $= "") { MaterialEditorPropertiesWindow-->lightMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->lightMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->lightMapNameText.setText( (%material).lightMap[%layer] ); MaterialEditorPropertiesWindow-->lightMapDisplayBitmap.setBitmap( (%material).lightMap[%layer] ); } if((%material).toneMap[%layer] $= "") { MaterialEditorPropertiesWindow-->toneMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->toneMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->toneMapNameText.setText( (%material).toneMap[%layer] ); MaterialEditorPropertiesWindow-->toneMapDisplayBitmap.setBitmap( (%material).toneMap[%layer] ); } //PBR Scripts MaterialEditorPropertiesWindow-->FlipRBCheckbox.setValue((%material).FlipRB[%layer]); MaterialEditorPropertiesWindow-->invertSmoothnessCheckbox.setValue((%material).invertSmoothness[%layer]); if((%material).specularMap[%layer] $= "") { MaterialEditorPropertiesWindow-->specularMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->specularMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); MaterialEditorPropertiesWindow-->specularFileNameText.setText( "" ); MaterialEditorPropertiesWindow-->compMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->compMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->specularMapNameText.setText( (%material).specularMap[%layer] ); MaterialEditorPropertiesWindow-->specularMapDisplayBitmap.setBitmap( (%material).specularMap[%layer] ); MaterialEditorPropertiesWindow-->specularFileNameText.setText( fileBase((%material).specularMap[%layer]) ); MaterialEditorPropertiesWindow-->compMapNameText.setText( (%material).specularMap[%layer] ); MaterialEditorPropertiesWindow-->compMapDisplayBitmap.setBitmap( (%material).specularMap[%layer] ); } //PBR Script if((%material).roughMap[%layer] $= "") { MaterialEditorPropertiesWindow-->roughMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->roughMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->roughMapNameText.setText( (%material).roughMap[%layer] ); MaterialEditorPropertiesWindow-->roughMapDisplayBitmap.setBitmap( (%material).roughMap[%layer] ); } if((%material).aoMap[%layer] $= "") { MaterialEditorPropertiesWindow-->aoMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->aoMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->aoMapNameText.setText( (%material).aoMap[%layer] ); MaterialEditorPropertiesWindow-->aoMapDisplayBitmap.setBitmap( (%material).aoMap[%layer] ); } if((%material).metalMap[%layer] $= "") { MaterialEditorPropertiesWindow-->metalMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->metalMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->metalMapNameText.setText( (%material).metalMap[%layer] ); MaterialEditorPropertiesWindow-->metalMapDisplayBitmap.setBitmap( (%material).metalMap[%layer] ); } // material damage if((%material).albedoDamageMap[%layer] $= "") { MaterialEditorPropertiesWindow-->albedoDamageMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->albedoDamageMapDisplayBitmap.setBitmap( $MEP_NoTextureImage); } else { MaterialEditorPropertiesWindow-->albedoDamageMapNameText.setText( (%material).albedoDamageMap[%layer] ); MaterialEditorPropertiesWindow-->albedoDamageMapDisplayBitmap.setBitmap( (%material).albedoDamageMap[%layer] ); } if((%material).normalDamageMap[%layer] $= "") { MaterialEditorPropertiesWindow-->normalDamageMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->normalDamageMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->normalDamageMapNameText.setText( (%material).normalDamageMap[%layer] ); MaterialEditorPropertiesWindow-->normalDamageMapDisplayBitmap.setBitmap( (%material).normalDamageMap[%layer] ); } if((%material).compositeDamageMap[%layer] $= "") { MaterialEditorPropertiesWindow-->compositeDamageMapNameText.setText( "None" ); MaterialEditorPropertiesWindow-->compositeDamageMapDisplayBitmap.setBitmap( $MEP_NoTextureImage ); } else { MaterialEditorPropertiesWindow-->compositeDamageMapNameText.setText( (%material).normalDamageMap[%layer] ); MaterialEditorPropertiesWindow-->compositeDamageMapDisplayBitmap.setBitmap( (%material).compositeDamageMap[%layer] ); } MaterialEditorPropertiesWindow-->minDamageTextEdit.setText((%material).minDamage[%layer]); MaterialEditorPropertiesWindow-->minDamageSlider.setValue((%material).minDamage[%layer]); //PBR Script End //MaterialEditorPropertiesWindow-->detailScaleTextEdit.setText( getWord((%material).detailScale[%layer], 0) ); //MaterialEditorPropertiesWindow-->detailNormalStrengthTextEdit.setText( getWord((%material).detailNormalMapStrength[%layer], 0) ); MaterialEditorPropertiesWindow-->colorTintSwatch.color = (%material).diffuseColor[%layer]; MaterialEditorPropertiesWindow-->specularColorSwatch.color = (%material).specular[%layer]; if (!MatEd.PBRenabled) { MaterialEditorPropertiesWindow-->specularPowerTextEdit.setText((%material).specularPower[%layer]); MaterialEditorPropertiesWindow-->specularPowerSlider.setValue((%material).specularPower[%layer]); MaterialEditorPropertiesWindow-->specularStrengthTextEdit.setText((%material).specularStrength[%layer]); MaterialEditorPropertiesWindow-->specularStrengthSlider.setValue((%material).specularStrength[%layer]); MaterialEditorPropertiesWindow-->pixelSpecularCheckbox.setValue((%material).pixelSpecular[%layer]); } else { //PBR Script MaterialEditorPropertiesWindow-->SmoothnessTextEdit.setText((%material).Smoothness[%layer]); MaterialEditorPropertiesWindow-->SmoothnessSlider.setValue((%material).Smoothness[%layer]); MaterialEditorPropertiesWindow-->MetalnessTextEdit.setText((%material).Metalness[%layer]); MaterialEditorPropertiesWindow-->MetalnessSlider.setValue((%material).Metalness[%layer]); //PBR Script End } MaterialEditorPropertiesWindow-->glowCheckbox.setValue((%material).glow[%layer]); MaterialEditorPropertiesWindow-->emissiveCheckbox.setValue((%material).emissive[%layer]); MaterialEditorPropertiesWindow-->parallaxTextEdit.setText((%material).parallaxScale[%layer]); MaterialEditorPropertiesWindow-->parallaxTextEdit.setText((%material).parallaxScale[%layer]); MaterialEditorPropertiesWindow-->parallaxSlider.setValue((%material).parallaxScale[%layer]); MaterialEditorPropertiesWindow-->useAnisoCheckbox.setValue((%material).useAnisotropic[%layer]); MaterialEditorPropertiesWindow-->vertLitCheckbox.setValue((%material).vertLit[%layer]); MaterialEditorPropertiesWindow-->vertColorSwatch.color = (%material).vertColor[%layer]; MaterialEditorPropertiesWindow-->subSurfaceCheckbox.setValue((%material).subSurface[%layer]); MaterialEditorPropertiesWindow-->subSurfaceColorSwatch.color = (%material).subSurfaceColor[%layer]; MaterialEditorPropertiesWindow-->subSurfaceRolloffTextEdit.setText((%material).subSurfaceRolloff[%layer]); MaterialEditorPropertiesWindow-->minnaertTextEdit.setText((%material).minnaertConstant[%layer]); // Animation properties MaterialEditorPropertiesWindow-->RotationAnimation.setValue(0); MaterialEditorPropertiesWindow-->ScrollAnimation.setValue(0); MaterialEditorPropertiesWindow-->WaveAnimation.setValue(0); MaterialEditorPropertiesWindow-->ScaleAnimation.setValue(0); MaterialEditorPropertiesWindow-->SequenceAnimation.setValue(0); %flags = (%material).getAnimFlags(%layer); %wordCount = getWordCount( %flags ); for(%i = 0; %i != %wordCount; %i++) { switch$(getWord( %flags, %i)) { case "$rotate": MaterialEditorPropertiesWindow-->RotationAnimation.setValue(1); case "$scroll": MaterialEditorPropertiesWindow-->ScrollAnimation.setValue(1); case "$wave": MaterialEditorPropertiesWindow-->WaveAnimation.setValue(1); case "$scale": MaterialEditorPropertiesWindow-->ScaleAnimation.setValue(1); case "$sequence": MaterialEditorPropertiesWindow-->SequenceAnimation.setValue(1); } } MaterialEditorPropertiesWindow-->RotationTextEditU.setText( getWord((%material).rotPivotOffset[%layer], 0) ); MaterialEditorPropertiesWindow-->RotationTextEditV.setText( getWord((%material).rotPivotOffset[%layer], 1) ); MaterialEditorPropertiesWindow-->RotationSpeedTextEdit.setText( (%material).rotSpeed[%layer] ); MaterialEditorPropertiesWindow-->RotationSliderU.setValue( getWord((%material).rotPivotOffset[%layer], 0) ); MaterialEditorPropertiesWindow-->RotationSliderV.setValue( getWord((%material).rotPivotOffset[%layer], 1) ); MaterialEditorPropertiesWindow-->RotationSpeedSlider.setValue( (%material).rotSpeed[%layer] ); MaterialEditorPropertiesWindow-->RotationCrosshair.setPosition( 45*mAbs(getWord((%material).rotPivotOffset[%layer], 0))-2, 45*mAbs(getWord((%material).rotPivotOffset[%layer], 1))-2 ); MaterialEditorPropertiesWindow-->ScrollTextEditU.setText( getWord((%material).scrollDir[%layer], 0) ); MaterialEditorPropertiesWindow-->ScrollTextEditV.setText( getWord((%material).scrollDir[%layer], 1) ); MaterialEditorPropertiesWindow-->ScrollSpeedTextEdit.setText( (%material).scrollSpeed[%layer] ); MaterialEditorPropertiesWindow-->ScrollSliderU.setValue( getWord((%material).scrollDir[%layer], 0) ); MaterialEditorPropertiesWindow-->ScrollSliderV.setValue( getWord((%material).scrollDir[%layer], 1) ); MaterialEditorPropertiesWindow-->ScrollSpeedSlider.setValue( (%material).scrollSpeed[%layer] ); MaterialEditorPropertiesWindow-->ScrollCrosshair.setPosition( -(23 * getWord((%material).scrollDir[%layer], 0))+20, -(23 * getWord((%material).scrollDir[%layer], 1))+20); %waveType = (%material).waveType[%layer]; for( %radioButton = 0; %radioButton < MaterialEditorPropertiesWindow-->WaveButtonContainer.getCount(); %radioButton++ ) { if( %waveType $= MaterialEditorPropertiesWindow-->WaveButtonContainer.getObject(%radioButton).waveType ) MaterialEditorPropertiesWindow-->WaveButtonContainer.getObject(%radioButton).setStateOn(1); } MaterialEditorPropertiesWindow-->WaveTextEditAmp.setText( (%material).waveAmp[%layer] ); MaterialEditorPropertiesWindow-->WaveTextEditFreq.setText( (%material).waveFreq[%layer] ); MaterialEditorPropertiesWindow-->WaveSliderAmp.setValue( (%material).waveAmp[%layer] ); MaterialEditorPropertiesWindow-->WaveSliderFreq.setValue( (%material).waveFreq[%layer] ); %numFrames = mRound( 1 / (%material).sequenceSegmentSize[%layer] ); MaterialEditorPropertiesWindow-->SequenceTextEditFPS.setText( (%material).sequenceFramePerSec[%layer] ); MaterialEditorPropertiesWindow-->SequenceTextEditSSS.setText( %numFrames ); MaterialEditorPropertiesWindow-->SequenceSliderFPS.setValue( (%material).sequenceFramePerSec[%layer] ); MaterialEditorPropertiesWindow-->SequenceSliderSSS.setValue( %numFrames ); // Accumulation PBR Script MaterialEditorPropertiesWindow-->accuCheckbox.setValue((%material).accuEnabled[%layer]); MaterialEditorPropertiesWindow-->accuCheckbox.setValue((%material).accuEnabled[%layer]); //TODO: This is wrong, need to check back with PBR branch editor to figure why //%this.getRoughChan((%material).SmoothnessChan[%layer]); //%this.getAOChan((%material).AOChan[%layer]); //%this.getMetalChan((%material).metalChan[%layer]); //ENDTODO //PBR Script End %this.preventUndo = false; } //------------------------------------------------------------------------------ //============================================================================== // Color Picker Helpers - They are all using colorPicker.ed.gui in order to function // These functions are mainly passed callbacks from getColorI/getColorF callbacks function MaterialEditorTools::syncGuiColor(%this, %guiCtrl, %propname, %color) { %layer = MaterialEditorTools.currentLayer; %r = getWord(%color,0); %g = getWord(%color,1); %b = getWord(%color,2); %a = getWord(%color,3); %colorSwatch = (%r SPC %g SPC %b SPC %a); %color = "\"" @ %r SPC %g SPC %b SPC %a @ "\""; %guiCtrl.color = %colorSwatch; MaterialEditorTools.updateActiveMaterial(%propName, %color); } //------------------------------------------------------------------------------
// // Kino/Bloom v2 - Bloom filter for Unity // // Copyright (C) 2015, 2016 Keijiro Takahashi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using UnityEngine; namespace Kino { [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Kino Image Effects/Bloom")] public class Bloom : MonoBehaviour { #region Public Properties /// Prefilter threshold (gamma-encoded) /// Filters out pixels under this level of brightness. public float thresholdGamma { get { return Mathf.Max(_threshold, 0); } set { _threshold = value; } } /// Prefilter threshold (linearly-encoded) /// Filters out pixels under this level of brightness. public float thresholdLinear { get { return GammaToLinear(thresholdGamma); } set { _threshold = LinearToGamma(value); } } [SerializeField] [Tooltip("Filters out pixels under this level of brightness.")] float _threshold = 0.8f; /// Soft-knee coefficient /// Makes transition between under/over-threshold gradual. public float softKnee { get { return _softKnee; } set { _softKnee = value; } } [SerializeField, Range(0, 1)] [Tooltip("Makes transition between under/over-threshold gradual.")] float _softKnee = 0.5f; /// Bloom radius /// Changes extent of veiling effects in a screen /// resolution-independent fashion. public float radius { get { return _radius; } set { _radius = value; } } [SerializeField, Range(1, 7)] [Tooltip("Changes extent of veiling effects\n" + "in a screen resolution-independent fashion.")] float _radius = 2.5f; /// Bloom intensity /// Blend factor of the result image. public float intensity { get { return Mathf.Max(_intensity, 0); } set { _intensity = value; } } [SerializeField] [Tooltip("Blend factor of the result image.")] float _intensity = 0.8f; /// High quality mode /// Controls filter quality and buffer resolution. public bool highQuality { get { return _highQuality; } set { _highQuality = value; } } [SerializeField] [Tooltip("Controls filter quality and buffer resolution.")] bool _highQuality = true; /// Anti-flicker filter /// Reduces flashing noise with an additional filter. [SerializeField] [Tooltip("Reduces flashing noise with an additional filter.")] bool _antiFlicker = true; public bool antiFlicker { get { return _antiFlicker; } set { _antiFlicker = value; } } #endregion #region Private Members [SerializeField, HideInInspector] Shader _shader; Material _material; const int kMaxIterations = 16; RenderTexture[] _blurBuffer1 = new RenderTexture[kMaxIterations]; RenderTexture[] _blurBuffer2 = new RenderTexture[kMaxIterations]; float LinearToGamma(float x) { #if UNITY_5_3_OR_NEWER return Mathf.LinearToGammaSpace(x); #else if (x <= 0.0031308f) return 12.92f * x; else return 1.055f * Mathf.Pow(x, 1 / 2.4f) - 0.055f; #endif } float GammaToLinear(float x) { #if UNITY_5_3_OR_NEWER return Mathf.GammaToLinearSpace(x); #else if (x <= 0.04045f) return x / 12.92f; else return Mathf.Pow((x + 0.055f) / 1.055f, 2.4f); #endif } #endregion #region MonoBehaviour Functions void OnEnable() { var shader = _shader ? _shader : Shader.Find("Hidden/Kino/Bloom"); _material = new Material(shader); _material.hideFlags = HideFlags.DontSave; } void OnDisable() { DestroyImmediate(_material); } void OnRenderImage(RenderTexture source, RenderTexture destination) { var useRGBM = Application.isMobilePlatform; // source texture size var tw = source.width; var th = source.height; // halve the texture size for the low quality mode if (!_highQuality) { tw /= 2; th /= 2; } // blur buffer format var rtFormat = useRGBM ? RenderTextureFormat.Default : RenderTextureFormat.DefaultHDR; // determine the iteration count var logh = Mathf.Log(th, 2) + _radius - 8; var logh_i = (int)logh; var iterations = Mathf.Clamp(logh_i, 1, kMaxIterations); // update the shader properties var lthresh = thresholdLinear; _material.SetFloat("_Threshold", lthresh); var knee = lthresh * _softKnee + 1e-5f; var curve = new Vector3(lthresh - knee, knee * 2, 0.25f / knee); _material.SetVector("_Curve", curve); var pfo = !_highQuality && _antiFlicker; _material.SetFloat("_PrefilterOffs", pfo ? -0.5f : 0.0f); _material.SetFloat("_SampleScale", 0.5f + logh - logh_i); _material.SetFloat("_Intensity", intensity); // prefilter pass var prefiltered = RenderTexture.GetTemporary(tw, th, 0, rtFormat); var pass = _antiFlicker ? 1 : 0; Graphics.Blit(source, prefiltered, _material, pass); // construct a mip pyramid var last = prefiltered; for (var level = 0; level < iterations; level++) { _blurBuffer1[level] = RenderTexture.GetTemporary( last.width / 2, last.height / 2, 0, rtFormat ); pass = (level == 0) ? (_antiFlicker ? 3 : 2) : 4; Graphics.Blit(last, _blurBuffer1[level], _material, pass); last = _blurBuffer1[level]; } // upsample and combine loop for (var level = iterations - 2; level >= 0; level--) { var basetex = _blurBuffer1[level]; _material.SetTexture("_BaseTex", basetex); _blurBuffer2[level] = RenderTexture.GetTemporary( basetex.width, basetex.height, 0, rtFormat ); pass = _highQuality ? 6 : 5; Graphics.Blit(last, _blurBuffer2[level], _material, pass); last = _blurBuffer2[level]; } // finish process _material.SetTexture("_BaseTex", source); pass = _highQuality ? 8 : 7; Graphics.Blit(last, destination, _material, pass); // release the temporary buffers for (var i = 0; i < kMaxIterations; i++) { if (_blurBuffer1[i] != null) RenderTexture.ReleaseTemporary(_blurBuffer1[i]); if (_blurBuffer2[i] != null) RenderTexture.ReleaseTemporary(_blurBuffer2[i]); _blurBuffer1[i] = null; _blurBuffer2[i] = null; } RenderTexture.ReleaseTemporary(prefiltered); } #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 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Inheritance operations. /// </summary> public partial class Inheritance : IServiceOperations<AutoRestComplexTestService>, IInheritance { /// <summary> /// Initializes a new instance of the Inheritance class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Inheritance(AutoRestComplexTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types that extend others /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Siamese>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/inheritance/valid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Siamese>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Siamese>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put complex types that extend others /// </summary> /// <param name='complexBody'> /// Please put a siamese with id=2, name="Siameee", color=green, /// breed=persion, which hates 2 dogs, the 1st one named "Potato" with id=1 /// and food="tomato", and the 2nd one named "Tomato" with id=-1 and /// food="french fries". /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Siamese complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/inheritance/valid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt #nullable enable using System; using NUnit.Framework.Constraints; using NUnit.Framework.Internal; namespace NUnit.Framework { public partial class Assert { #region ThrowsAsync /// <summary> /// Verifies that an async delegate throws a particular exception when called. The returned exception may be /// <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="expression">A constraint to be satisfied by the exception</param> /// <param name="code">A TestSnippet delegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception? ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code, string? message, params object?[]? args) { Exception? caughtException = null; try { AsyncToSyncAdapter.Await(code.Invoke); } catch (Exception e) { caughtException = e; } Assert.That(caughtException, expression, message, args); return caughtException; } /// <summary> /// Verifies that an async delegate throws a particular exception when called. The returned exception may be /// <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="expression">A constraint to be satisfied by the exception</param> /// <param name="code">A TestSnippet delegate</param> public static Exception? ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code) { return ThrowsAsync(expression, code, string.Empty, null); } /// <summary> /// Verifies that an async delegate throws a particular exception when called. The returned exception may be /// <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="expectedExceptionType">The exception Type expected</param> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception? ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code, string? message, params object?[]? args) { return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, message, args); } /// <summary> /// Verifies that an async delegate throws a particular exception when called. The returned exception may be /// <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="expectedExceptionType">The exception Type expected</param> /// <param name="code">A TestDelegate</param> public static Exception? ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code) { return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null); } #endregion #region ThrowsAsync<TActual> /// <summary> /// Verifies that an async delegate throws a particular exception when called. The returned exception may be /// <see langword="null"/> when inside a multiple assert block. /// </summary> /// <typeparam name="TActual">Type of the expected exception</typeparam> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static TActual? ThrowsAsync<TActual>(AsyncTestDelegate code, string? message, params object?[]? args) where TActual : Exception { return (TActual?)ThrowsAsync(typeof (TActual), code, message, args); } /// <summary> /// Verifies that an async delegate throws a particular exception when called. The returned exception may be /// <see langword="null"/> when inside a multiple assert block. /// </summary> /// <typeparam name="TActual">Type of the expected exception</typeparam> /// <param name="code">A TestDelegate</param> public static TActual? ThrowsAsync<TActual>(AsyncTestDelegate code) where TActual : Exception { return ThrowsAsync<TActual>(code, string.Empty, null); } #endregion #region CatchAsync /// <summary> /// Verifies that an async delegate throws an exception when called and returns it. The returned exception may /// be <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception? CatchAsync(AsyncTestDelegate code, string? message, params object?[]? args) { return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args); } /// <summary> /// Verifies that an async delegate throws an exception when called and returns it. The returned exception may /// be <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="code">A TestDelegate</param> public static Exception? CatchAsync(AsyncTestDelegate code) { return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code); } /// <summary> /// Verifies that an async delegate throws an exception of a certain Type or one derived from it when called and /// returns it. The returned exception may be <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="expectedExceptionType">The expected Exception Type</param> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception? CatchAsync(Type expectedExceptionType, AsyncTestDelegate code, string? message, params object?[]? args) { return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args); } /// <summary> /// Verifies that an async delegate throws an exception of a certain Type or one derived from it when called and /// returns it. The returned exception may be <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="expectedExceptionType">The expected Exception Type</param> /// <param name="code">A TestDelegate</param> public static Exception? CatchAsync(Type expectedExceptionType, AsyncTestDelegate code) { return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code); } #endregion #region CatchAsync<TActual> /// <summary> /// Verifies that an async delegate throws an exception of a certain Type or one derived from it when called and /// returns it. The returned exception may be <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static TActual? CatchAsync<TActual>(AsyncTestDelegate code, string? message, params object?[]? args) where TActual : Exception { return (TActual?)ThrowsAsync(new InstanceOfTypeConstraint(typeof (TActual)), code, message, args); } /// <summary> /// Verifies that an async delegate throws an exception of a certain Type or one derived from it when called and /// returns it. The returned exception may be <see langword="null"/> when inside a multiple assert block. /// </summary> /// <param name="code">A TestDelegate</param> public static TActual? CatchAsync<TActual>(AsyncTestDelegate code) where TActual : Exception { return (TActual?)ThrowsAsync(new InstanceOfTypeConstraint(typeof (TActual)), code); } #endregion #region DoesNotThrowAsync /// <summary> /// Verifies that an async delegate does not throw an exception /// </summary> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void DoesNotThrowAsync(AsyncTestDelegate code, string? message, params object?[]? args) { Assert.That(code, new ThrowsNothingConstraint(), message, args); } /// <summary> /// Verifies that an async delegate does not throw an exception. /// </summary> /// <param name="code">A TestDelegate</param> public static void DoesNotThrowAsync(AsyncTestDelegate code) { DoesNotThrowAsync(code, string.Empty, null); } #endregion } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // 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 log4net.ObjectRenderer; using log4net.Core; using log4net.Util; using log4net.Plugin; namespace log4net.Repository { /// <summary> /// Base implementation of <see cref="ILoggerRepository"/> /// </summary> /// <remarks> /// <para> /// Default abstract implementation of the <see cref="ILoggerRepository"/> interface. /// </para> /// <para> /// Skeleton implementation of the <see cref="ILoggerRepository"/> interface. /// All <see cref="ILoggerRepository"/> types can extend this type. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public abstract class LoggerRepositorySkeleton : ILoggerRepository { #region Member Variables private string m_name; private RendererMap m_rendererMap; private PluginMap m_pluginMap; private LevelMap m_levelMap; private Level m_threshold; private bool m_configured; private event LoggerRepositoryShutdownEventHandler m_shutdownEvent; private event LoggerRepositoryConfigurationResetEventHandler m_configurationResetEvent; private event LoggerRepositoryConfigurationChangedEventHandler m_configurationChangedEvent; private PropertiesDictionary m_properties; #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> /// <remarks> /// <para> /// Initializes the repository with default (empty) properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton() : this(new PropertiesDictionary()) { } /// <summary> /// Construct the repository using specific properties /// </summary> /// <param name="properties">the properties to set for this repository</param> /// <remarks> /// <para> /// Initializes the repository with specified properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton(PropertiesDictionary properties) { m_properties = properties; m_rendererMap = new RendererMap(); m_pluginMap = new PluginMap(this); m_levelMap = new LevelMap(); m_configured = false; AddBuiltinLevels(); // Don't disable any levels by default. m_threshold = Level.All; } #endregion #region Implementation of ILoggerRepository /// <summary> /// The name of the repository /// </summary> /// <value> /// The string name of the repository /// </value> /// <remarks> /// <para> /// The name of this repository. The name is /// used to store and lookup the repositories /// stored by the <see cref="IRepositorySelector"/>. /// </para> /// </remarks> virtual public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// The threshold for all events in this repository /// </summary> /// <value> /// The threshold for all events in this repository /// </value> /// <remarks> /// <para> /// The threshold for all events in this repository /// </para> /// </remarks> virtual public Level Threshold { get { return m_threshold; } set { if (value != null) { m_threshold = value; } else { // Must not set threshold to null LogLog.Warn("LoggerRepositorySkeleton: Threshold cannot be set to null. Setting to ALL"); m_threshold = Level.All; } } } /// <summary> /// RendererMap accesses the object renderer map for this repository. /// </summary> /// <value> /// RendererMap accesses the object renderer map for this repository. /// </value> /// <remarks> /// <para> /// RendererMap accesses the object renderer map for this repository. /// </para> /// <para> /// The RendererMap holds a mapping between types and /// <see cref="IObjectRenderer"/> objects. /// </para> /// </remarks> virtual public RendererMap RendererMap { get { return m_rendererMap; } } /// <summary> /// The plugin map for this repository. /// </summary> /// <value> /// The plugin map for this repository. /// </value> /// <remarks> /// <para> /// The plugin map holds the <see cref="IPlugin"/> instances /// that have been attached to this repository. /// </para> /// </remarks> virtual public PluginMap PluginMap { get { return m_pluginMap; } } /// <summary> /// Get the level map for the Repository. /// </summary> /// <remarks> /// <para> /// Get the level map for the Repository. /// </para> /// <para> /// The level map defines the mappings between /// level names and <see cref="Level"/> objects in /// this repository. /// </para> /// </remarks> virtual public LevelMap LevelMap { get { return m_levelMap; } } /// <summary> /// Test if logger exists /// </summary> /// <param name="name">The name of the logger to lookup</param> /// <returns>The Logger object with the name specified</returns> /// <remarks> /// <para> /// Check if the named logger exists in the repository. If so return /// its reference, otherwise returns <c>null</c>. /// </para> /// </remarks> abstract public ILogger Exists(string name); /// <summary> /// Returns all the currently defined loggers in the repository /// </summary> /// <returns>All the defined loggers</returns> /// <remarks> /// <para> /// Returns all the currently defined loggers in the repository as an Array. /// </para> /// </remarks> abstract public ILogger[] GetCurrentLoggers(); /// <summary> /// Return a new logger instance /// </summary> /// <param name="name">The name of the logger to retrieve</param> /// <returns>The logger object with the name specified</returns> /// <remarks> /// <para> /// Return a new logger instance. /// </para> /// <para> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated and /// then linked with its existing ancestors as well as children. /// </para> /// </remarks> abstract public ILogger GetLogger(string name); /// <summary> /// Shutdown the repository /// </summary> /// <remarks> /// <para> /// Shutdown the repository. Can be overridden in a subclass. /// This base class implementation notifies the <see cref="ShutdownEvent"/> /// listeners and all attached plugins of the shutdown event. /// </para> /// </remarks> virtual public void Shutdown() { // Shutdown attached plugins foreach(IPlugin plugin in PluginMap.AllPlugins) { plugin.Shutdown(); } // Notify listeners OnShutdown(null); } /// <summary> /// Reset the repositories configuration to a default state /// </summary> /// <remarks> /// <para> /// Reset all values contained in this instance to their /// default state. /// </para> /// <para> /// Existing loggers are not removed. They are just reset. /// </para> /// <para> /// This method should be used sparingly and with care as it will /// block all logging until it is completed. /// </para> /// </remarks> virtual public void ResetConfiguration() { // Clear internal data structures m_rendererMap.Clear(); m_levelMap.Clear(); // Add the predefined levels to the map AddBuiltinLevels(); Configured = false; // Notify listeners OnConfigurationReset(null); } /// <summary> /// Log the logEvent through this repository. /// </summary> /// <param name="logEvent">the event to log</param> /// <remarks> /// <para> /// This method should not normally be used to log. /// The <see cref="ILog"/> interface should be used /// for routine logging. This interface can be obtained /// using the <see cref="log4net.LogManager.GetLogger(string)"/> method. /// </para> /// <para> /// The <c>logEvent</c> is delivered to the appropriate logger and /// that logger is then responsible for logging the event. /// </para> /// </remarks> abstract public void Log(LoggingEvent logEvent); /// <summary> /// Flag indicates if this repository has been configured. /// </summary> /// <value> /// Flag indicates if this repository has been configured. /// </value> /// <remarks> /// <para> /// Flag indicates if this repository has been configured. /// </para> /// </remarks> virtual public bool Configured { get { return m_configured; } set { m_configured = value; } } /// <summary> /// Event to notify that the repository has been shutdown. /// </summary> /// <value> /// Event to notify that the repository has been shutdown. /// </value> /// <remarks> /// <para> /// Event raised when the repository has been shutdown. /// </para> /// </remarks> public event LoggerRepositoryShutdownEventHandler ShutdownEvent { add { m_shutdownEvent += value; } remove { m_shutdownEvent -= value; } } /// <summary> /// Event to notify that the repository has had its configuration reset. /// </summary> /// <value> /// Event to notify that the repository has had its configuration reset. /// </value> /// <remarks> /// <para> /// Event raised when the repository's configuration has been /// reset to default. /// </para> /// </remarks> public event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset { add { m_configurationResetEvent += value; } remove { m_configurationResetEvent -= value; } } /// <summary> /// Event to notify that the repository has had its configuration changed. /// </summary> /// <value> /// Event to notify that the repository has had its configuration changed. /// </value> /// <remarks> /// <para> /// Event raised when the repository's configuration has been changed. /// </para> /// </remarks> public event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged { add { m_configurationChangedEvent += value; } remove { m_configurationChangedEvent -= value; } } /// <summary> /// Repository specific properties /// </summary> /// <value> /// Repository specific properties /// </value> /// <remarks> /// These properties can be specified on a repository specific basis /// </remarks> public PropertiesDictionary Properties { get { return m_properties; } } /// <summary> /// Returns all the Appenders that are configured as an Array. /// </summary> /// <returns>All the Appenders</returns> /// <remarks> /// <para> /// Returns all the Appenders that are configured as an Array. /// </para> /// </remarks> abstract public log4net.Appender.IAppender[] GetAppenders(); #endregion private void AddBuiltinLevels() { // Add the predefined levels to the map m_levelMap.Add(Level.Off); // Unrecoverable errors m_levelMap.Add(Level.Emergency); m_levelMap.Add(Level.Fatal); m_levelMap.Add(Level.Alert); // Recoverable errors m_levelMap.Add(Level.Critical); m_levelMap.Add(Level.Severe); m_levelMap.Add(Level.Error); m_levelMap.Add(Level.Warn); // Information m_levelMap.Add(Level.Notice); m_levelMap.Add(Level.Info); // Debug m_levelMap.Add(Level.Debug); m_levelMap.Add(Level.Fine); m_levelMap.Add(Level.Trace); m_levelMap.Add(Level.Finer); m_levelMap.Add(Level.Verbose); m_levelMap.Add(Level.Finest); m_levelMap.Add(Level.All); } /// <summary> /// Adds an object renderer for a specific class. /// </summary> /// <param name="typeToRender">The type that will be rendered by the renderer supplied.</param> /// <param name="rendererInstance">The object renderer used to render the object.</param> /// <remarks> /// <para> /// Adds an object renderer for a specific class. /// </para> /// </remarks> virtual public void AddRenderer(Type typeToRender, IObjectRenderer rendererInstance) { if (typeToRender == null) { throw new ArgumentNullException("typeToRender"); } if (rendererInstance == null) { throw new ArgumentNullException("rendererInstance"); } m_rendererMap.Put(typeToRender, rendererInstance); } /// <summary> /// Notify the registered listeners that the repository is shutting down /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository is shutting down. /// </para> /// </remarks> protected virtual void OnShutdown(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryShutdownEventHandler handler = m_shutdownEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Notify the registered listeners that the repository has had its configuration reset /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository's configuration has been reset. /// </para> /// </remarks> protected virtual void OnConfigurationReset(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryConfigurationResetEventHandler handler = m_configurationResetEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Notify the registered listeners that the repository has had its configuration changed /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository's configuration has changed. /// </para> /// </remarks> protected virtual void OnConfigurationChanged(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryConfigurationChangedEventHandler handler = m_configurationChangedEvent; if (handler != null) { handler(this, EventArgs.Empty); } } /// <summary> /// Raise a configuration changed event on this repository /// </summary> /// <param name="e">EventArgs.Empty</param> /// <remarks> /// <para> /// Applications that programmatically change the configuration of the repository should /// raise this event notification to notify listeners. /// </para> /// </remarks> public void RaiseConfigurationChanged(EventArgs e) { OnConfigurationChanged(e); } } }
using System; using System.Collections.Generic; using System.Linq; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Instructions; using FrbTicTacToe.Entities; using FrbTicTacToe.Unmanaged_Code; using Microsoft.Xna.Framework.Media; using GuiManager = FlatRedBall.Gui.GuiManager; #if FRB_XNA || SILVERLIGHT using Keys = Microsoft.Xna.Framework.Input.Keys; #endif namespace FrbTicTacToe.Screens { public partial class GameScreen { public List<TicTacToeLine> TicTacToeLines = new List<TicTacToeLine> { // Verticles new TicTacToeLine(new GridSpace(0, 0), new GridSpace(0, 1), new GridSpace(0, 2)), new TicTacToeLine(new GridSpace(1, 0), new GridSpace(1, 1), new GridSpace(1, 2)), new TicTacToeLine(new GridSpace(2, 0), new GridSpace(2, 1), new GridSpace(2, 2)), // Horizontals new TicTacToeLine(new GridSpace(0, 0), new GridSpace(1, 0), new GridSpace(2, 0)), new TicTacToeLine(new GridSpace(0, 1), new GridSpace(1, 1), new GridSpace(2, 1)), new TicTacToeLine(new GridSpace(0, 2), new GridSpace(1, 2), new GridSpace(2, 2)), // Diagonals new TicTacToeLine(new GridSpace(0, 0), new GridSpace(1, 1), new GridSpace(2, 2)), new TicTacToeLine(new GridSpace(0, 2), new GridSpace(1, 1), new GridSpace(2, 0)) }; readonly BoardTile[,] _tiles = new BoardTile[3,3]; private bool _aiCallPlaced = false; void CustomInitialize() { // Initialize the grid array _tiles[0, 0] = BoardTile11; _tiles[0, 1] = BoardTile12; _tiles[0, 2] = BoardTile13; _tiles[1, 0] = BoardTile21; _tiles[1, 1] = BoardTile22; _tiles[1, 2] = BoardTile23; _tiles[2, 0] = BoardTile31; _tiles[2, 1] = BoardTile32; _tiles[2, 2] = BoardTile33; for (var i = 0; i < 3;i++) { for(var j=0;j<3;j++) { _tiles[i,j].CurrentState = BoardTile.VariableState.None; _tiles[i, j].Click += TileClick; } } // offset the camera Camera.Main.X = Camera.Main.OrthogonalWidth / 2.0f; Camera.Main.Y = Camera.Main.OrthogonalHeight/2.0f; Player1WinCount.Text = string.Format("{0} Wins", Globals.PlayerXWins); Player2WinCount.Text = string.Format("{0} Wins", Globals.PlayerOWins); Player1TypeLabel.CurrentPlayerTypeState = Globals.PlayerXType == PlayerType.Human ? Icon.PlayerType.Human : Icon.PlayerType.Computer; Player1TypeLabel.Size = 30; Player2TypeLabel.CurrentPlayerTypeState = Globals.PlayerOType == PlayerType.Human ? Icon.PlayerType.Human : Icon.PlayerType.Computer; Player2TypeLabel.Size = 30; VictoryPopupWindow.YesClicked += VictoryPopupWindowYesButtonClick; VictoryPopupWindow.NoClicked += VictoryPopupWindowNoButtonClick; VictoryPopupWindow.Visible = false; PlayerXAiLevelText.Visible = Globals.PlayerXType == PlayerType.Computer; switch (Globals.PlayerXAiLevel) { case AiLevel.Easy: PlayerXAiLevelText.Text = "Easy"; break; case AiLevel.Hard: PlayerXAiLevelText.Text = "Hard"; break; case AiLevel.NormalDefensive: PlayerXAiLevelText.Text = "Defensive"; break; case AiLevel.NormalOffensive: PlayerXAiLevelText.Text = "Offensive"; break; } PlayerOAiLevelText.Visible = Globals.PlayerOType == PlayerType.Computer; switch (Globals.PlayerOAiLevel) { case AiLevel.Easy: PlayerOAiLevelText.Text = "Easy"; break; case AiLevel.Hard: PlayerOAiLevelText.Text = "Hard"; break; case AiLevel.NormalDefensive: PlayerOAiLevelText.Text = "Defensive"; break; case AiLevel.NormalOffensive: PlayerOAiLevelText.Text = "Offensive"; break; } } void CustomActivity(bool firstTimeCalled) { if(FlatRedBall.Audio.AudioManager.CurrentlyPlayingSong == GlobalContent.MenuMusic) FlatRedBall.Audio.AudioManager.StopSong(); if (Microsoft.Xna.Framework.Media.MediaPlayer.State == MediaState.Stopped) StartMusic(); var currentPlayer = CurrentPlayerIndicatorState; GuiManager.SortZAndLayerBased(); if(firstTimeCalled) { CurrentPlayerIndicatorState = FlatRedBallServices.Random.Next(100) > 50 ? PlayerIndicator.PlayerXMove : PlayerIndicator.PlayerOMove; } Player1WinCount.Text = string.Format("Wins {0}", Globals.PlayerXWins); Player2WinCount.Text = string.Format("{0} Wins", Globals.PlayerOWins); // Don't want to do the rest if the pop up is visible if (VictoryPopupWindow.Visible) { if(_aiCallPlaced) { this.Instructions.Clear(); _aiCallPlaced = false; } return; } CurrentPlayerIndicator.CurrentState = CurrentPlayerIndicatorState == PlayerIndicator.PlayerXMove ? BoardTile.VariableState.X : BoardTile.VariableState.O; if(InputManager.Keyboard.KeyTyped(Keys.Escape)) { InputManager.Keyboard.IgnoreKeyForOneFrame(Keys.Escape); MoveToScreen(typeof (Screens.TitleMenu)); } CheckForWins(); if(_aiCallPlaced) return; if ((currentPlayer == PlayerIndicator.PlayerXMove && Globals.PlayerXType == PlayerType.Computer) || (currentPlayer == PlayerIndicator.PlayerOMove && Globals.PlayerOType == PlayerType.Computer)) { _aiCallPlaced = true; var pause = Math.Min(Math.Max(1, FlatRedBallServices.Random.NextDouble() * 2), 2); this.Call(DoComputerMove).After(pause); } } void CustomDestroy() { } static void CustomLoadStaticContent(string contentManagerName) { } #region Events void VictoryPopupWindowNoButtonClick() { GlobalContent.ClickWave.Play(); MoveToScreen(typeof(Screens.TitleMenu)); } void VictoryPopupWindowYesButtonClick() { GlobalContent.ClickWave.Play(); VictoryPopupWindow.Visible = false; ResetBoard(); } void TileClick(FlatRedBall.Gui.IWindow window) { if(VictoryPopupWindow.Visible) return; // If the current player is a computer, get out if(CurrentPlayerIndicatorState == PlayerIndicator.PlayerXMove && Globals.PlayerXType == PlayerType.Computer) return; if(CurrentPlayerIndicatorState == PlayerIndicator.PlayerOMove && Globals.PlayerOType == PlayerType.Computer) return; // if the tile is already set, get out var tile = (BoardTile) window; if(tile.CurrentState != BoardTile.VariableState.None) return; switch (CurrentPlayerIndicatorState) { case PlayerIndicator.PlayerOMove: GlobalContent.ScrapeWave.Play(); tile.CurrentState = BoardTile.VariableState.O; CurrentPlayerIndicatorState = PlayerIndicator.PlayerXMove; break; case PlayerIndicator.PlayerXMove: GlobalContent.ScrapeWave.Play(); tile.CurrentState = BoardTile.VariableState.X; CurrentPlayerIndicatorState = PlayerIndicator.PlayerOMove; break; } } #endregion #region Utils private int SpacesLeft() { var ct = 0; for(var i=0;i<3;i++) { for(var j=0;j<3;j++) { if (_tiles[i, j].CurrentState == BoardTile.VariableState.None) ct++; } } return ct; } private List<GridSpace> GetAvailableSpaces() { var toReturn = new List<GridSpace>(); for(var i=0;i<3;i++) { for(var j=0;j<3;j++) { if(_tiles[i,j].CurrentState == BoardTile.VariableState.None) toReturn.Add(new GridSpace(i,j)); } } return toReturn; } private void CheckForWins() { BoardTile.VariableState winner = BoardTile.VariableState.None; foreach (var ticTacToeLine in TicTacToeLines) { if (IsVictoryLine(ticTacToeLine)) winner = _tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState; } if(winner != BoardTile.VariableState.None) { if(Globals.PlayerXType == PlayerType.Computer && Globals.PlayerOType == PlayerType.Computer) { CurrentPlayerIndicatorState = PlayerIndicator.Unknown; if (winner == BoardTile.VariableState.X) Globals.PlayerXWins++; else Globals.PlayerOWins++; ResetBoard(); } else { VictoryPopupWindow.Winner = string.Format("Player {0} Wins!", winner == BoardTile.VariableState.X ? "X" : "O"); VictoryPopupWindow.Visible = true; GlobalContent.TaDa.Play(); CurrentPlayerIndicatorState = PlayerIndicator.Unknown; if (winner == BoardTile.VariableState.X) Globals.PlayerXWins++; else Globals.PlayerOWins++; return; } } if(SpacesLeft() == 0) { if(Globals.PlayerXType == PlayerType.Computer && Globals.PlayerOType == PlayerType.Computer) { CurrentPlayerIndicatorState = PlayerIndicator.Unknown; ResetBoard(); } else { VictoryPopupWindow.Winner = "It was a tie!"; VictoryPopupWindow.Visible = true; GlobalContent.Sad.Play(); CurrentPlayerIndicatorState = PlayerIndicator.Unknown; } } } private bool IsVictoryLine(TicTacToeLine line) { if (line.Cells.Any(cell => _tiles[cell.X, cell.Y].CurrentState == BoardTile.VariableState.None)) { return false; } return _tiles[line.Cells[0].X, line.Cells[0].Y].CurrentState == _tiles[line.Cells[1].X, line.Cells[1].Y].CurrentState && _tiles[line.Cells[1].X, line.Cells[1].Y].CurrentState == _tiles[line.Cells[2].X, line.Cells[2].Y].CurrentState; } private void ResetBoard() { // Reset the tiles for(var i=0;i<3;i++) { for(var j=0;j<3;j++) { _tiles[i,j].CurrentState = BoardTile.VariableState.None; } } // Set who goes first CurrentPlayerIndicatorState = FlatRedBallServices.Random.Next(100) > 50 ? PlayerIndicator.PlayerXMove : PlayerIndicator.PlayerOMove; // Change the background BackgroundImage.ChangeBackground(); } private int _lastPlayed = -1; private void StartMusic() { var lst = new List<int>(); for(var i=1;i<6;i++) { if (i != _lastPlayed) lst.Add(i); } var index = FlatRedBallServices.Random.Next(lst.Count); var toPlay = lst[index]; _lastPlayed = toPlay; switch (toPlay) { case 1: FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.GameMusic1, true, true); break; case 2: FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.GameMusic2, true, true); break; case 3: FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.GameMusic3, true, true); break; case 4: FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.GameMusic4, true, true); break; case 5: FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.GameMusic5, true, true); break; default: _lastPlayed = 1; FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.GameMusic1, true, true); break; } } #endregion #region AI private int[,] _availableMoves = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; private void PerformComputerMove(int x, int y) { var playingX = CurrentPlayerIndicatorState == PlayerIndicator.PlayerXMove; _tiles[x, y].CurrentState = playingX ? BoardTile.VariableState.X : BoardTile.VariableState.O; GlobalContent.ScrapeWave.Play(); CurrentPlayerIndicatorState = CurrentPlayerIndicatorState == PlayerIndicator.PlayerOMove ? PlayerIndicator.PlayerXMove : PlayerIndicator.PlayerOMove; _aiCallPlaced = false; } private void DoComputerMove() { var playingX = CurrentPlayerIndicatorState == PlayerIndicator.PlayerXMove; var aiLevel = playingX ? Globals.PlayerXAiLevel : Globals.PlayerOAiLevel; switch (aiLevel) { case AiLevel.Easy: DoEasyComputerMove(); break; case AiLevel.NormalOffensive: DoNormalOffensiveComputerMove(); break; case AiLevel.NormalDefensive: DoNormalDefensiveComputerMove(); break; case AiLevel.Hard: DoHardComputerMove(); break; default: DoEasyComputerMove(); break; } } private void DoEasyComputerMove() { var availableGrid = GetAvailableSpaces(); if(availableGrid.Count == 0) return; var index = FlatRedBallServices.Random.Next(availableGrid.Count); PerformComputerMove(availableGrid[index].X, availableGrid[index].Y); } private void DoNormalOffensiveComputerMove() { _availableMoves = new int[,] {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; for(var i=0;i<3;i++) { for(var j=0;j<3;j++) { if(_tiles[i,j].CurrentState == BoardTile.VariableState.None) { CalculateCompletions(i, j); CalculatePairs(i, j); } } } CalculateSingles(); var available = GetHighestMoves(); if(available.Count == 1) { PerformComputerMove(available[0].X, available[0].Y); } else { var index = FlatRedBallServices.Random.Next(available.Count); PerformComputerMove(available[index].X, available[index].Y); } } private void DoNormalDefensiveComputerMove() { _availableMoves = new int[,] { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }; for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { if (_tiles[i, j].CurrentState == BoardTile.VariableState.None) { CalculateBlocks(i, j); CalculatePairs(i, j); } } } CalculateSingles(); var available = GetHighestMoves(); if (available.Count == 1) { PerformComputerMove(available[0].X, available[0].Y); } else { var index = FlatRedBallServices.Random.Next(available.Count); PerformComputerMove(available[index].X, available[index].Y); } } private void DoHardComputerMove() { _availableMoves = new int[,] { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }; for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { // Don't want to do any calculations on cells that are already used if (_tiles[i, j].CurrentState == BoardTile.VariableState.None) { CalculateCompletions(i, j); CalculateBlocks(i, j); CalculatePairs(i, j); } } } CalculateSingles(); var available = GetHighestMoves(); if (available.Count == 1) { PerformComputerMove(available[0].X, available[0].Y); } else { var index = FlatRedBallServices.Random.Next(available.Count); PerformComputerMove(available[index].X, available[index].Y); } } private void CalculateBlocks(int x, int y) { var playingX = CurrentPlayerIndicatorState == PlayerIndicator.PlayerXMove; var searchingFor = playingX ? BoardTile.VariableState.O : BoardTile.VariableState.X; // Check all lines continaing this cell to see if the other two cells contain enemy moves foreach (var ticTacToeLine in TicTacToeLines) { var index = ticTacToeLine.FindCellIndex(x, y); switch (index) { case 0: if (_tiles[ticTacToeLine.Cells[1].X, ticTacToeLine.Cells[1].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[2].X, ticTacToeLine.Cells[2].Y].CurrentState == searchingFor) _availableMoves[x, y] += BlockingWeight; break; case 1: if (_tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[2].X, ticTacToeLine.Cells[2].Y].CurrentState == searchingFor) _availableMoves[x, y] += BlockingWeight; break; case 2: if (_tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[1].X, ticTacToeLine.Cells[1].Y].CurrentState == searchingFor) _availableMoves[x, y] += BlockingWeight; break; default: // We should get this if the index was -1 break; } } } private void CalculateCompletions(int x, int y) { var playingX = CurrentPlayerIndicatorState == PlayerIndicator.PlayerXMove; var searchingFor = playingX ? BoardTile.VariableState.X : BoardTile.VariableState.O; // Check all lines continaing this cell to see if the other two cells contain enemy moves foreach (var ticTacToeLine in TicTacToeLines) { var index = ticTacToeLine.FindCellIndex(x, y); switch (index) { case 0: if (_tiles[ticTacToeLine.Cells[1].X, ticTacToeLine.Cells[1].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[2].X, ticTacToeLine.Cells[2].Y].CurrentState == searchingFor) _availableMoves[x, y] += CompletionWeight; break; case 1: if (_tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[2].X, ticTacToeLine.Cells[2].Y].CurrentState == searchingFor) _availableMoves[x, y] += CompletionWeight; break; case 2: if (_tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[1].X, ticTacToeLine.Cells[1].Y].CurrentState == searchingFor) _availableMoves[x, y] += CompletionWeight; break; } } } private void CalculatePairs(int x, int y) { var playingX = CurrentPlayerIndicatorState == PlayerIndicator.PlayerXMove; var searchingFor = playingX ? BoardTile.VariableState.X : BoardTile.VariableState.O; // Check all lines continaing this cell to see if the other two cells contain enemy moves foreach (var ticTacToeLine in TicTacToeLines) { var index = ticTacToeLine.FindCellIndex(x, y); switch (index) { case 0: if (_tiles[ticTacToeLine.Cells[1].X, ticTacToeLine.Cells[1].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[2].X, ticTacToeLine.Cells[2].Y].CurrentState == BoardTile.VariableState.None) _availableMoves[x, y] += PairWeight; if (_tiles[ticTacToeLine.Cells[1].X, ticTacToeLine.Cells[1].Y].CurrentState == BoardTile.VariableState.None && _tiles[ticTacToeLine.Cells[2].X, ticTacToeLine.Cells[2].Y].CurrentState == searchingFor) _availableMoves[x, y] += PairWeight; break; case 1: if (_tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[2].X, ticTacToeLine.Cells[2].Y].CurrentState == BoardTile.VariableState.None) _availableMoves[x, y] += PairWeight; if (_tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState == BoardTile.VariableState.None && _tiles[ticTacToeLine.Cells[2].X, ticTacToeLine.Cells[2].Y].CurrentState == searchingFor) _availableMoves[x, y] += PairWeight; break; case 2: if (_tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState == searchingFor && _tiles[ticTacToeLine.Cells[1].X, ticTacToeLine.Cells[1].Y].CurrentState == BoardTile.VariableState.None) _availableMoves[x, y] += PairWeight; if (_tiles[ticTacToeLine.Cells[0].X, ticTacToeLine.Cells[0].Y].CurrentState == BoardTile.VariableState.None && _tiles[ticTacToeLine.Cells[1].X, ticTacToeLine.Cells[1].Y].CurrentState == searchingFor) _availableMoves[x, y] += PairWeight; break; } } } private void CalculateSingles() { // Adds one to every unoccupied cell. This prevents the random selection code from selecting // a cell that's already used, since all those cells will be 0 for(var i=0;i<3;i++) { for(var j=0;j<3;j++) { if (_tiles[i, j].CurrentState == BoardTile.VariableState.None) _availableMoves[i, j] += SingleWeight; } } } private List<GridSpace> GetHighestMoves() { var topVal = 0; for(var i=0;i<3;i++) { for(var j=0;j<3;j++) { if (_availableMoves[i, j] > topVal) topVal = _availableMoves[i, j]; } } var toReturn = new List<GridSpace>(); for(var i=0;i<3;i++) { for(var j=0;j<3;j++) { if(_availableMoves[i,j] == topVal) toReturn.Add(new GridSpace(i, j)); } } return toReturn; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_FieldInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class FieldInfo : MemberInfo, _FieldInfo { #region Static Members public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), nameof(handle)); FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo()); Type declaringType = f.DeclaringType; if (declaringType != null && declaringType.IsGenericType) throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"), f.Name, declaringType.GetGenericTypeDefinition())); return f; } [System.Runtime.InteropServices.ComVisible(false)] public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo()); } #endregion #region Constructor protected FieldInfo() { } #endregion public static bool operator ==(FieldInfo left, FieldInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeFieldInfo || right is RuntimeFieldInfo) { return false; } return left.Equals(right); } public static bool operator !=(FieldInfo left, FieldInfo right) { return !(left == right); } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } } #endregion #region Public Abstract\Virtual Members public virtual Type[] GetRequiredCustomModifiers() { throw new NotImplementedException(); } public virtual Type[] GetOptionalCustomModifiers() { throw new NotImplementedException(); } [CLSCompliant(false)] public virtual void SetValueDirect(TypedReference obj, Object value) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } [CLSCompliant(false)] public virtual Object GetValueDirect(TypedReference obj) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } public abstract RuntimeFieldHandle FieldHandle { get; } public abstract Type FieldType { get; } public abstract Object GetValue(Object obj); public virtual Object GetRawConstantValue() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture); public abstract FieldAttributes Attributes { get; } #endregion #region Public Members [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public void SetValue(Object obj, Object value) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null); } public bool IsPublic { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } } public bool IsPrivate { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } } public bool IsFamily { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } } public bool IsAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } } public bool IsFamilyAndAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } } public bool IsFamilyOrAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } } public bool IsStatic { get { return(Attributes & FieldAttributes.Static) != 0; } } public bool IsInitOnly { get { return(Attributes & FieldAttributes.InitOnly) != 0; } } public bool IsLiteral { get { return(Attributes & FieldAttributes.Literal) != 0; } } public bool IsNotSerialized { get { return(Attributes & FieldAttributes.NotSerialized) != 0; } } public bool IsSpecialName { get { return(Attributes & FieldAttributes.SpecialName) != 0; } } public bool IsPinvokeImpl { get { return(Attributes & FieldAttributes.PinvokeImpl) != 0; } } public virtual bool IsSecurityCritical { get { return FieldHandle.IsSecurityCritical(); } } public virtual bool IsSecuritySafeCritical { get { return FieldHandle.IsSecuritySafeCritical(); } } public virtual bool IsSecurityTransparent { get { return FieldHandle.IsSecurityTransparent(); } } #endregion #if !FEATURE_CORECLR Type _FieldInfo.GetType() { return base.GetType(); } void _FieldInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _FieldInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _FieldInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _FieldInfo.Invoke in VM\DangerousAPIs.h and // include _FieldInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _FieldInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable { #region Private Data Members private BindingFlags m_bindingFlags; protected RuntimeTypeCache m_reflectedTypeCache; protected RuntimeType m_declaringType; #endregion #region Constructor protected RuntimeFieldInfo() { // Used for dummy head node during population } protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags) { m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_reflectedTypeCache = reflectedTypeCache; } #endregion #if FEATURE_REMOTING #region Legacy Remoting Cache // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. // This member is currently being used by Remoting for caching remoting data. If you // need to cache data here, talk to the Remoting team to work out a mechanism, so that // both caching systems can happily work together. private RemotingFieldCachedData m_cachedData; internal RemotingFieldCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingFieldCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingFieldCachedData(this); RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region NonPublic Members internal BindingFlags BindingFlags { get { return m_bindingFlags; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal abstract RuntimeModule GetRuntimeModule(); #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Field; } } public override Type ReflectedType { get { return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; } } public override Type DeclaringType { get { return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; } } public override Module Module { get { return GetRuntimeModule(); } } #endregion #region Object Overrides public unsafe override String ToString() { return FieldType.FormatTypeName() + " " + Name; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region FieldInfo Overrides // All implemented on derived classes #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), MemberTypes.Field); } #endregion } [Serializable] internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo { #region FCalls [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags); #endregion #region Private Data Members // agressive caching private IntPtr m_fieldHandle; private FieldAttributes m_fieldAttributes; // lazy caching private string m_name; private RuntimeType m_fieldType; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; // Allow "value__" if (m_declaringType.IsEnum) return false; RuntimeAssembly rtAssembly = GetRuntimeAssembly(); if (rtAssembly.IsFrameworkAssembly()) { int ctorToken = rtAssembly.InvocableAttributeCtorToken; if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken)) return true; } return false; } #endif internal INVOCATION_FLAGS InvocationFlags { get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { Type declaringType = DeclaringType; bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType); INVOCATION_FLAGS invocationFlags = 0; // first take care of all the NO_INVOKE cases if ( (declaringType != null && declaringType.ContainsGenericParameters) || (declaringType == null && Module.Assembly.ReflectionOnly) || (fIsReflectionOnlyType) ) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } // If the invocationFlags are still 0, then // this should be an usable field, determine the other flags if (invocationFlags == 0) { if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; // A public field is inaccesible to Transparent code if the field is Critical. bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical; bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) || (declaringType != null && declaringType.NeedsReflectionSecurityCheck); if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; // find out if the field type is one of the following: Primitive, Enum or Pointer Type fieldType = FieldType; if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST; } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX // must be last to avoid threading problems m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); } #region Constructor [System.Security.SecurityCritical] // auto-generated internal RtFieldInfo( RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringType, bindingFlags) { m_fieldHandle = handle.Value; m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle); } #endregion #region Private Members RuntimeFieldHandleInternal IRuntimeFieldInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeFieldHandleInternal(m_fieldHandle); } } #endregion #region Internal Members internal void CheckConsistency(Object target) { // only test instance fields if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static) { if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) { throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg")); } else { throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"), Name, m_declaringType, target.GetType())); } } } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RtFieldInfo m = o as RtFieldInfo; if ((object)m == null) return false; return m.m_fieldHandle == m_fieldHandle; } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark) { INVOCATION_FLAGS invocationFlags = InvocationFlags; RuntimeType declaringType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { if (declaringType != null && declaringType.ContainsGenericParameters) throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); throw new FieldAccessException(); } CheckConsistency(obj); RuntimeType fieldType = (RuntimeType)FieldType; value = fieldType.CheckValue(value, binder, culture, invokeAttr); #region Security Check #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags); #endregion bool domainInitialized = false; if (declaringType == null) { RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; } } // UnsafeSetValue doesn't perform any consistency or visibility check. // It is the caller's responsibility to ensure the operation is safe. // When the caller needs to perform visibility checks they should call // InternalSetValue() instead. When the caller needs to perform // consistency checks they should call CheckConsistency() before // calling this method. [System.Security.SecurityCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { RuntimeType declaringType = DeclaringType as RuntimeType; RuntimeType fieldType = (RuntimeType)FieldType; value = fieldType.CheckValue(value, binder, culture, invokeAttr); bool domainInitialized = false; if (declaringType == null) { RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; } } [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark) { INVOCATION_FLAGS invocationFlags = InvocationFlags; RuntimeType declaringType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { if (declaringType != null && DeclaringType.ContainsGenericParameters) throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); throw new FieldAccessException(); } CheckConsistency(obj); #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif RuntimeType fieldType = (RuntimeType)FieldType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD)); return UnsafeGetValue(obj); } // UnsafeGetValue doesn't perform any consistency or visibility check. // It is the caller's responsibility to ensure the operation is safe. // When the caller needs to perform visibility checks they should call // InternalGetValue() instead. When the caller needs to perform // consistency checks they should call CheckConsistency() before // calling this method. [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal Object UnsafeGetValue(Object obj) { RuntimeType declaringType = DeclaringType as RuntimeType; RuntimeType fieldType = (RuntimeType)FieldType; bool domainInitialized = false; if (declaringType == null) { return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; return retVal; } } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = RuntimeFieldHandle.GetName(this); return m_name; } } internal String FullName { get { return String.Format("{0}.{1}", DeclaringType.FullName, Name); } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeFieldHandle.GetToken(this); } } [System.Security.SecuritySafeCritical] // auto-generated internal override RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this)); } #endregion #region FieldInfo Overrides public override Object GetValue(Object obj) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetValue(obj, ref stackMark); } public override object GetRawConstantValue() { throw new InvalidOperationException(); } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValueDirect(TypedReference obj) { if (obj.IsNull) throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); Contract.EndContractBlock(); unsafe { // Passing TypedReference by reference is easier to make correct in native code return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType); } } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark); } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValueDirect(TypedReference obj, Object value) { if (obj.IsNull) throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); Contract.EndContractBlock(); unsafe { // Passing TypedReference by reference is easier to make correct in native code RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType); } } public override RuntimeFieldHandle FieldHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeFieldHandle(this); } } internal IntPtr GetFieldHandle() { return m_fieldHandle; } public override FieldAttributes Attributes { get { return m_fieldAttributes; } } public override Type FieldType { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_fieldType == null) m_fieldType = new Signature(this, m_declaringType).FieldType; return m_fieldType; } } [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetRequiredCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, true); } [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetOptionalCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, false); } #endregion } [Serializable] internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable { #region Private Data Members private int m_tkField; private string m_name; private RuntimeType m_fieldType; private FieldAttributes m_fieldAttributes; #endregion #region Constructor internal MdFieldInfo( int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags) { m_tkField = tkField; m_name = null; m_fieldAttributes = fieldAttributes; } #endregion #region Internal Members [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { MdFieldInfo m = o as MdFieldInfo; if ((object)m == null) return false; return m.m_tkField == m_tkField && m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( m.m_declaringType.GetTypeHandleInternal().GetModuleHandle()); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString(); return m_name; } } public override int MetadataToken { get { return m_tkField; } } internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } #endregion #region FieldInfo Overrides public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } } public override FieldAttributes Attributes { get { return m_fieldAttributes; } } public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } } public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } } public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValueDirect(TypedReference obj) { return GetValue(null); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValueDirect(TypedReference obj,Object value) { throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public unsafe override Object GetValue(Object obj) { return GetValue(false); } public unsafe override Object GetRawConstantValue() { return GetValue(true); } [System.Security.SecuritySafeCritical] // auto-generated private unsafe Object GetValue(bool raw) { // Cannot cache these because they could be user defined non-agile enumerations Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw); if (value == DBNull.Value) throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound")); return value; } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); } public override Type FieldType { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_fieldType == null) { ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField); m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(), (int)fieldMarshal.Length, m_declaringType).FieldType; } return m_fieldType; } } public override Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; } public override Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; } #endregion } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.EntityState.Appearance { /// <summary> /// Enumeration values for SpacePlatformAppearance (es.appear.platform.space, Platforms of the Space Domain, /// section 4.3.1.5) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public struct SpacePlatformAppearance { /// <summary> /// Describes the paint scheme of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the paint scheme of an entity")] public enum PaintSchemeValue : uint { /// <summary> /// Uniform color /// </summary> UniformColor = 0, /// <summary> /// Camouflage /// </summary> Camouflage = 1 } /// <summary> /// Describes characteristics of mobility kills /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes characteristics of mobility kills")] public enum MobilityValue : uint { /// <summary> /// No mobility kill /// </summary> NoMobilityKill = 0, /// <summary> /// Mobility kill /// </summary> MobilityKill = 1 } /// <summary> /// Describes the damaged appearance of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the damaged appearance of an entity")] public enum DamageValue : uint { /// <summary> /// No damage /// </summary> NoDamage = 0, /// <summary> /// Slight damage /// </summary> SlightDamage = 1, /// <summary> /// Moderate damage /// </summary> ModerateDamage = 2, /// <summary> /// Destroyed /// </summary> Destroyed = 3 } /// <summary> /// Describes status or location of smoke emanating from an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes status or location of smoke emanating from an entity")] public enum SmokeValue : uint { /// <summary> /// Not smoking /// </summary> NotSmoking = 0, /// <summary> /// Smoke plume rising from the entity /// </summary> SmokePlumeRisingFromTheEntity = 1, /// <summary> /// null /// </summary> Unknown = 2 } /// <summary> /// Describes whether flames are rising from an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether flames are rising from an entity")] public enum FlamingValue : uint { /// <summary> /// None /// </summary> None = 0, /// <summary> /// Flames present /// </summary> FlamesPresent = 1 } /// <summary> /// Describes the frozen status of a space platform /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the frozen status of a space platform")] public enum FrozenStatusValue : uint { /// <summary> /// Not frozen /// </summary> NotFrozen = 0, /// <summary> /// Frozen (Frozen entities should not be dead-reckoned, i.e. they should be displayed as fixed at the current location even if nonzero velocity, acceleration or rotation data is received from the frozen entity) /// </summary> FrozenFrozenEntitiesShouldNotBeDeadReckonedIETheyShouldBeDisplayedAsFixedAtTheCurrentLocationEvenIfNonzeroVelocityAccelerationOrRotationDataIsReceivedFromTheFrozenEntity = 1 } /// <summary> /// Describes the power-plant status of a space platform /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the power-plant status of a space platform")] public enum PowerPlantStatusValue : uint { /// <summary> /// Power plant off /// </summary> PowerPlantOff = 0, /// <summary> /// Power plant on /// </summary> PowerPlantOn = 1 } /// <summary> /// Describes the state of a space platform /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the state of a space platform")] public enum StateValue : uint { /// <summary> /// Active /// </summary> Active = 0, /// <summary> /// Deactivated /// </summary> Deactivated = 1 } private SpacePlatformAppearance.PaintSchemeValue paintScheme; private SpacePlatformAppearance.MobilityValue mobility; private SpacePlatformAppearance.DamageValue damage; private SpacePlatformAppearance.SmokeValue smoke; private SpacePlatformAppearance.FlamingValue flaming; private SpacePlatformAppearance.FrozenStatusValue frozenStatus; private SpacePlatformAppearance.PowerPlantStatusValue powerPlantStatus; private SpacePlatformAppearance.StateValue state; /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(SpacePlatformAppearance left, SpacePlatformAppearance right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(SpacePlatformAppearance left, SpacePlatformAppearance right) { if (object.ReferenceEquals(left, right)) { return true; } // If parameters are null return false (cast to object to prevent recursive loop!) if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } /// <summary> /// Performs an explicit conversion from <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> to <see cref="System.UInt32"/>. /// </summary> /// <param name="obj">The <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> scheme instance.</param> /// <returns>The result of the conversion.</returns> public static explicit operator uint(SpacePlatformAppearance obj) { return obj.ToUInt32(); } /// <summary> /// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/>. /// </summary> /// <param name="value">The uint value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator SpacePlatformAppearance(uint value) { return SpacePlatformAppearance.FromUInt32(value); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance from the byte array. /// </summary> /// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/>.</param> /// <param name="index">The starting position within value.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance, represented by a byte array.</returns> /// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception> /// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception> public static SpacePlatformAppearance FromByteArray(byte[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length - 1 || index + 4 > array.Length - 1) { throw new IndexOutOfRangeException(); } return FromUInt32(BitConverter.ToUInt32(array, index)); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance from the uint value. /// </summary> /// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance, represented by the uint value.</returns> public static SpacePlatformAppearance FromUInt32(uint value) { SpacePlatformAppearance ps = new SpacePlatformAppearance(); uint mask0 = 0x0001; byte shift0 = 0; uint newValue0 = value & mask0 >> shift0; ps.PaintScheme = (SpacePlatformAppearance.PaintSchemeValue)newValue0; uint mask1 = 0x0002; byte shift1 = 1; uint newValue1 = value & mask1 >> shift1; ps.Mobility = (SpacePlatformAppearance.MobilityValue)newValue1; uint mask3 = 0x0018; byte shift3 = 3; uint newValue3 = value & mask3 >> shift3; ps.Damage = (SpacePlatformAppearance.DamageValue)newValue3; uint mask4 = 0x0060; byte shift4 = 5; uint newValue4 = value & mask4 >> shift4; ps.Smoke = (SpacePlatformAppearance.SmokeValue)newValue4; uint mask6 = 0x8000; byte shift6 = 15; uint newValue6 = value & mask6 >> shift6; ps.Flaming = (SpacePlatformAppearance.FlamingValue)newValue6; uint mask8 = 0x200000; byte shift8 = 21; uint newValue8 = value & mask8 >> shift8; ps.FrozenStatus = (SpacePlatformAppearance.FrozenStatusValue)newValue8; uint mask9 = 0x400000; byte shift9 = 22; uint newValue9 = value & mask9 >> shift9; ps.PowerPlantStatus = (SpacePlatformAppearance.PowerPlantStatusValue)newValue9; uint mask10 = 0x800000; byte shift10 = 23; uint newValue10 = value & mask10 >> shift10; ps.State = (SpacePlatformAppearance.StateValue)newValue10; return ps; } /// <summary> /// Gets or sets the paintscheme. /// </summary> /// <value>The paintscheme.</value> public SpacePlatformAppearance.PaintSchemeValue PaintScheme { get { return this.paintScheme; } set { this.paintScheme = value; } } /// <summary> /// Gets or sets the mobility. /// </summary> /// <value>The mobility.</value> public SpacePlatformAppearance.MobilityValue Mobility { get { return this.mobility; } set { this.mobility = value; } } /// <summary> /// Gets or sets the damage. /// </summary> /// <value>The damage.</value> public SpacePlatformAppearance.DamageValue Damage { get { return this.damage; } set { this.damage = value; } } /// <summary> /// Gets or sets the smoke. /// </summary> /// <value>The smoke.</value> public SpacePlatformAppearance.SmokeValue Smoke { get { return this.smoke; } set { this.smoke = value; } } /// <summary> /// Gets or sets the flaming. /// </summary> /// <value>The flaming.</value> public SpacePlatformAppearance.FlamingValue Flaming { get { return this.flaming; } set { this.flaming = value; } } /// <summary> /// Gets or sets the frozenstatus. /// </summary> /// <value>The frozenstatus.</value> public SpacePlatformAppearance.FrozenStatusValue FrozenStatus { get { return this.frozenStatus; } set { this.frozenStatus = value; } } /// <summary> /// Gets or sets the powerplantstatus. /// </summary> /// <value>The powerplantstatus.</value> public SpacePlatformAppearance.PowerPlantStatusValue PowerPlantStatus { get { return this.powerPlantStatus; } set { this.powerPlantStatus = value; } } /// <summary> /// Gets or sets the state. /// </summary> /// <value>The state.</value> public SpacePlatformAppearance.StateValue State { get { return this.state; } set { this.state = value; } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is SpacePlatformAppearance)) { return false; } return this.Equals((SpacePlatformAppearance)obj); } /// <summary> /// Determines whether the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(SpacePlatformAppearance other) { // If parameter is null return false (cast to object to prevent recursive loop!) if ((object)other == null) { return false; } return this.PaintScheme == other.PaintScheme && this.Mobility == other.Mobility && this.Damage == other.Damage && this.Smoke == other.Smoke && this.Flaming == other.Flaming && this.FrozenStatus == other.FrozenStatus && this.PowerPlantStatus == other.PowerPlantStatus && this.State == other.State; } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> to the byte array. /// </summary> /// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance.</returns> public byte[] ToByteArray() { return BitConverter.GetBytes(this.ToUInt32()); } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> to the uint value. /// </summary> /// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.SpacePlatformAppearance"/> instance.</returns> public uint ToUInt32() { uint val = 0; val |= (uint)((uint)this.PaintScheme << 0); val |= (uint)((uint)this.Mobility << 1); val |= (uint)((uint)this.Damage << 3); val |= (uint)((uint)this.Smoke << 5); val |= (uint)((uint)this.Flaming << 15); val |= (uint)((uint)this.FrozenStatus << 21); val |= (uint)((uint)this.PowerPlantStatus << 22); val |= (uint)((uint)this.State << 23); return val; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { int hash = 17; // Overflow is fine, just wrap unchecked { hash = (hash * 29) + this.PaintScheme.GetHashCode(); hash = (hash * 29) + this.Mobility.GetHashCode(); hash = (hash * 29) + this.Damage.GetHashCode(); hash = (hash * 29) + this.Smoke.GetHashCode(); hash = (hash * 29) + this.Flaming.GetHashCode(); hash = (hash * 29) + this.FrozenStatus.GetHashCode(); hash = (hash * 29) + this.PowerPlantStatus.GetHashCode(); hash = (hash * 29) + this.State.GetHashCode(); } return hash; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { using System.IO; using System.Net; // Summary: // Provides the underlying stream of data for network access. public class NetworkStream : Stream { // Summary: // Internal members internal Socket m_socket; // Internal Socket object protected int m_socketType; // Internal property used to store the socket type protected EndPoint m_remoteEndPoint; // Internal endpoint ref used for dgram sockets private bool m_ownsSocket; // Internal flags protected bool m_disposed; // Summary: // Creates a new instance of the System.Net.Sockets.NetworkStream class for // the specified System.Net.Sockets.Socket. // // Parameters: // socket: // The System.Net.Sockets.Socket that the System.Net.Sockets.NetworkStream will // use to send and receive data. // // Exceptions: // System.ArgumentNullException: // socket is null. // // System.IO.IOException: // socket is not connected.-or- The System.Net.Sockets.Socket.SocketType property // of socket is not System.Net.Sockets.SocketType.Stream.-or- socket is in a // nonblocking state. public NetworkStream(Socket socket) : this(socket, false) { } // // Summary: // Initializes a new instance of the System.Net.Sockets.NetworkStream class // for the specified System.Net.Sockets.Socket with the specified System.Net.Sockets.Socket // ownership. // // Parameters: // ownsSocket: // true to indicate that the System.Net.Sockets.NetworkStream will take ownership // of the System.Net.Sockets.Socket; otherwise, false. // // socket: // The System.Net.Sockets.Socket that the System.Net.Sockets.NetworkStream will // use to send and receive data. // // Exceptions: // System.IO.IOException: // socket is not connected.-or- The value of the System.Net.Sockets.Socket.SocketType // property of socket is not System.Net.Sockets.SocketType.Stream.-or- socket // is in a nonblocking state. // // System.ArgumentNullException: // socket is null. public NetworkStream(Socket socket, bool ownsSocket) { if (socket == null) throw new ArgumentNullException(); // This should throw a SocketException if not connected try { m_remoteEndPoint = socket.RemoteEndPoint; } catch (Exception e) { int errCode = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error); throw new IOException(errCode.ToString(), e); } // Set the internal socket m_socket = socket; m_socketType = (int)m_socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Type); m_ownsSocket = ownsSocket; } // Summary: // Gets a value that indicates whether the System.Net.Sockets.NetworkStream // supports reading. // // Returns: // true if data can be read from the stream; otherwise, false. The default value // is true. public override bool CanRead { get { return true; } } // // Summary: // Gets a value that indicates whether the stream supports seeking. This property // is not currently supported.This property always returns false. // // Returns: // false in all cases to indicate that System.Net.Sockets.NetworkStream cannot // seek a specific location in the stream. public override bool CanSeek { get { return false; } } // // Summary: // Indicates whether timeout properties are usable for System.Net.Sockets.NetworkStream. // // Returns: // true in all cases. public override bool CanTimeout { get { return true; } } // // Summary: // Gets a value that indicates whether the System.Net.Sockets.NetworkStream // supports writing. // // Returns: // true if data can be written to the System.Net.Sockets.NetworkStream; otherwise, // false. The default value is true. public override bool CanWrite { get { return true; } } public override int ReadTimeout { get { return m_socket.ReceiveTimeout; } set { if (value == 0 || value < System.Threading.Timeout.Infinite) throw new ArgumentOutOfRangeException(); m_socket.ReceiveTimeout = value; } } public override int WriteTimeout { get { return m_socket.SendTimeout; } set { if (value == 0 || value < System.Threading.Timeout.Infinite) throw new ArgumentOutOfRangeException(); m_socket.SendTimeout = value; } } // // Summary: // Gets the length of the data available on the stream. // // Returns: // The length of the data available on the stream. // // Exceptions: // InvalidOperationException - when socket is disposed. public override long Length { get { if (m_disposed == true) throw new ObjectDisposedException( "" ); if (m_socket.m_handle == -1) throw new IOException(); return m_socket.Available; } } // // Summary: // Gets or sets the current position in the stream. This property is not currently // supported and always throws a System.NotSupportedException. // // Returns: // The current position in the stream. // // Exceptions: // System.NotSupportedException: // Any use of this property. public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public virtual bool DataAvailable { get { if (m_disposed == true) throw new ObjectDisposedException( "" ); if (m_socket.m_handle == -1) throw new IOException(); return (m_socket.Available > 0); } } // // Summary: // Closes the System.Net.Sockets.NetworkStream after waiting the specified time // to allow data to be sent. // // Parameters: // timeout: // A 32-bit signed integer that specifies how long to wait to send any remaining // data before closing. // // Exceptions: // System.ArgumentOutOfRangeException: // timeout is less than -1. public void Close(int timeout) { if (timeout < -1) throw new ArgumentOutOfRangeException(); System.Threading.Thread.Sleep(timeout); Close(); } // // Summary: // Releases the unmanaged resources used by the System.Net.Sockets.NetworkStream // and optionally releases the managed resources. // // Parameters: // disposing: // true to release both managed and unmanaged resources; false to release only // unmanaged resources. protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if (m_ownsSocket == true) m_socket.Close(); } } finally { m_disposed = true; } } } // // Summary: // Flushes data from the stream. This method is reserved for future use. public override void Flush() { } // // Summary: // Reads data from the System.Net.Sockets.NetworkStream. // // Parameters: // offset: // The location in buffer to begin storing the data to. // // size: // The number of bytes to read from the System.Net.Sockets.NetworkStream. // // buffer: // An array of type System.Byte that is the location in memory to store data // read from the System.Net.Sockets.NetworkStream. // // Returns: // The number of bytes read from the System.Net.Sockets.NetworkStream. // // Exceptions: // System.IO.IOException: // The underlying System.Net.Sockets.Socket is closed. // // System.ArgumentNullException: // buffer is null. // // System.ObjectDisposedException: // The System.Net.Sockets.NetworkStream is closed.-or- There is a failure reading // from the network. // // System.ArgumentOutOfRangeException: // offset is less than 0.-or- offset is greater than the length of buffer.-or- // size is less than 0.-or- size is greater than the length of buffer minus // the value of the offset parameter. -or-An error occurred when accessing the // socket. See the Remarks section for more information. public override int Read(byte[] buffer, int offset, int count) { if (m_disposed) throw new ObjectDisposedException( "" ); if (m_socket.m_handle == -1) throw new IOException(); if (buffer == null) throw new ArgumentNullException(); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(); int available = m_socket.Available; // we will need to read using thr timeout specified // if there is data available we can return with that data only // the underlying socket infrastructure will handle the timeout if (count > available && available > 0) { count = available; } if (m_socketType == (int)SocketType.Stream) { return m_socket.Receive(buffer, offset, count, SocketFlags.None); } else if (m_socketType == (int)SocketType.Dgram) { return m_socket.ReceiveFrom(buffer, offset, count, SocketFlags.None, ref m_remoteEndPoint); } else { throw new NotSupportedException(); } } // // Summary: // Sets the current position of the stream to the given value. This method is // not currently supported and always throws a System.NotSupportedException. // // Parameters: // offset: // This parameter is not used. // // origin: // This parameter is not used. // // Returns: // The position in the stream. // // Exceptions: // System.NotSupportedException: // Any use of this property. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } // // Summary: // Sets the length of the stream. This method always throws a System.NotSupportedException. // // Parameters: // value: // This parameter is not used. // // Exceptions: // System.NotSupportedException: // Any use of this property. public override void SetLength(long value) { throw new NotSupportedException(); } // // Summary: // Writes data to the System.Net.Sockets.NetworkStream. // // Parameters: // offset: // The location in buffer from which to start writing data. // // size: // The number of bytes to write to the System.Net.Sockets.NetworkStream. // // buffer: // An array of type System.Byte that contains the data to write to the System.Net.Sockets.NetworkStream. // // Exceptions: // System.ArgumentOutOfRangeException: // offset is less than 0.-or- offset is greater than the length of buffer.-or- // size is less than 0.-or- size is greater than the length of buffer minus // the value of the offset parameter. // // System.ObjectDisposedException: // The System.Net.Sockets.NetworkStream is closed.-or- There was a failure reading // from the network. // // System.IO.IOException: // There was a failure while writing to the network. -or-An error occurred when // accessing the socket. See the Remarks section for more information. // // System.ArgumentNullException: // buffer is null. public override void Write(byte[] buffer, int offset, int count) { if (m_disposed) throw new ObjectDisposedException( "" ); if (m_socket.m_handle == -1) throw new IOException(); if (buffer == null) throw new ArgumentNullException(); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(); int bytesSent = 0; if (m_socketType == (int)SocketType.Stream) { bytesSent = m_socket.Send(buffer, offset, count, SocketFlags.None); } else if (m_socketType == (int)SocketType.Dgram) { bytesSent = m_socket.SendTo(buffer, offset, count, SocketFlags.None, m_socket.RemoteEndPoint); } else { throw new NotSupportedException(); } if (bytesSent != count) throw new IOException(); } } }
#if UNITY_EDITOR using UnityEngine.Networking; using System.Text; namespace NetworkScopes { using System; using UnityEditor; using System.Collections.Generic; using System.Reflection; using UnityEngine; using System.Linq; public static class ScopeDebugger { public struct ScopeEvents { public ScopeEvents(BaseScope scope) { this.scope = scope; signals = new List<SignalEvent>(100); events = new List<ScopeEvent>(10); } public BaseScope scope { get; private set; } public List<SignalEvent> signals { get; private set; } public List<ScopeEvent> events { get; private set; } public SignalEvent AddSignalEvent(MethodInfo method, NetworkReader reader, bool outgoing) { signals.Add(new SignalEvent(method, reader, outgoing)); return signals[signals.Count-1]; } public ScopeEvent AddScopeEvent(ScopeEvent.Type eventType, BaseScope scope1, BaseScope scope2) { events.Add(new ScopeEvent(eventType, scope1, scope2)); return events[events.Count-1]; } } public struct ScopeEvent { public enum Type { Enter, Exit, Switch, } public Type type; public BaseScope scope1; public BaseScope scope2; public DateTime receiveTime { get; private set; } public ScopeEvent(Type eventType, BaseScope scope1, BaseScope scope2) { type = eventType; this.scope1 = scope1; this.scope2 = scope2; receiveTime = DateTime.Now; } } public struct SignalEvent { public MethodInfo method { get; private set; } public string[] parameters { get; private set; } public DateTime receiveTime { get; private set; } public bool isOutgoing { get; private set; } public SignalEvent(MethodInfo method, NetworkReader reader, bool outgoing) { this.method = method; this.isOutgoing = outgoing; receiveTime = DateTime.Now; parameters = new string[0]; if (method != null) SetParameters(method.GetParameters(), reader); } void SetParameters(ParameterInfo[] pi, NetworkReader reader) { parameters = new string[pi.Length]; for (int x = 0; x < pi.Length; x++) parameters[x] = ReadParameterToString(pi[x].ParameterType, reader); } string ReadParameterToString(Type t, NetworkReader reader) { if (t.IsArray) { Type elemType = t.GetElementType(); int count = reader.ReadInt32(); StringBuilder sb = new StringBuilder(); sb.Append("["); for (int x = 0; x < count; x++) { if (x != 0) sb.Append(", "); sb.Append(ReadParameterToString(elemType, reader)); } sb.Append("]"); return sb.ToString(); } else { if (t == typeof(int)) return reader.ReadInt32().ToString(); else if (t == typeof(string)) return reader.ReadString(); else if (t == typeof(short)) return reader.ReadInt16().ToString(); else if (t == typeof(byte)) return reader.ReadByte().ToString(); else if (t.IsEnum) { return Enum.Parse(t, reader.ReadByte().ToString()).ToString(); } else { MethodInfo deserializeMethod = t.GetMethod("NetworkDeserialize", BindingFlags.Static | BindingFlags.Public); if (deserializeMethod != null) { object value = Activator.CreateInstance(t); deserializeMethod.Invoke(null, new object[] { value, reader }); return value.ToString(); } else return string.Format("[{0}]", t.Name); } } } } public static List<ScopeEvents> scopeEventsList = null; public static bool IsEnabled { get { return scopeEventsList != null; } } public static event Action<BaseScope,SignalEvent> OnSignalEvent = null; public static event Action<BaseScope,BaseScope,ScopeEvent> OnScopeEvent = null; private static ScopeEvents GetOrCreateScopeEvent(BaseScope scope) { if (scopeEventsList == null) { scopeEventsList = new List<ScopeEvents>(); } // find event int scopeEventIndex = scopeEventsList.FindIndex(s => s.scope == scope); // create and add if not found if (scopeEventIndex == -1) { ScopeEvents ev = new ScopeEvents(scope); scopeEventsList.Add(ev); return ev; } return scopeEventsList[scopeEventIndex]; } public static void AddScopeEvent(BaseScope scope, BaseScope otherScope, ScopeEvent.Type scopeEv) { ScopeEvents ev = GetOrCreateScopeEvent(scope); ScopeEvent scopeEvent = ev.AddScopeEvent(scopeEv, scope, otherScope); if (OnScopeEvent != null) OnScopeEvent(scope, otherScope, scopeEvent); } public static void AddIncomingSignal(BaseScope scope, NetworkReader reader) { int signalType = reader.ReadInt32(); MethodInfo method = scope.GetType().GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public).FirstOrDefault(m => m.Name.GetHashCode() == signalType); ScopeEvents ev = GetOrCreateScopeEvent(scope); SignalEvent sigEvent = ev.AddSignalEvent(method, reader, false); reader.SeekZero(); if (OnSignalEvent != null) OnSignalEvent(scope, sigEvent); } public static void AddOutgoingSignal(BaseScope scope, Type outgoingScopeType, NetworkReader reader) { // read useless data reader.ReadInt32(); int signalType = reader.ReadInt32(); MethodInfo method = outgoingScopeType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public).FirstOrDefault(m => m.Name.GetHashCode() == signalType); if (method == null) Debug.Log("Could not find method with sigType " + signalType); ScopeEvents ev = GetOrCreateScopeEvent(scope); SignalEvent sigEvent = ev.AddSignalEvent(method, reader, false); reader.SeekZero(); if (OnSignalEvent != null) OnSignalEvent(scope, sigEvent); } public static void Dispose() { scopeEventsList = null; OnSignalEvent = null; OnScopeEvent = null; } } } #endif
//WordSlide //Copyright (C) 2008-2012 Jonathan Ray <asky314159@gmail.com> //WordSlide 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 3 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. //A copy of the GNU General Public License should be in the //Installer directory of this source tree. If not, see //<http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using WordSlideEngine; namespace WordSlide { /// <summary> /// The Importer class stores static functions used to import slide data from various sources. /// </summary> public class Importer { /// <summary> /// The ErrorCode enumeration allows the importer functions to communicate back to the Import /// form what went wrong during an import, allowing the form to display an apppropriate /// error message. /// </summary> public enum ImporterErrorCode { Unset, CompletedSucessfully, GenericError, SearchTermNotFound, SearchConstantIncorrect } /// <summary> /// Stores an EditableSlideSet generated by one of the importer functions. Use this property /// to retrieve the results after running the appropriate function. /// </summary> private static EditableSlideSet iss; /// <summary> /// Stores an EditableSlideSet generated by one of the importer functions. Use this property /// to retrieve the results after running the appropriate function. /// </summary> public static EditableSlideSet ImportedSlideSet { get { return iss; } } /// <summary> /// Import a SlideSet using the data stored at the RUF Hymnbook website. /// </summary> /// <param name="url">Either the name of a song to search for or a URL directly to a song page.</param> /// <returns>Returns an ErrorCode specifying what went wrong during the import.</returns> public static ImporterErrorCode importRHO(string url) { //http://www.developer.com/net/csharp/article.php/2230091 Try this? try { WebClient client = new WebClient(); iss = new EditableSlideSet(); if (!url.Contains(".html")) { string search = client.DownloadString("http://www.igracemusic.com/hymnbook/hymns.html"); url = url.ToLower(); search = search.ToLower(); int sindex = search.IndexOf(url); if (sindex == -1) return ImporterErrorCode.SearchTermNotFound; string urlfind = "<a href=\""; int uindex = 0; while (true) { int utemp = search.IndexOf(urlfind, uindex + 1); if (utemp > sindex) break; uindex = utemp; if (uindex == -1) return ImporterErrorCode.SearchConstantIncorrect; } uindex += urlfind.Length; int ulength = (search.IndexOf("\"", uindex) - uindex); url = "http://www.igracemusic.com/hymnbook/" + search.Substring(uindex, ulength); } string titlefind = " class=\"header1\">"; string versefind = " class=\"body\">"; string endversefind = "<a href=\"#top\">"; string page = client.DownloadString(url); int index = page.IndexOf(titlefind); int length = (page.IndexOf("</p>", index) - index - titlefind.Length); iss.Name = page.Substring((index + titlefind.Length), length); iss.Name = stripHTML(iss.Name); int chop = (page.IndexOf(endversefind, index) - index); string verses = page.Substring(index, chop); chop = 0; int n = 0; while (true) { chop = verses.IndexOf(versefind, chop + 1); if (chop == -1) break; n++; } iss.setupTexts(n - 1, 0); index = 0; for (int x = 0; x < (n - 1); x++) { index = verses.IndexOf(versefind, index + 1); length = (verses.IndexOf("</p>", index) - index - versefind.Length); string verse = verses.Substring((index + versefind.Length), length); verse = verse.Replace("&#146;", "'"); verse = verse.Replace("&quot;", "\""); verse = verse.Replace("<br>\n", System.Environment.NewLine); verse = verse.Replace(" ", ""); verse = stripHTML(verse); iss.addText(x, verse, 0); } } catch (Exception e) { //Program.ReportError(e); return ImporterErrorCode.GenericError; } return ImporterErrorCode.CompletedSucessfully; } /// <summary> /// Import a SlideSet using data stored at the Cyber Hymnal website. /// </summary> /// <param name="url">Either the name of a song to search for or a URL directly to a song page.</param> /// <returns>Returns an ErrorCode specifying what went wrong during the import.</returns> public static ImporterErrorCode importCH(string url) { try { WebClient client = new WebClient(); iss = new EditableSlideSet(); if (!url.Contains(".htm")) { url = url.ToLower(); string search = client.DownloadString("http://www.cyberhymnal.org/ttl/ttl-" + url.ToCharArray()[0] + ".htm"); search = search.Replace("&#8217;", "'"); search = search.ToLower(); int sindex = search.IndexOf(url); if (sindex == -1) return ImporterErrorCode.SearchTermNotFound; string urlfind = "<a href=\".."; int uindex = 0; while (true) { int utemp = search.IndexOf(urlfind, uindex + 1); if (utemp > sindex) break; uindex = utemp; if (uindex == -1) return ImporterErrorCode.SearchConstantIncorrect; } uindex += urlfind.Length; int ulength = (search.IndexOf("\"", uindex) - uindex); url = "http://www.cyberhymnal.org" + search.Substring(uindex, ulength); } string titlefind = "<title>"; string versefind = "<p>"; string chorusfind = "<p class=\"chorus\">"; string versesectionfind = "<div class=\"lyrics\">"; string page = client.DownloadString(url); int index = page.IndexOf(titlefind); int length = (page.IndexOf("</title>", index) - index - titlefind.Length); iss.Name = page.Substring((index + titlefind.Length), length); index = page.IndexOf(versesectionfind); int chop = (page.IndexOf("</div>", index) - index); string verses = page.Substring(index, chop); chop = 0; int n = 0; while (true) { chop = verses.IndexOf(versefind, chop + 1); if (chop == -1) break; n++; } bool haschorus = false; if (verses.Contains(chorusfind)) { n++; haschorus = true; } iss.setupTexts(n, 0); index = 0; for (int x = 0; x < (n - (haschorus ? 1 : 0)); x++) { index = verses.IndexOf(versefind, index + 1); length = (verses.IndexOf("</p>", index) - index - versefind.Length); string verse = verses.Substring((index + versefind.Length), length); verse = verse.Replace("<br />", ""); verse = verse.Replace("&#8217;", "'"); verse = verse.Replace("&#8212;", ";"); verse = verse.Replace("&#8220;", "\""); verse = verse.Replace("&#8221;", ","); verse = stripHTML(verse); iss.addText(x, verse, 0); } if (haschorus) { index = 0; index = verses.IndexOf(chorusfind, index + 1); index = verses.IndexOf(chorusfind, index + 1); length = (verses.IndexOf("</p>", index) - index - chorusfind.Length); string chorus = verses.Substring((index + chorusfind.Length), length); chorus = chorus.Replace("<br />", ""); chorus = chorus.Replace("&#8217;", "'"); chorus = chorus.Replace("&#8212;", ";"); chorus = chorus.Replace("&#8220;", "\""); chorus = chorus.Replace("&#8221;", ","); chorus = stripHTML(chorus); iss.addText(n - 1, chorus, 0); iss.Chorus = n - 1; } } catch (Exception e) { //Program.ReportError(e); return ImporterErrorCode.GenericError; } return ImporterErrorCode.CompletedSucessfully; } /// <summary> /// Import a SlideSet into the program's folder using an existing .sld file. /// </summary> /// <param name="path">The full path to the .sld file to import.</param> /// <returns>Returns an ErrorCode specifying what went wrong during the import.</returns> public static ImporterErrorCode importSLD(string path) { try { iss = new EditableSlideSet(path); iss.loadFile(); iss.resetPath(); } catch (Exception e) { //Program.ReportError(e); return ImporterErrorCode.GenericError; } return ImporterErrorCode.CompletedSucessfully; } /// <summary> /// This function does not work. Do not use. /// </summary> /// <param name="path">This function does not work. Do not use.</param> /// <returns>Thus function does not work. Do not use.</returns> public static ImporterErrorCode importPPT(string path) { try { iss = new EditableSlideSet(); StreamReader reader = new StreamReader(path); bool flag1 = false; bool flag2 = false; bool flag3 = false; int count = 0; string text = ""; while (!reader.EndOfStream) { int ch = reader.Read(); if (flag1 && flag2) { if (count == 0 && ch == 2) { flag1 = false; } if (count < 4) { count++; } else { if (ch == 0) { if (flag3) { flag1 = false; iss.Name += "i"; } else { flag3 = true; } } else { text += (char)ch; } } } else { text = ""; count = 0; if (flag1 && ch == 15) { flag2 = true; } else { flag1 = false; flag2 = false; if (ch == 160 || ch == 168) { flag1 = true; } } } } reader.Close(); } catch (Exception e) { //Program.ReportError(e); return ImporterErrorCode.GenericError; } return ImporterErrorCode.CompletedSucessfully; } /// <summary> /// Takes a string of text and strips all HTML tags from it. Indended to be used in /// conjunction with the various importers. /// </summary> /// <param name="input">The string to strip tags from.</param> /// <returns>The input string without HTML tags.</returns> public static string stripHTML(string input) { int first = -1; string temp = input; for (int x = 0; x < temp.Length; x++) { if (temp[x] == '<') { first = x; } if (temp[x] == '>' && first != -1) { temp = temp.Remove(first, (x - first + 1)); first = -1; } } return temp; } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using System.IO; using Mono.Collections.Generic; using Microsoft.Cci.Pdb; using Mono.Cecil.Cil; namespace Mono.Cecil.Pdb { public class NativePdbReader : ISymbolReader { int age; Guid guid; readonly Disposable<Stream> pdb_file; readonly Dictionary<string, Document> documents = new Dictionary<string, Document> (); readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction> (); readonly Dictionary<PdbScope, ImportDebugInformation> imports = new Dictionary<PdbScope, ImportDebugInformation> (); internal NativePdbReader (Disposable<Stream> file) { this.pdb_file = file; } public ISymbolWriterProvider GetWriterProvider () { return new NativePdbWriterProvider (); } /* uint Magic = 0x53445352; Guid Signature; uint Age; string FileName; */ public bool ProcessDebugHeader (ImageDebugHeader header) { if (!header.HasEntries) return false; var entry = header.GetCodeViewEntry (); if (entry == null) return false; var directory = entry.Directory; if (directory.Type != ImageDebugType.CodeView) return false; var data = entry.Data; if (data.Length < 24) return false; var magic = ReadInt32 (data, 0); if (magic != 0x53445352) return false; var guid_bytes = new byte [16]; Buffer.BlockCopy (data, 4, guid_bytes, 0, 16); this.guid = new Guid (guid_bytes); this.age = ReadInt32 (data, 20); return PopulateFunctions (); } static int ReadInt32 (byte [] bytes, int start) { return (bytes [start] | (bytes [start + 1] << 8) | (bytes [start + 2] << 16) | (bytes [start + 3] << 24)); } bool PopulateFunctions () { using (pdb_file) { var info = PdbFile.LoadFunctions (pdb_file.value); if (this.guid != info.Guid) return false; foreach (PdbFunction function in info.Functions) functions.Add (function.token, function); } return true; } public MethodDebugInformation Read (MethodDefinition method) { var method_token = method.MetadataToken; PdbFunction function; if (!functions.TryGetValue (method_token.ToUInt32 (), out function)) return null; var symbol = new MethodDebugInformation (method); ReadSequencePoints (function, symbol); symbol.scope = !function.scopes.IsNullOrEmpty () ? ReadScopeAndLocals (function.scopes [0], symbol) : new ScopeDebugInformation { Start = new InstructionOffset (0), End = new InstructionOffset ((int) function.length) }; if (function.tokenOfMethodWhoseUsingInfoAppliesToThisMethod != method.MetadataToken.ToUInt32 () && function.tokenOfMethodWhoseUsingInfoAppliesToThisMethod != 0) symbol.scope.import = GetImport (function.tokenOfMethodWhoseUsingInfoAppliesToThisMethod, method.Module); if (function.scopes.Length > 1) { for (int i = 1; i < function.scopes.Length; i++) { var s = ReadScopeAndLocals (function.scopes [i], symbol); if (!AddScope (symbol.scope.Scopes, s)) symbol.scope.Scopes.Add (s); } } if (function.iteratorScopes != null) { var state_machine = new StateMachineScopeDebugInformation (); foreach (var iterator_scope in function.iteratorScopes) { state_machine.Scopes.Add (new StateMachineScope ((int) iterator_scope.Offset, (int) (iterator_scope.Offset + iterator_scope.Length + 1))); } symbol.CustomDebugInformations.Add (state_machine); } if (function.synchronizationInformation != null) { var async_debug_info = new AsyncMethodBodyDebugInformation ((int) function.synchronizationInformation.GeneratedCatchHandlerOffset); foreach (var synchronization_point in function.synchronizationInformation.synchronizationPoints) { async_debug_info.Yields.Add (new InstructionOffset ((int) synchronization_point.SynchronizeOffset)); async_debug_info.Resumes.Add (new InstructionOffset ((int) synchronization_point.ContinuationOffset)); async_debug_info.ResumeMethods.Add (method); } symbol.CustomDebugInformations.Add (async_debug_info); symbol.StateMachineKickOffMethod = (MethodDefinition) method.Module.LookupToken ((int) function.synchronizationInformation.kickoffMethodToken); } return symbol; } Collection<ScopeDebugInformation> ReadScopeAndLocals (PdbScope [] scopes, MethodDebugInformation info) { var symbols = new Collection<ScopeDebugInformation> (scopes.Length); foreach (PdbScope scope in scopes) if (scope != null) symbols.Add (ReadScopeAndLocals (scope, info)); return symbols; } ScopeDebugInformation ReadScopeAndLocals (PdbScope scope, MethodDebugInformation info) { var parent = new ScopeDebugInformation (); parent.Start = new InstructionOffset ((int) scope.offset); parent.End = new InstructionOffset ((int) (scope.offset + scope.length)); if (!scope.slots.IsNullOrEmpty ()) { parent.variables = new Collection<VariableDebugInformation> (scope.slots.Length); foreach (PdbSlot slot in scope.slots) { if ((slot.flags & 1) != 0) // parameter names continue; var index = (int) slot.slot; var variable = new VariableDebugInformation (index, slot.name); if ((slot.flags & 4) != 0) variable.IsDebuggerHidden = true; parent.variables.Add (variable); } } if (!scope.constants.IsNullOrEmpty ()) { parent.constants = new Collection<ConstantDebugInformation> (scope.constants.Length); foreach (var constant in scope.constants) { var type = info.Method.Module.Read (constant, (c, r) => r.ReadConstantSignature (new MetadataToken (c.token))); var value = constant.value; // Object "null" is encoded as integer if (type != null && !type.IsValueType && value is int && (int) value == 0) value = null; parent.constants.Add (new ConstantDebugInformation (constant.name, type, value)); } } if (!scope.usedNamespaces.IsNullOrEmpty ()) { ImportDebugInformation import; if (imports.TryGetValue (scope, out import)) { parent.import = import; } else { import = GetImport (scope, info.Method.Module); imports.Add (scope, import); parent.import = import; } } parent.scopes = ReadScopeAndLocals (scope.scopes, info); return parent; } static bool AddScope (Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope) { foreach (var sub_scope in scopes) { if (sub_scope.HasScopes && AddScope (sub_scope.Scopes, scope)) return true; if (scope.Start.Offset >= sub_scope.Start.Offset && scope.End.Offset <= sub_scope.End.Offset) { sub_scope.Scopes.Add (scope); return true; } } return false; } ImportDebugInformation GetImport (uint token, ModuleDefinition module) { PdbFunction function; if (!functions.TryGetValue (token, out function)) return null; if (function.scopes.Length != 1) return null; var scope = function.scopes [0]; ImportDebugInformation import; if (imports.TryGetValue (scope, out import)) return import; import = GetImport (scope, module); imports.Add (scope, import); return import; } static ImportDebugInformation GetImport (PdbScope scope, ModuleDefinition module) { if (scope.usedNamespaces.IsNullOrEmpty ()) return null; var import = new ImportDebugInformation (); foreach (var used_namespace in scope.usedNamespaces) { if (string.IsNullOrEmpty (used_namespace)) continue; ImportTarget target = null; var value = used_namespace.Substring (1); switch (used_namespace [0]) { case 'U': target = new ImportTarget (ImportTargetKind.ImportNamespace) { @namespace = value }; break; case 'T': { var type = TypeParser.ParseType (module, value); if (type != null) target = new ImportTarget (ImportTargetKind.ImportType) { type = type }; break; } case 'A': var index = used_namespace.IndexOf (' '); if (index < 0) { target = new ImportTarget (ImportTargetKind.ImportNamespace) { @namespace = used_namespace }; break; } var alias_value = used_namespace.Substring (1, index - 1); var alias_target_value = used_namespace.Substring (index + 2); switch (used_namespace [index + 1]) { case 'U': target = new ImportTarget (ImportTargetKind.DefineNamespaceAlias) { alias = alias_value, @namespace = alias_target_value }; break; case 'T': var type = TypeParser.ParseType (module, alias_target_value); if (type != null) target = new ImportTarget (ImportTargetKind.DefineTypeAlias) { alias = alias_value, type = type }; break; } break; case '*': target = new ImportTarget (ImportTargetKind.ImportNamespace) { @namespace = value }; break; case '@': if (!value.StartsWith ("P:")) continue; target = new ImportTarget (ImportTargetKind.ImportNamespace) { @namespace = value.Substring (2) }; break; } if (target != null) import.Targets.Add (target); } return import; } void ReadSequencePoints (PdbFunction function, MethodDebugInformation info) { if (function.lines == null) return; info.sequence_points = new Collection<SequencePoint> (); foreach (PdbLines lines in function.lines) ReadLines (lines, info); } void ReadLines (PdbLines lines, MethodDebugInformation info) { var document = GetDocument (lines.file); foreach (var line in lines.lines) ReadLine (line, document, info); } static void ReadLine (PdbLine line, Document document, MethodDebugInformation info) { var sequence_point = new SequencePoint ((int) line.offset, document); sequence_point.StartLine = (int) line.lineBegin; sequence_point.StartColumn = (int) line.colBegin; sequence_point.EndLine = (int) line.lineEnd; sequence_point.EndColumn = (int) line.colEnd; info.sequence_points.Add (sequence_point); } Document GetDocument (PdbSource source) { string name = source.name; Document document; if (documents.TryGetValue (name, out document)) return document; document = new Document (name) { LanguageGuid = source.language, LanguageVendorGuid = source.vendor, TypeGuid = source.doctype, HashAlgorithmGuid = source.checksumAlgorithm, Hash = source.checksum, }; documents.Add (name, document); return document; } public void Dispose () { pdb_file.Dispose (); } } }
using System; using System.Globalization; /// <summary> /// System.Globalization.TextInfo.Equals(Object) /// </summary> public class TextInfoEquals { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; public static int Main() { TextInfoEquals testObj = new TextInfoEquals(); TestLibrary.TestFramework.BeginTestCase("for Method:System.Globalization.TextInfo.Equals(Object)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region PositiveTesting public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Verify same culture TextInfo equals original TextInfo. "; const string c_TEST_ID = "P001"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); CultureInfo ci = new CultureInfo("en-US"); CultureInfo ci2 = new CultureInfo("en-US"); object textInfo = ci2.TextInfo; try { if (!ci.TextInfo.Equals(textInfo)) { string errorDesc = "the second TextInfo should equal original TextInfo."; 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); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Verify the TextInfo is not same CultureInfo's . "; const string c_TEST_ID = "P002"; TextInfo textInfoFrance = new CultureInfo("fr-FR").TextInfo; TextInfo textInfoUS = new CultureInfo("en-US").TextInfo; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (textInfoFrance.Equals((object)textInfoUS)) { string errorDesc = "the TextInfos of differente CultureInfo should not equal. "; 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); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Verify the TextInfo not equal a null reference . "; const string c_TEST_ID = "P003"; TextInfo textInfoUS = new CultureInfo("en-US").TextInfo; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (textInfoUS.Equals(null)) { string errorDesc = "the US CultureInfo's TextInfo should not equal a null reference. "; 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); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Verify the TextInfo not equal another type object . "; const string c_TEST_ID = "P004"; TextInfo textInfoUS = new CultureInfo("en-US").TextInfo; object obj = (object)(new MyClass()); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (textInfoUS.Equals(obj)) { string errorDesc = "the US CultureInfo's TextInfo should not equal user-defined type object. "; 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); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_DESC = "PosTest5: Verify the TextInfo not equal a int object . "; const string c_TEST_ID = "P005"; TextInfo textInfoUS = new CultureInfo("en-US").TextInfo; int i = TestLibrary.Generator.GetInt32(-55); object intObject = i as object; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (textInfoUS.Equals(intObject)) { string errorDesc = "the US CultureInfo's TextInfo should not equal int object. "; 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); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; const string c_TEST_DESC = "PosTest6: Verify the TextInfo not equal a string object . "; const string c_TEST_ID = "P006"; TextInfo textInfoUS = new CultureInfo("en-US").TextInfo; String str = TestLibrary.Generator.GetString(-55, false,c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH); object strObject = str as object; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (textInfoUS.Equals(strObject)) { string errorDesc = "the US CultureInfo's TextInfo should not equal string object. "; 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); retVal = false; } return retVal; } #endregion #region Customer Class public class MyClass { } #endregion }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Shouldly; using Xunit; namespace AutoMapper.UnitTests.InterfaceMapping { public class GenericsAndInterfaces : AutoMapperSpecBase { MyClass<ContainerClass> source = new MyClass<ContainerClass> { Container = new ContainerClass { MyProperty = 3 } }; public interface IMyInterface<T> { T Container { get; set; } } public class ContainerClass { public int MyProperty { get; set; } } public class ImplementedClass : IMyInterface<ContainerClass> { public ContainerClass Container { get; set; } } public class MyClass<T> { public T Container { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMap(typeof(MyClass<>), typeof(IMyInterface<>))); [Fact] public void ShouldMapToExistingObject() { var destination = new ImplementedClass(); Mapper.Map(source, destination, typeof(MyClass<ContainerClass>), typeof(IMyInterface<ContainerClass>)); destination.Container.MyProperty.ShouldBe(3); } [Fact] public void ShouldMapToNewObject() { var destination = (IMyInterface<ContainerClass>) Mapper.Map(source, typeof(MyClass<ContainerClass>), typeof(IMyInterface<ContainerClass>)); destination.Container.MyProperty.ShouldBe(3); } } public class When_mapping_generic_interface : AutoMapperSpecBase { public class Source<T> : List<T> { public String PropertyToMap { get; set; } public String PropertyToIgnore { get; set; } = "I am not ignored"; } public class Destination : DestinationBase<String> { } public abstract class DestinationBase<T> : DestinationBaseBase, IDestinationBase<T> { private String m_PropertyToIgnore; public virtual String PropertyToMap { get; set; } [IgnoreMap] public override String PropertyToIgnore { get { return m_PropertyToIgnore ?? (m_PropertyToIgnore = "Ignore me"); } set { m_PropertyToIgnore = value; } } public virtual List<T> Items { get; set; } } public abstract class DestinationBaseBase { [IgnoreMap] public virtual String PropertyToIgnore { get; set; } } public interface IDestinationBase<T> { String PropertyToMap { get; set; } List<T> Items { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg=> cfg.CreateMap(typeof(IList<>), typeof(IDestinationBase<>)) .ForMember(nameof(IDestinationBase<Object>.Items), p_Expression => p_Expression.MapFrom(p_Source => p_Source)) .ForMember("PropertyToMap", o=>o.Ignore())); [Fact] public void Should_work() { var source = new Source<String>{"Cat", "Dog"}; source.PropertyToMap = "Hello World"; var destination = Mapper.Map<IDestinationBase<string>>(source); destination.PropertyToMap.ShouldBeNull(); destination.Items.ShouldBe(source); } } public class When_mapping_an_interface_with_getter_only_member : AutoMapperSpecBase { interface ISource { int Id { get; set; } } public interface IDestination { int Id { get; set; } int ReadOnly { get; } } class Source : ISource { public int Id { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(c=>c.CreateMap<ISource, IDestination>()); [Fact] public void ShouldMapOk() { Mapper.Map<IDestination>(new Source { Id = 5 }).Id.ShouldBe(5); } } public class When_mapping_base_interface_members { public interface ISource { int Id { get; set; } } public interface ITarget : ITargetBase { int Id { get; set; } } public interface ITargetBase { int BaseId { get; set; } } [Fact] public void Should_find_inherited_members_by_name() { new MapperConfiguration(c=>c.CreateMap<ISource, ITarget>().ForMember("BaseId", opt => opt.Ignore())); } } public class When_mapping_to_existing_object_through_interfaces : AutoMapperSpecBase { private class2DTO _result; public class class1 : iclass1 { public string prop1 { get; set; } } public class class2 : class1, iclass2 { public string prop2 { get; set; } } public class class1DTO : iclass1DTO { public string prop1 { get; set; } } public class class2DTO : class1DTO, iclass2DTO { public string prop2 { get; set; } } public interface iclass1 { string prop1 { get; set; } } public interface iclass2 { string prop2 { get; set; } } public interface iclass1DTO { string prop1 { get; set; } } public interface iclass2DTO { string prop2 { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<iclass1, iclass1DTO>(); cfg.CreateMap<iclass2, iclass2DTO>(); }); protected override void Because_of() { var bo = new class2 { prop1 = "PROP1", prop2 = "PROP2" }; _result = Mapper.Map(bo, new class2DTO()); } [Fact] public void Should_use_the_most_derived_interface() { _result.prop2.ShouldBe("PROP2"); } } public class When_mapping_an_interface_to_an_abstract_type : AutoMapperSpecBase { private DtoObject _result; public class ModelObject { public IChildModelObject Child { get; set; } } public interface IChildModelObject { string ChildProperty { get; set; } } public class SubChildModelObject : IChildModelObject { public string ChildProperty { get; set; } } public class DtoObject { public DtoChildObject Child { get; set; } } public abstract class DtoChildObject { public virtual string ChildProperty { get; set; } } public class SubDtoChildObject : DtoChildObject { } protected override void Because_of() { var model = new ModelObject { Child = new SubChildModelObject {ChildProperty = "child property value"} }; _result = Mapper.Map<ModelObject, DtoObject>(model); } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<ModelObject, DtoObject>(); cfg.CreateMap<IChildModelObject, DtoChildObject>() .Include<SubChildModelObject, SubDtoChildObject>(); cfg.CreateMap<SubChildModelObject, SubDtoChildObject>(); }); [Fact] public void Should_map_Child_to_SubDtoChildObject_type() { _result.Child.ShouldBeOfType(typeof (SubDtoChildObject)); } [Fact] public void Should_map_ChildProperty_to_child_property_value() { _result.Child.ChildProperty.ShouldBe("child property value"); } } public class When_mapping_a_concrete_type_to_an_interface_type : AutoMapperSpecBase { private IDestination _result; public class Source { public int Value { get; set; } } public interface IDestination { int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, IDestination>(); }); protected override void Because_of() { _result = Mapper.Map<Source, IDestination>(new Source {Value = 5}); } [Fact] public void Should_create_an_implementation_of_the_interface() { _result.Value.ShouldBe(5); } [Fact] public void Should_not_derive_from_INotifyPropertyChanged() { _result.ShouldNotBeOfType<INotifyPropertyChanged>(); } } public class When_mapping_a_concrete_type_to_an_interface_type_that_derives_from_INotifyPropertyChanged : AutoMapperSpecBase { private IDestination _result; private int _count; public class Source { public int Value { get; set; } } public interface IDestination : INotifyPropertyChanged { int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, IDestination>(); }); protected override void Because_of() { _result = Mapper.Map<Source, IDestination>(new Source {Value = 5}); } [Fact] public void Should_create_an_implementation_of_the_interface() { _result.Value.ShouldBe(5); } [Fact] public void Should_derive_from_INotifyPropertyChanged() { var q = _result as INotifyPropertyChanged; q.ShouldNotBeNull(); } [Fact] public void Should_notify_property_changes() { var count = 0; _result.PropertyChanged += (o, e) => { count++; o.ShouldBeSameAs(_result); e.PropertyName.ShouldBe("Value"); }; _result.Value = 42; count.ShouldBe(1); _result.Value.ShouldBe(42); } [Fact] public void Should_detach_event_handler() { _result.PropertyChanged += MyHandler; _count.ShouldBe(0); _result.Value = 56; _count.ShouldBe(1); _result.PropertyChanged -= MyHandler; _count.ShouldBe(1); _result.Value = 75; _count.ShouldBe(1); } private void MyHandler(object sender, PropertyChangedEventArgs e) { _count++; } } public class When_mapping_a_derived_interface_to_an_derived_concrete_type : AutoMapperSpecBase { private Destination _result = null; public interface ISourceBase { int Id { get; } } public interface ISource : ISourceBase { int SecondId { get; } } public class Source : ISource { public int Id { get; set; } public int SecondId { get; set; } } public abstract class DestinationBase { public int Id { get; set; } } public class Destination : DestinationBase { public int SecondId { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<ISource, Destination>(); }); protected override void Because_of() { _result = Mapper.Map<ISource, Destination>(new Source {Id = 7, SecondId = 42}); } [Fact] public void Should_map_base_interface_property() { _result.Id.ShouldBe(7); } [Fact] public void Should_map_derived_interface_property() { _result.SecondId.ShouldBe(42); } [Fact] public void Should_pass_configuration_testing() { Configuration.AssertConfigurationIsValid(); } } public class When_mapping_a_derived_interface_to_an_derived_concrete_type_with_readonly_interface_members : AutoMapperSpecBase { private Destination _result = null; public interface ISourceBase { int Id { get; } } public interface ISource : ISourceBase { int SecondId { get; } } public class Source : ISource { public int Id { get; set; } public int SecondId { get; set; } } public interface IDestinationBase { int Id { get; } } public interface IDestination : IDestinationBase { int SecondId { get; } } public abstract class DestinationBase : IDestinationBase { public int Id { get; set; } } public class Destination : DestinationBase, IDestination { public int SecondId { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<ISource, Destination>(); }); protected override void Because_of() { _result = Mapper.Map<ISource, Destination>(new Source {Id = 7, SecondId = 42}); } [Fact] public void Should_map_base_interface_property() { _result.Id.ShouldBe(7); } [Fact] public void Should_map_derived_interface_property() { _result.SecondId.ShouldBe(42); } [Fact] public void Should_pass_configuration_testing() { Configuration.AssertConfigurationIsValid(); } } public class When_mapping_to_a_type_with_explicitly_implemented_interface_members : AutoMapperSpecBase { private Destination _destination; public class Source { public int Value { get; set; } } public interface IOtherDestination { int OtherValue { get; set; } } public class Destination : IOtherDestination { public int Value { get; set; } int IOtherDestination.OtherValue { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source {Value = 10}); } [Fact] public void Should_ignore_interface_members_for_mapping() { _destination.Value.ShouldBe(10); } [Fact] public void Should_ignore_interface_members_for_validation() { Configuration.AssertConfigurationIsValid(); } } public class MappingToInterfacesWithPolymorphism : AutoMapperSpecBase { private BaseDto[] _baseDtos; public interface IBase { } public interface IDerived : IBase { } public class Base : IBase { } public class Derived : Base, IDerived { } public class BaseDto { } public class DerivedDto : BaseDto { } //and following mappings: protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Base, BaseDto>().Include<Derived, DerivedDto>(); cfg.CreateMap<Derived, DerivedDto>(); cfg.CreateMap<IBase, BaseDto>().Include<IDerived, DerivedDto>(); cfg.CreateMap<IDerived, DerivedDto>(); }); protected override void Because_of() { List<Base> list = new List<Base>() { new Derived() }; _baseDtos = Mapper.Map<IEnumerable<Base>, BaseDto[]>(list); } [Fact] public void Should_use_the_derived_type_map() { _baseDtos.First().ShouldBeOfType<DerivedDto>(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Web; using NServiceKit.Common; using NServiceKit.Common.Extensions; using NServiceKit.Common.Utils; using NServiceKit.Common.Web; using NServiceKit.Logging; using NServiceKit.ServiceHost; using NServiceKit.Text; using NServiceKit.WebHost.Endpoints.Support; namespace NServiceKit.WebHost.Endpoints.Extensions { /** * Input: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?q=item#fragment Some HttpRequest path and URL properties: Request.ApplicationPath: /Cambia3 Request.CurrentExecutionFilePath: /Cambia3/Temp/Test.aspx Request.FilePath: /Cambia3/Temp/Test.aspx Request.Path: /Cambia3/Temp/Test.aspx/path/info Request.PathInfo: /path/info Request.PhysicalApplicationPath: D:\Inetpub\wwwroot\CambiaWeb\Cambia3\ Request.QueryString: /Cambia3/Temp/Test.aspx/path/info?query=arg Request.Url.AbsolutePath: /Cambia3/Temp/Test.aspx/path/info Request.Url.AbsoluteUri: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?query=arg Request.Url.Fragment: Request.Url.Host: localhost Request.Url.LocalPath: /Cambia3/Temp/Test.aspx/path/info Request.Url.PathAndQuery: /Cambia3/Temp/Test.aspx/path/info?query=arg Request.Url.Port: 96 Request.Url.Query: ?query=arg Request.Url.Scheme: http Request.Url.Segments: / Cambia3/ Temp/ Test.aspx/ path/ info * */ /// <summary>A HTTP request extensions.</summary> public static class HttpRequestExtensions { private static readonly ILog Log = LogManager.GetLogger(typeof(HttpRequestExtensions)); private static string WebHostDirectoryName = ""; static HttpRequestExtensions() { WebHostDirectoryName = Path.GetFileName("~".MapHostAbsolutePath()); } /// <summary>A HttpListenerRequest extension method that gets operation name.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The operation name.</returns> public static string GetOperationName(this HttpRequest request) { var pathInfo = request.GetLastPathInfo(); return GetOperationNameFromLastPathInfo(pathInfo); } /// <summary>Gets operation name from last path information.</summary> /// /// <param name="lastPathInfo">Information describing the last path.</param> /// /// <returns>The operation name from last path information.</returns> public static string GetOperationNameFromLastPathInfo(string lastPathInfo) { if (String.IsNullOrEmpty(lastPathInfo)) return null; var operationName = lastPathInfo.Substring("/".Length); return operationName; } private static string GetLastPathInfoFromRawUrl(string rawUrl) { var pathInfo = rawUrl.IndexOf("?") != -1 ? rawUrl.Substring(0, rawUrl.IndexOf("?")) : rawUrl; pathInfo = pathInfo.Substring(pathInfo.LastIndexOf("/")); return pathInfo; } /// <summary>A HttpListenerRequest extension method that gets the last path information.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The last path information.</returns> public static string GetLastPathInfo(this HttpRequest request) { var pathInfo = request.PathInfo; if (String.IsNullOrEmpty(pathInfo)) { pathInfo = GetLastPathInfoFromRawUrl(request.RawUrl); } //Log.DebugFormat("Request.PathInfo: {0}, Request.RawUrl: {1}, pathInfo:{2}", // request.PathInfo, request.RawUrl, pathInfo); return pathInfo; } /// <summary>A HttpRequest extension method that gets URL host name.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The URL host name.</returns> public static string GetUrlHostName(this HttpRequest request) { //TODO: Fix bug in mono fastcgi, when trying to get 'Request.Url.Host' try { return request.Url.Host; } catch (Exception ex) { Log.ErrorFormat("Error trying to get 'Request.Url.Host'", ex); return request.UserHostName; } } /// <summary> /// http://localhost/NServiceKit.Examples.Host.Web/Public/Public/Soap12/Wsdl => /// http://localhost/NServiceKit.Examples.Host.Web/Public/Soap12/. /// </summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The parent base URL.</returns> public static string GetParentBaseUrl(this HttpRequest request) { var rawUrl = request.RawUrl; // /Cambia3/Temp/Test.aspx/path/info var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1); // /Cambia3/Temp/Test.aspx/path return GetAuthority(request) + endpointsPath; } /// <summary>An IHttpRequest extension method that gets the parent base URL.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The parent base URL.</returns> public static string GetParentBaseUrl(this IHttpRequest request){ var rawUrl = request.RawUrl; var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1); return new Uri(request.AbsoluteUri).GetLeftPart(UriPartial.Authority) + endpointsPath; } /// <summary>An IHttpRequest extension method that gets base URL.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The base URL.</returns> public static string GetBaseUrl(this HttpRequest request) { return GetAuthority(request) + request.RawUrl; } //=> http://localhost:96 ?? ex=> http://localhost private static string GetAuthority(HttpRequest request) { try { return request.Url.GetLeftPart(UriPartial.Authority); } catch (Exception ex) { Log.Error("Error trying to get: request.Url.GetLeftPart(UriPartial.Authority): " + ex.Message, ex); return "http://" + request.UserHostName; } } /// <summary>A HttpListenerRequest extension method that gets operation name.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The operation name.</returns> public static string GetOperationName(this HttpListenerRequest request) { return request.Url.Segments[request.Url.Segments.Length - 1]; } /// <summary>A HttpListenerRequest extension method that gets the last path information.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The last path information.</returns> public static string GetLastPathInfo(this HttpListenerRequest request) { return GetLastPathInfoFromRawUrl(request.RawUrl); } /// <summary>Gets path information.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The path information.</returns> public static string GetPathInfo(this HttpRequest request) { if (!String.IsNullOrEmpty(request.PathInfo)) return request.PathInfo.TrimEnd('/'); var mode = EndpointHost.Config.NServiceKitHandlerFactoryPath; var appPath = String.IsNullOrEmpty(request.ApplicationPath) ? WebHostDirectoryName : request.ApplicationPath.TrimStart('/'); //mod_mono: /CustomPath35/api//default.htm var path = Env.IsMono ? request.Path.Replace("//", "/") : request.Path; return GetPathInfo(path, mode, appPath); } /// <summary>Gets path information.</summary> /// /// <param name="fullPath">Full pathname of the full file.</param> /// <param name="mode"> The mode.</param> /// <param name="appPath"> Full pathname of the application file.</param> /// /// <returns>The path information.</returns> public static string GetPathInfo(string fullPath, string mode, string appPath) { var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode); if (!String.IsNullOrEmpty(pathInfo)) return pathInfo; //Wildcard mode relies on this to work out the handlerPath pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath); if (!String.IsNullOrEmpty(pathInfo)) return pathInfo; return fullPath; } /// <summary>Resolve path information from mapped path.</summary> /// /// <param name="fullPath"> Full pathname of the full file.</param> /// <param name="mappedPathRoot">The mapped path root.</param> /// /// <returns>A string.</returns> public static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot) { if (mappedPathRoot == null) return null; var sbPathInfo = new StringBuilder(); var fullPathParts = fullPath.Split('/'); var mappedPathRootParts = mappedPathRoot.Split('/'); var fullPathIndexOffset = mappedPathRootParts.Length - 1; var pathRootFound = false; for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++) { if (pathRootFound) { sbPathInfo.Append("/" + fullPathParts[fullPathIndex]); } else if (fullPathIndex - fullPathIndexOffset >= 0) { pathRootFound = true; for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++) { if (!String.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.InvariantCultureIgnoreCase)) { pathRootFound = false; break; } } } } if (!pathRootFound) return null; var path = sbPathInfo.ToString(); return path.Length > 1 ? path.TrimEnd('/') : "/"; } /// <summary>An IHttpRequest extension method that query if 'request' is content type.</summary> /// /// <param name="request"> The request to act on.</param> /// <param name="contentType">Type of the content.</param> /// /// <returns>true if content type, false if not.</returns> public static bool IsContentType(this IHttpRequest request, string contentType) { return request.ContentType.StartsWith(contentType, StringComparison.InvariantCultureIgnoreCase); } /// <summary>An IHttpRequest extension method that query if 'request' has any of content types.</summary> /// /// <param name="request"> The request to act on.</param> /// <param name="contentTypes">List of types of the contents.</param> /// /// <returns>true if any of content types, false if not.</returns> public static bool HasAnyOfContentTypes(this IHttpRequest request, params string[] contentTypes) { if (contentTypes == null || request.ContentType == null) return false; foreach (var contentType in contentTypes) { if (IsContentType(request, contentType)) return true; } return false; } /// <summary>A HttpListenerRequest extension method that gets HTTP request.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The HTTP request.</returns> public static IHttpRequest GetHttpRequest(this HttpRequest request) { return new HttpRequestWrapper(null, request); } /// <summary>A HttpListenerRequest extension method that gets HTTP request.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The HTTP request.</returns> public static IHttpRequest GetHttpRequest(this HttpListenerRequest request) { return new HttpListenerRequestWrapper(null, request); } /// <summary>An IHttpRequest extension method that gets request parameters.</summary> /// /// <param name="request">The request to act on.</param> /// /// <returns>The request parameters.</returns> public static Dictionary<string, string> GetRequestParams(this IHttpRequest request) { var map = new Dictionary<string, string>(); foreach (var name in request.QueryString.AllKeys) { if (name == null) continue; //thank you ASP.NET map[name] = request.QueryString[name]; } if ((request.HttpMethod == HttpMethods.Post || request.HttpMethod == HttpMethods.Put) && request.FormData != null) { foreach (var name in request.FormData.AllKeys) { if (name == null) continue; //thank you ASP.NET map[name] = request.FormData[name]; } } return map; } /// <summary>An IHttpRequest extension method that gets query string content type.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The query string content type.</returns> public static string GetQueryStringContentType(this IHttpRequest httpReq) { var callback = httpReq.QueryString["callback"]; if (!String.IsNullOrEmpty(callback)) return ContentType.Json; var format = httpReq.QueryString["format"]; if (format == null) { const int formatMaxLength = 4; var pi = httpReq.PathInfo; if (pi == null || pi.Length <= formatMaxLength) return null; if (pi[0] == '/') pi = pi.Substring(1); format = pi.SplitOnFirst('/')[0]; if (format.Length > formatMaxLength) return null; } format = format.SplitOnFirst('.')[0].ToLower(); if (format.Contains("json")) return ContentType.Json; if (format.Contains("xml")) return ContentType.Xml; if (format.Contains("jsv")) return ContentType.Jsv; string contentType; EndpointHost.ContentTypeFilter.ContentTypeFormats.TryGetValue(format, out contentType); return contentType; } /// <summary>List of types of the preferred contents.</summary> public static string[] PreferredContentTypes = new[] { ContentType.Html, ContentType.Json, ContentType.Xml, ContentType.Jsv }; /// <summary> /// Use this to treat Request.Items[] as a cache by returning pre-computed items to save /// calculating them multiple times. /// </summary> public static object ResolveItem(this IHttpRequest httpReq, string itemKey, Func<IHttpRequest, object> resolveFn) { object cachedItem; if (httpReq.Items.TryGetValue(itemKey, out cachedItem)) return cachedItem; var item = resolveFn(httpReq); httpReq.Items[itemKey] = item; return item; } /// <summary>An IHttpRequest extension method that gets response content type.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The response content type.</returns> public static string GetResponseContentType(this IHttpRequest httpReq) { var specifiedContentType = GetQueryStringContentType(httpReq); if (!String.IsNullOrEmpty(specifiedContentType)) return specifiedContentType; var acceptContentTypes = httpReq.AcceptTypes; var defaultContentType = httpReq.ContentType; if (httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData)) { defaultContentType = EndpointHost.Config.DefaultContentType; } var customContentTypes = EndpointHost.ContentTypeFilter.ContentTypeFormats.Values; var acceptsAnything = false; var hasDefaultContentType = !String.IsNullOrEmpty(defaultContentType); if (acceptContentTypes != null) { var hasPreferredContentTypes = new bool[PreferredContentTypes.Length]; foreach (var contentType in acceptContentTypes) { acceptsAnything = acceptsAnything || contentType == "*/*"; for (var i = 0; i < PreferredContentTypes.Length; i++) { if (hasPreferredContentTypes[i]) continue; var preferredContentType = PreferredContentTypes[i]; hasPreferredContentTypes[i] = contentType.StartsWith(preferredContentType); //Prefer Request.ContentType if it is also a preferredContentType if (hasPreferredContentTypes[i] && preferredContentType == defaultContentType) return preferredContentType; } } for (var i = 0; i < PreferredContentTypes.Length; i++) { if (hasPreferredContentTypes[i]) return PreferredContentTypes[i]; } if (acceptsAnything && hasDefaultContentType) return defaultContentType; foreach (var contentType in acceptContentTypes) { foreach (var customContentType in customContentTypes) { if (contentType.StartsWith(customContentType)) return customContentType; } } } //We could also send a '406 Not Acceptable', but this is allowed also return EndpointHost.Config.DefaultContentType; } /// <summary>An IHttpRequest extension method that sets a view.</summary> /// /// <param name="httpReq"> The httpReq to act on.</param> /// <param name="viewName">Name of the view.</param> public static void SetView(this IHttpRequest httpReq, string viewName) { httpReq.SetItem("View", viewName); } /// <summary>An IHttpRequest extension method that gets a view.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The view.</returns> public static string GetView(this IHttpRequest httpReq) { return httpReq.GetItem("View") as string; } /// <summary>An IHttpRequest extension method that sets a template.</summary> /// /// <param name="httpReq"> The httpReq to act on.</param> /// <param name="templateName">Name of the template.</param> public static void SetTemplate(this IHttpRequest httpReq, string templateName) { httpReq.SetItem("Template", templateName); } /// <summary>An IHttpRequest extension method that gets a template.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The template.</returns> public static string GetTemplate(this IHttpRequest httpReq) { return httpReq.GetItem("Template") as string; } /// <summary>An IHttpRequest extension method that resolve absolute URL.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// <param name="url"> URL of the document.</param> /// /// <returns>A string.</returns> public static string ResolveAbsoluteUrl(this IHttpRequest httpReq, string url) { return EndpointHost.AppHost.ResolveAbsoluteUrl(url, httpReq); } /// <summary>An IHttpRequest extension method that resolve base URL.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>A string.</returns> public static string ResolveBaseUrl(this IHttpRequest httpReq) { return EndpointHost.AppHost.ResolveAbsoluteUrl("~/", httpReq); } /// <summary>An IHttpRequest extension method that gets absolute URL.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// <param name="url"> URL of the document.</param> /// /// <returns>The absolute URL.</returns> public static string GetAbsoluteUrl(this IHttpRequest httpReq, string url) { if (url.SafeSubstring(0, 2) == "~/") { url = httpReq.GetBaseUrl().CombineWith(url.Substring(2)); } return url; } /// <summary>An IHttpRequest extension method that gets base URL.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The base URL.</returns> public static string GetBaseUrl(this IHttpRequest httpReq) { var baseUrl = NServiceKitHttpHandlerFactory.GetBaseUrl(); if (baseUrl != null) return baseUrl; var handlerPath = EndpointHost.Config.NServiceKitHandlerFactoryPath; if (handlerPath != null) { var pos = httpReq.AbsoluteUri.IndexOf(handlerPath, StringComparison.InvariantCultureIgnoreCase); if (pos >= 0) { baseUrl = httpReq.AbsoluteUri.Substring(0, pos + handlerPath.Length); return baseUrl; } return "/" + handlerPath; } return "/"; //Can't infer Absolute Uri, fallback to root relative path } /// <summary>Converts the attrNames to an endpoint attributes.</summary> /// /// <param name="attrNames">List of names of the attributes.</param> /// /// <returns>attrNames as the EndpointAttributes.</returns> public static EndpointAttributes ToEndpointAttributes(string[] attrNames) { var attrs = EndpointAttributes.None; foreach (var simulatedAttr in attrNames) { var attr = (EndpointAttributes)Enum.Parse(typeof(EndpointAttributes), simulatedAttr, true); attrs |= attr; } return attrs; } /// <summary>Gets the attributes.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="request">The request to act on.</param> /// /// <returns>The attributes.</returns> public static EndpointAttributes GetAttributes(this IHttpRequest request) { if (EndpointHost.DebugMode && request.QueryString != null) //Mock<IHttpRequest> { var simulate = request.QueryString["simulate"]; if (simulate != null) { return ToEndpointAttributes(simulate.Split(',')); } } var portRestrictions = EndpointAttributes.None; portRestrictions |= HttpMethods.GetEndpointAttribute(request.HttpMethod); portRestrictions |= request.IsSecureConnection ? EndpointAttributes.Secure : EndpointAttributes.InSecure; if (request.UserHostAddress != null) { var isIpv4Address = request.UserHostAddress.IndexOf('.') != -1 && request.UserHostAddress.IndexOf("::", StringComparison.InvariantCulture) == -1; string ipAddressNumber = null; if (isIpv4Address) { ipAddressNumber = request.UserHostAddress.SplitOnFirst(":")[0]; } else { if (request.UserHostAddress.Contains("]:")) { ipAddressNumber = request.UserHostAddress.SplitOnLast(":")[0]; } else { ipAddressNumber = request.UserHostAddress.LastIndexOf("%", StringComparison.InvariantCulture) > 0 ? request.UserHostAddress.SplitOnLast(":")[0] : request.UserHostAddress; } } try { ipAddressNumber = ipAddressNumber.SplitOnFirst(',')[0]; var ipAddress = ipAddressNumber.StartsWith("::1") ? IPAddress.IPv6Loopback : IPAddress.Parse(ipAddressNumber); portRestrictions |= GetAttributes(ipAddress); } catch (Exception ex) { throw new ArgumentException("Could not parse Ipv{0} Address: {1} / {2}" .Fmt((isIpv4Address ? 4 : 6), request.UserHostAddress, ipAddressNumber), ex); } } return portRestrictions; } /// <summary>Gets the attributes.</summary> /// /// <param name="ipAddress">The IP address.</param> /// /// <returns>The attributes.</returns> public static EndpointAttributes GetAttributes(IPAddress ipAddress) { if (IPAddress.IsLoopback(ipAddress)) return EndpointAttributes.Localhost; return IsInLocalSubnet(ipAddress) ? EndpointAttributes.LocalSubnet : EndpointAttributes.External; } /// <summary>Query if 'ipAddress' is in local subnet.</summary> /// /// <param name="ipAddress">The IP address.</param> /// /// <returns>true if in local subnet, false if not.</returns> public static bool IsInLocalSubnet(IPAddress ipAddress) { var ipAddressBytes = ipAddress.GetAddressBytes(); switch (ipAddress.AddressFamily) { case AddressFamily.InterNetwork: foreach (var localIpv4AddressAndMask in EndpointHandlerBase.NetworkInterfaceIpv4Addresses) { if (ipAddressBytes.IsInSameIpv4Subnet(localIpv4AddressAndMask.Key, localIpv4AddressAndMask.Value)) { return true; } } break; case AddressFamily.InterNetworkV6: foreach (var localIpv6Address in EndpointHandlerBase.NetworkInterfaceIpv6Addresses) { if (ipAddressBytes.IsInSameIpv6Subnet(localIpv6Address)) { return true; } } break; } return false; } /// <summary>A HttpListenerRequest extension method that converts this object to a request.</summary> /// /// <param name="aspnetHttpReq">The aspnetHttpReq to act on.</param> /// <param name="operationName">Name of the operation.</param> /// /// <returns>The given data converted to an IHttpRequest.</returns> public static IHttpRequest ToRequest(this HttpRequest aspnetHttpReq, string operationName=null) { return new HttpRequestWrapper(aspnetHttpReq) { OperationName = operationName, Container = AppHostBase.Instance != null ? AppHostBase.Instance.Container : null }; } /// <summary>A HttpListenerRequest extension method that converts this object to a request.</summary> /// /// <param name="listenerHttpReq">The listenerHttpReq to act on.</param> /// <param name="operationName"> Name of the operation.</param> /// /// <returns>The given data converted to an IHttpRequest.</returns> public static IHttpRequest ToRequest(this HttpListenerRequest listenerHttpReq, string operationName = null) { return new HttpListenerRequestWrapper(listenerHttpReq) { OperationName = operationName, Container = AppHostBase.Instance != null ? AppHostBase.Instance.Container : null }; } /// <summary>A HttpListenerResponse extension method that converts the listenerHttpRes to a response.</summary> /// /// <param name="aspnetHttpRes">The aspnetHttpRes to act on.</param> /// /// <returns>listenerHttpRes as an IHttpResponse.</returns> public static IHttpResponse ToResponse(this HttpResponse aspnetHttpRes) { return new HttpResponseWrapper(aspnetHttpRes); } /// <summary>A HttpListenerResponse extension method that converts the listenerHttpRes to a response.</summary> /// /// <param name="listenerHttpRes">The listenerHttpRes to act on.</param> /// /// <returns>listenerHttpRes as an IHttpResponse.</returns> public static IHttpResponse ToResponse(this HttpListenerResponse listenerHttpRes) { return new HttpListenerResponseWrapper(listenerHttpRes); } /// <summary>An IHttpRequest extension method that sets operation name.</summary> /// /// <param name="httpReq"> The httpReq to act on.</param> /// <param name="operationName">Name of the operation.</param> public static void SetOperationName(this IHttpRequest httpReq, string operationName) { if (httpReq.OperationName == null) { var aspReq = httpReq as HttpRequestWrapper; if (aspReq != null) { aspReq.OperationName = operationName; return; } var listenerReq = httpReq as HttpListenerRequestWrapper; if (listenerReq != null) { listenerReq.OperationName = operationName; } } } /// <summary>An IHttpRequest extension method that gets SOAP message.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The SOAP message.</returns> public static System.ServiceModel.Channels.Message GetSoapMessage(this IHttpRequest httpReq) { return httpReq.Items["SoapMessage"] as System.ServiceModel.Channels.Message; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Network { /// <summary> /// The Network Resource Provider API includes operations for managing the /// PublicIPAddress for your subscription. /// </summary> internal partial class PublicIpAddressOperations : IServiceOperations<NetworkResourceProviderClient>, IPublicIpAddressOperations { /// <summary> /// Initializes a new instance of the PublicIpAddressOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PublicIpAddressOperations(NetworkResourceProviderClient client) { this._client = client; } private NetworkResourceProviderClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Network.NetworkResourceProviderClient. /// </summary> public NetworkResourceProviderClient Client { get { return this._client; } } /// <summary> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update PublicIPAddress /// operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for PutPublicIpAddress Api servive call /// </returns> public async Task<PublicIpAddressPutResponse> BeginCreateOrUpdatingAsync(string resourceGroupName, string publicIpAddressName, PublicIpAddress parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (publicIpAddressName == null) { throw new ArgumentNullException("publicIpAddressName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } if (parameters.PublicIpAllocationMethod == null) { throw new ArgumentNullException("parameters.PublicIpAllocationMethod"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses/"; url = url + Uri.EscapeDataString(publicIpAddressName); url = url + "/"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject publicIpAddressJsonFormatValue = new JObject(); requestDoc = publicIpAddressJsonFormatValue; JObject propertiesValue = new JObject(); publicIpAddressJsonFormatValue["properties"] = propertiesValue; propertiesValue["publicIPAllocationMethod"] = parameters.PublicIpAllocationMethod; if (parameters.IpConfiguration != null) { JObject ipConfigurationValue = new JObject(); propertiesValue["ipConfiguration"] = ipConfigurationValue; if (parameters.IpConfiguration.Id != null) { ipConfigurationValue["id"] = parameters.IpConfiguration.Id; } } if (parameters.DnsSettings != null) { JObject dnsSettingsValue = new JObject(); propertiesValue["dnsSettings"] = dnsSettingsValue; if (parameters.DnsSettings.DomainNameLabel != null) { dnsSettingsValue["domainNameLabel"] = parameters.DnsSettings.DomainNameLabel; } if (parameters.DnsSettings.Fqdn != null) { dnsSettingsValue["fqdn"] = parameters.DnsSettings.Fqdn; } if (parameters.DnsSettings.ReverseFqdn != null) { dnsSettingsValue["reverseFqdn"] = parameters.DnsSettings.ReverseFqdn; } } if (parameters.IpAddress != null) { propertiesValue["ipAddress"] = parameters.IpAddress; } if (parameters.IdleTimeoutInMinutes != null) { propertiesValue["idleTimeoutInMinutes"] = parameters.IdleTimeoutInMinutes.Value; } if (parameters.ResourceGuid != null) { propertiesValue["resourceGuid"] = parameters.ResourceGuid; } if (parameters.ProvisioningState != null) { propertiesValue["provisioningState"] = parameters.ProvisioningState; } if (parameters.Etag != null) { publicIpAddressJsonFormatValue["etag"] = parameters.Etag; } if (parameters.Id != null) { publicIpAddressJsonFormatValue["id"] = parameters.Id; } if (parameters.Name != null) { publicIpAddressJsonFormatValue["name"] = parameters.Name; } if (parameters.Type != null) { publicIpAddressJsonFormatValue["type"] = parameters.Type; } publicIpAddressJsonFormatValue["location"] = parameters.Location; if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } publicIpAddressJsonFormatValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PublicIpAddressPutResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicIpAddressPutResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { PublicIpAddress publicIpAddressInstance = new PublicIpAddress(); result.PublicIpAddress = publicIpAddressInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { JToken publicIPAllocationMethodValue = propertiesValue2["publicIPAllocationMethod"]; if (publicIPAllocationMethodValue != null && publicIPAllocationMethodValue.Type != JTokenType.Null) { string publicIPAllocationMethodInstance = ((string)publicIPAllocationMethodValue); publicIpAddressInstance.PublicIpAllocationMethod = publicIPAllocationMethodInstance; } JToken ipConfigurationValue2 = propertiesValue2["ipConfiguration"]; if (ipConfigurationValue2 != null && ipConfigurationValue2.Type != JTokenType.Null) { ResourceId ipConfigurationInstance = new ResourceId(); publicIpAddressInstance.IpConfiguration = ipConfigurationInstance; JToken idValue = ipConfigurationValue2["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ipConfigurationInstance.Id = idInstance; } } JToken dnsSettingsValue2 = propertiesValue2["dnsSettings"]; if (dnsSettingsValue2 != null && dnsSettingsValue2.Type != JTokenType.Null) { PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings(); publicIpAddressInstance.DnsSettings = dnsSettingsInstance; JToken domainNameLabelValue = dnsSettingsValue2["domainNameLabel"]; if (domainNameLabelValue != null && domainNameLabelValue.Type != JTokenType.Null) { string domainNameLabelInstance = ((string)domainNameLabelValue); dnsSettingsInstance.DomainNameLabel = domainNameLabelInstance; } JToken fqdnValue = dnsSettingsValue2["fqdn"]; if (fqdnValue != null && fqdnValue.Type != JTokenType.Null) { string fqdnInstance = ((string)fqdnValue); dnsSettingsInstance.Fqdn = fqdnInstance; } JToken reverseFqdnValue = dnsSettingsValue2["reverseFqdn"]; if (reverseFqdnValue != null && reverseFqdnValue.Type != JTokenType.Null) { string reverseFqdnInstance = ((string)reverseFqdnValue); dnsSettingsInstance.ReverseFqdn = reverseFqdnInstance; } } JToken ipAddressValue = propertiesValue2["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); publicIpAddressInstance.IpAddress = ipAddressInstance; } JToken idleTimeoutInMinutesValue = propertiesValue2["idleTimeoutInMinutes"]; if (idleTimeoutInMinutesValue != null && idleTimeoutInMinutesValue.Type != JTokenType.Null) { int idleTimeoutInMinutesInstance = ((int)idleTimeoutInMinutesValue); publicIpAddressInstance.IdleTimeoutInMinutes = idleTimeoutInMinutesInstance; } JToken resourceGuidValue = propertiesValue2["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); publicIpAddressInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue2["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); publicIpAddressInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); publicIpAddressInstance.Etag = etagInstance; } JToken idValue2 = responseDoc["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); publicIpAddressInstance.Id = idInstance2; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); publicIpAddressInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); publicIpAddressInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); publicIpAddressInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); publicIpAddressInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { Error errorInstance = new Error(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = errorValue["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JToken detailsArray = errorValue["details"]; if (detailsArray != null && detailsArray.Type != JTokenType.Null) { foreach (JToken detailsValue in ((JArray)detailsArray)) { ErrorDetails errorDetailsInstance = new ErrorDetails(); errorInstance.Details.Add(errorDetailsInstance); JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); errorDetailsInstance.Code = codeInstance2; } JToken targetValue2 = detailsValue["target"]; if (targetValue2 != null && targetValue2.Type != JTokenType.Null) { string targetInstance2 = ((string)targetValue2); errorDetailsInstance.Target = targetInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); errorDetailsInstance.Message = messageInstance2; } } } JToken innerErrorValue = errorValue["innerError"]; if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null) { string innerErrorInstance = ((string)innerErrorValue); errorInstance.InnerError = innerErrorInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The delete publicIpAddress operation deletes the specified /// publicIpAddress. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public async Task<UpdateOperationResponse> BeginDeletingAsync(string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (publicIpAddressName == null) { throw new ArgumentNullException("publicIpAddressName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses/"; url = url + Uri.EscapeDataString(publicIpAddressName); url = url + "/"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UpdateOperationResponse result = null; // Deserialize Response result = new UpdateOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create PublicIPAddress /// operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string publicIpAddressName, PublicIpAddress parameters, CancellationToken cancellationToken) { NetworkResourceProviderClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); PublicIpAddressPutResponse response = await client.PublicIpAddresses.BeginCreateOrUpdatingAsync(resourceGroupName, publicIpAddressName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// The Get Role operation retrieves information about the specified /// virtual machine. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken) { NetworkResourceProviderClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); UpdateOperationResponse response = await client.PublicIpAddresses.BeginDeletingAsync(resourceGroupName, publicIpAddressName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// The Get publicIpAddress operation retreives information about the /// specified pubicIpAddress /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// Required. The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for GetPublicIpAddress Api servive call /// </returns> public async Task<PublicIpAddressGetResponse> GetAsync(string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (publicIpAddressName == null) { throw new ArgumentNullException("publicIpAddressName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses/"; url = url + Uri.EscapeDataString(publicIpAddressName); url = url + "/"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PublicIpAddressGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicIpAddressGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { PublicIpAddress publicIpAddressInstance = new PublicIpAddress(); result.PublicIpAddress = publicIpAddressInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken publicIPAllocationMethodValue = propertiesValue["publicIPAllocationMethod"]; if (publicIPAllocationMethodValue != null && publicIPAllocationMethodValue.Type != JTokenType.Null) { string publicIPAllocationMethodInstance = ((string)publicIPAllocationMethodValue); publicIpAddressInstance.PublicIpAllocationMethod = publicIPAllocationMethodInstance; } JToken ipConfigurationValue = propertiesValue["ipConfiguration"]; if (ipConfigurationValue != null && ipConfigurationValue.Type != JTokenType.Null) { ResourceId ipConfigurationInstance = new ResourceId(); publicIpAddressInstance.IpConfiguration = ipConfigurationInstance; JToken idValue = ipConfigurationValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ipConfigurationInstance.Id = idInstance; } } JToken dnsSettingsValue = propertiesValue["dnsSettings"]; if (dnsSettingsValue != null && dnsSettingsValue.Type != JTokenType.Null) { PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings(); publicIpAddressInstance.DnsSettings = dnsSettingsInstance; JToken domainNameLabelValue = dnsSettingsValue["domainNameLabel"]; if (domainNameLabelValue != null && domainNameLabelValue.Type != JTokenType.Null) { string domainNameLabelInstance = ((string)domainNameLabelValue); dnsSettingsInstance.DomainNameLabel = domainNameLabelInstance; } JToken fqdnValue = dnsSettingsValue["fqdn"]; if (fqdnValue != null && fqdnValue.Type != JTokenType.Null) { string fqdnInstance = ((string)fqdnValue); dnsSettingsInstance.Fqdn = fqdnInstance; } JToken reverseFqdnValue = dnsSettingsValue["reverseFqdn"]; if (reverseFqdnValue != null && reverseFqdnValue.Type != JTokenType.Null) { string reverseFqdnInstance = ((string)reverseFqdnValue); dnsSettingsInstance.ReverseFqdn = reverseFqdnInstance; } } JToken ipAddressValue = propertiesValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); publicIpAddressInstance.IpAddress = ipAddressInstance; } JToken idleTimeoutInMinutesValue = propertiesValue["idleTimeoutInMinutes"]; if (idleTimeoutInMinutesValue != null && idleTimeoutInMinutesValue.Type != JTokenType.Null) { int idleTimeoutInMinutesInstance = ((int)idleTimeoutInMinutesValue); publicIpAddressInstance.IdleTimeoutInMinutes = idleTimeoutInMinutesInstance; } JToken resourceGuidValue = propertiesValue["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); publicIpAddressInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); publicIpAddressInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); publicIpAddressInstance.Etag = etagInstance; } JToken idValue2 = responseDoc["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); publicIpAddressInstance.Id = idInstance2; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); publicIpAddressInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); publicIpAddressInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); publicIpAddressInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); publicIpAddressInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List publicIpAddress opertion retrieves all the /// publicIpAddresses in a resource group. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for ListPublicIpAddresses Api service call /// </returns> public async Task<PublicIpAddressListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PublicIpAddressListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicIpAddressListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { PublicIpAddress publicIpAddressJsonFormatInstance = new PublicIpAddress(); result.PublicIpAddresses.Add(publicIpAddressJsonFormatInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken publicIPAllocationMethodValue = propertiesValue["publicIPAllocationMethod"]; if (publicIPAllocationMethodValue != null && publicIPAllocationMethodValue.Type != JTokenType.Null) { string publicIPAllocationMethodInstance = ((string)publicIPAllocationMethodValue); publicIpAddressJsonFormatInstance.PublicIpAllocationMethod = publicIPAllocationMethodInstance; } JToken ipConfigurationValue = propertiesValue["ipConfiguration"]; if (ipConfigurationValue != null && ipConfigurationValue.Type != JTokenType.Null) { ResourceId ipConfigurationInstance = new ResourceId(); publicIpAddressJsonFormatInstance.IpConfiguration = ipConfigurationInstance; JToken idValue = ipConfigurationValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ipConfigurationInstance.Id = idInstance; } } JToken dnsSettingsValue = propertiesValue["dnsSettings"]; if (dnsSettingsValue != null && dnsSettingsValue.Type != JTokenType.Null) { PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings(); publicIpAddressJsonFormatInstance.DnsSettings = dnsSettingsInstance; JToken domainNameLabelValue = dnsSettingsValue["domainNameLabel"]; if (domainNameLabelValue != null && domainNameLabelValue.Type != JTokenType.Null) { string domainNameLabelInstance = ((string)domainNameLabelValue); dnsSettingsInstance.DomainNameLabel = domainNameLabelInstance; } JToken fqdnValue = dnsSettingsValue["fqdn"]; if (fqdnValue != null && fqdnValue.Type != JTokenType.Null) { string fqdnInstance = ((string)fqdnValue); dnsSettingsInstance.Fqdn = fqdnInstance; } JToken reverseFqdnValue = dnsSettingsValue["reverseFqdn"]; if (reverseFqdnValue != null && reverseFqdnValue.Type != JTokenType.Null) { string reverseFqdnInstance = ((string)reverseFqdnValue); dnsSettingsInstance.ReverseFqdn = reverseFqdnInstance; } } JToken ipAddressValue = propertiesValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); publicIpAddressJsonFormatInstance.IpAddress = ipAddressInstance; } JToken idleTimeoutInMinutesValue = propertiesValue["idleTimeoutInMinutes"]; if (idleTimeoutInMinutesValue != null && idleTimeoutInMinutesValue.Type != JTokenType.Null) { int idleTimeoutInMinutesInstance = ((int)idleTimeoutInMinutesValue); publicIpAddressJsonFormatInstance.IdleTimeoutInMinutes = idleTimeoutInMinutesInstance; } JToken resourceGuidValue = propertiesValue["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); publicIpAddressJsonFormatInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); publicIpAddressJsonFormatInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); publicIpAddressJsonFormatInstance.Etag = etagInstance; } JToken idValue2 = valueValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); publicIpAddressJsonFormatInstance.Id = idInstance2; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); publicIpAddressJsonFormatInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); publicIpAddressJsonFormatInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); publicIpAddressJsonFormatInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); publicIpAddressJsonFormatInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List publicIpAddress opertion retrieves all the /// publicIpAddresses in a subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for ListPublicIpAddresses Api service call /// </returns> public async Task<PublicIpAddressListResponse> ListAllAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAllAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + "Microsoft.Network"; url = url + "/publicIPAddresses"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PublicIpAddressListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicIpAddressListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { PublicIpAddress publicIpAddressJsonFormatInstance = new PublicIpAddress(); result.PublicIpAddresses.Add(publicIpAddressJsonFormatInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JToken publicIPAllocationMethodValue = propertiesValue["publicIPAllocationMethod"]; if (publicIPAllocationMethodValue != null && publicIPAllocationMethodValue.Type != JTokenType.Null) { string publicIPAllocationMethodInstance = ((string)publicIPAllocationMethodValue); publicIpAddressJsonFormatInstance.PublicIpAllocationMethod = publicIPAllocationMethodInstance; } JToken ipConfigurationValue = propertiesValue["ipConfiguration"]; if (ipConfigurationValue != null && ipConfigurationValue.Type != JTokenType.Null) { ResourceId ipConfigurationInstance = new ResourceId(); publicIpAddressJsonFormatInstance.IpConfiguration = ipConfigurationInstance; JToken idValue = ipConfigurationValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ipConfigurationInstance.Id = idInstance; } } JToken dnsSettingsValue = propertiesValue["dnsSettings"]; if (dnsSettingsValue != null && dnsSettingsValue.Type != JTokenType.Null) { PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings(); publicIpAddressJsonFormatInstance.DnsSettings = dnsSettingsInstance; JToken domainNameLabelValue = dnsSettingsValue["domainNameLabel"]; if (domainNameLabelValue != null && domainNameLabelValue.Type != JTokenType.Null) { string domainNameLabelInstance = ((string)domainNameLabelValue); dnsSettingsInstance.DomainNameLabel = domainNameLabelInstance; } JToken fqdnValue = dnsSettingsValue["fqdn"]; if (fqdnValue != null && fqdnValue.Type != JTokenType.Null) { string fqdnInstance = ((string)fqdnValue); dnsSettingsInstance.Fqdn = fqdnInstance; } JToken reverseFqdnValue = dnsSettingsValue["reverseFqdn"]; if (reverseFqdnValue != null && reverseFqdnValue.Type != JTokenType.Null) { string reverseFqdnInstance = ((string)reverseFqdnValue); dnsSettingsInstance.ReverseFqdn = reverseFqdnInstance; } } JToken ipAddressValue = propertiesValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); publicIpAddressJsonFormatInstance.IpAddress = ipAddressInstance; } JToken idleTimeoutInMinutesValue = propertiesValue["idleTimeoutInMinutes"]; if (idleTimeoutInMinutesValue != null && idleTimeoutInMinutesValue.Type != JTokenType.Null) { int idleTimeoutInMinutesInstance = ((int)idleTimeoutInMinutesValue); publicIpAddressJsonFormatInstance.IdleTimeoutInMinutes = idleTimeoutInMinutesInstance; } JToken resourceGuidValue = propertiesValue["resourceGuid"]; if (resourceGuidValue != null && resourceGuidValue.Type != JTokenType.Null) { string resourceGuidInstance = ((string)resourceGuidValue); publicIpAddressJsonFormatInstance.ResourceGuid = resourceGuidInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); publicIpAddressJsonFormatInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); publicIpAddressJsonFormatInstance.Etag = etagInstance; } JToken idValue2 = valueValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); publicIpAddressJsonFormatInstance.Id = idInstance2; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); publicIpAddressJsonFormatInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); publicIpAddressJsonFormatInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); publicIpAddressJsonFormatInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); publicIpAddressJsonFormatInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.WebSites { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Composite Swagger for WebSite Management Client /// </summary> public partial interface IWebSiteManagementClient : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> ServiceClientCredentials Credentials { get; } /// <summary> /// Your Azure subscription ID. This is a GUID-formatted string (e.g. /// 00000000-0000-0000-0000-000000000000). /// </summary> string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running /// Operations. Default value is 30. /// </summary> 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> bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IAppServiceCertificateOrdersOperations. /// </summary> IAppServiceCertificateOrdersOperations AppServiceCertificateOrders { get; } /// <summary> /// Gets the IAppServiceEnvironmentsOperations. /// </summary> IAppServiceEnvironmentsOperations AppServiceEnvironments { get; } /// <summary> /// Gets the IAppServicePlansOperations. /// </summary> IAppServicePlansOperations AppServicePlans { get; } /// <summary> /// Gets the ICertificatesOperations. /// </summary> ICertificatesOperations Certificates { get; } /// <summary> /// Gets the IDomainsOperations. /// </summary> IDomainsOperations Domains { get; } /// <summary> /// Gets the IRecommendationsOperations. /// </summary> IRecommendationsOperations Recommendations { get; } /// <summary> /// Gets the ITopLevelDomainsOperations. /// </summary> ITopLevelDomainsOperations TopLevelDomains { get; } /// <summary> /// Gets the IWebAppsOperations. /// </summary> IWebAppsOperations WebApps { get; } /// <summary> /// Gets the IDeletedWebAppsOperations. /// </summary> IDeletedWebAppsOperations DeletedWebApps { get; } /// <summary> /// Gets the source controls available for Azure websites. /// </summary> /// <remarks> /// Gets the source controls available for Azure websites. /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<SourceControl>>> ListSourceControlsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates source control token /// </summary> /// <remarks> /// Updates source control token /// </remarks> /// <param name='sourceControlType'> /// Type of source control /// </param> /// <param name='requestMessage'> /// Source control token information /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<SourceControl>> UpdateSourceControlWithHttpMessagesAsync(string sourceControlType, SourceControl requestMessage, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Check if a resource name is available. /// </summary> /// <remarks> /// Check if a resource name is available. /// </remarks> /// <param name='name'> /// Resource name to verify. /// </param> /// <param name='type'> /// Resource type used for verification. Possible values include: /// 'Site', 'Slot', 'HostingEnvironment' /// </param> /// <param name='isFqdn'> /// Is fully qualified domain name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ResourceNameAvailability>> CheckNameAvailabilityWithHttpMessagesAsync(string name, string type, bool? isFqdn = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a list of available geographical regions. /// </summary> /// <remarks> /// Get a list of available geographical regions. /// </remarks> /// <param name='sku'> /// Name of SKU used to filter the regions. Possible values include: /// 'Free', 'Shared', 'Basic', 'Standard', 'Premium', 'Dynamic' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<GeoRegion>>> ListGeoRegionsWithHttpMessagesAsync(string sku = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all premier add-on offers. /// </summary> /// <remarks> /// List all premier add-on offers. /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<PremierAddOnOffer>>> ListPremierAddOnOffersWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the publishing credentials for the subscription owner. /// </summary> /// <remarks> /// Get the publishing credentials for the subscription owner. /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<User>> GetPublishingCredentialsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update the publishing credentials for the subscription owner. /// </summary> /// <remarks> /// Update the publishing credentials for the subscription owner. /// </remarks> /// <param name='requestMessage'> /// A request message with the new publishing credentials. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<User>> UpdatePublishingCredentialsWithHttpMessagesAsync(User requestMessage, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all SKUs. /// </summary> /// <remarks> /// List all SKUs. /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<SkuInfos>> ListSkusWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Move resources between resource groups. /// </summary> /// <remarks> /// Move resources between resource groups. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='moveResourceEnvelope'> /// Object that represents the resource to move. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> MoveWithHttpMessagesAsync(string resourceGroupName, CsmMoveResourceEnvelope moveResourceEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Validate if a resource can be created. /// </summary> /// <remarks> /// Validate if a resource can be created. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='validateRequest'> /// Request with the resources to validate. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ValidateResponse>> ValidateWithHttpMessagesAsync(string resourceGroupName, ValidateRequest validateRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Validate whether a resource can be moved. /// </summary> /// <remarks> /// Validate whether a resource can be moved. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='moveResourceEnvelope'> /// Object that represents the resource to move. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> ValidateMoveWithHttpMessagesAsync(string resourceGroupName, CsmMoveResourceEnvelope moveResourceEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the source controls available for Azure websites. /// </summary> /// <remarks> /// Gets the source controls available for Azure websites. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<SourceControl>>> ListSourceControlsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a list of available geographical regions. /// </summary> /// <remarks> /// Get a list of available geographical regions. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<GeoRegion>>> ListGeoRegionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all premier add-on offers. /// </summary> /// <remarks> /// List all premier add-on offers. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<PremierAddOnOffer>>> ListPremierAddOnOffersNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * * (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.Collections.Generic; using System.Data; using System.Text; namespace ASC.Common.Data.Sql { public abstract class SqlCreate : ISqlInstruction { protected string Name { get; private set; } protected SqlCreate(string name) { Name = name; } public abstract string ToString(ISqlDialect dialect); public IEnumerable<object> GetParameters() { return new object[0]; } public override string ToString() { return ToString(SqlDialect.Default); } public class Table : SqlCreate { private bool ifNotExists; private readonly List<string> primaryKey = new List<string>(); private readonly List<Column> columns = new List<Column>(); private readonly List<Index> indexes = new List<Index>(); public Table(string name) : base(name) { } public Table(string name, bool ifNotExists) : this(name) { IfNotExists(ifNotExists); } public Table IfNotExists(bool ifNotExists) { this.ifNotExists = ifNotExists; return this; } public Table AddColumn(Column column) { this.columns.Add(column); return this; } public Table AddColumn(string name, DbType type) { AddColumn(name, type, 0, false); return this; } public Table AddColumn(string name, DbType type, int size) { AddColumn(name, type, size, false); return this; } public Table AddColumn(string name, DbType type, bool notNull) { AddColumn(name, type, 0, notNull); return this; } public Table AddColumn(string name, DbType type, int size, bool notNull) { AddColumn(new Column(name, type, size).NotNull(notNull)); return this; } public Table PrimaryKey(params string[] columns) { primaryKey.AddRange(columns); return this; } public Table AddIndex(Index index) { index.IfNotExists(ifNotExists); this.indexes.Add(index); return this; } public Table AddIndex(string name, params string[] columns) { AddIndex(new Index(name, Name, columns)); return this; } public override string ToString(ISqlDialect dialect) { var sql = new StringBuilder("create table "); if (ifNotExists) sql.Append("if not exists "); sql.AppendFormat("{0} (", Name); foreach (var c in columns) { sql.AppendFormat("{0}, ", c.ToString(dialect)); } if (0 < primaryKey.Count) { sql.Append("primary key ("); foreach (var c in primaryKey) { sql.AppendFormat("{0}, ", c); } sql.Replace(", ", "), ", sql.Length - 2, 2); } if (dialect.SeparateCreateIndex) { sql.Replace(", ", ");", sql.Length - 2, 2); sql.AppendLine(); indexes.ForEach(i => sql.AppendLine(i.ToString(dialect))); } else { foreach (var i in indexes) { sql.AppendFormat("index {0}{1} (", i.unique ? "unique " : string.Empty, i.Name); foreach (var c in i.columns) { sql.AppendFormat("{0}, ", c); } sql.Replace(", ", "), ", sql.Length - 2, 2); } sql.Replace(", ", ");", sql.Length - 2, 2); } return sql.ToString(); } } public class Column : SqlCreate { private readonly DbType type; private readonly int size; private readonly int precision; private bool notNull; private bool primaryKey; private bool autoinc; private object defaultValue; public Column(string name, DbType type) : this(name, type, 0, 0) { this.type = type; } public Column(string name, DbType type, int size) : this(name, type, size, 0) { this.type = type; } public Column(string name, DbType type, int size, int precision) : base(name) { this.type = type; this.size = size; this.precision = precision; } public Column NotNull(bool notNull) { this.notNull = notNull; return this; } public Column Autoincrement(bool autoincrement) { this.autoinc = autoincrement; return this; } public Column PrimaryKey(bool primaryKey) { this.primaryKey = primaryKey; return this; } public Column Default(object value) { this.defaultValue = value; return this; } public override string ToString(ISqlDialect dialect) { var sql = new StringBuilder().AppendFormat("{0} {1} {2} ", Name, dialect.DbTypeToString(type, size, precision), notNull ? "not null" : "null"); if (defaultValue != null) sql.AppendFormat("default {0} ", defaultValue); if (primaryKey) sql.Append("primary key "); if (autoinc) sql.Append(dialect.Autoincrement); return sql.ToString().Trim(); } } public class Index : SqlCreate { private readonly string table; internal string[] columns; internal bool unique; private bool ifNotExists; public Index(string name, string table, params string[] columns) : base(name) { this.table = table; this.columns = columns ?? new string[0]; } public Index Unique(bool unique) { this.unique = unique; return this; } public Index IfNotExists(bool ifNotExists) { this.ifNotExists = ifNotExists; return this; } public override string ToString(ISqlDialect dialect) { var sql = new StringBuilder("create "); if (unique) sql.Append("unique "); sql.Append("index "); if (ifNotExists) sql.Append("if not exists "); sql.AppendFormat("{0} on {1} (", Name, table); foreach (var c in columns) { sql.AppendFormat("{0}, ", c); } return sql.Replace(", ", ");", sql.Length - 2, 2).ToString(); } } } }
using System; using System.ServiceModel; namespace OpenRiaServices.DomainServices.Hosting { #region Namespaces using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.ServiceModel.Description; using OpenRiaServices.DomainServices.Hosting.OData; using OpenRiaServices.DomainServices.Server; using System.ServiceModel.Web; using System.Text; #endregion /// <summary> /// Represents a Domain Data Service endpoint factory for <see cref="DomainService"/>s. /// </summary> public class ODataEndpointFactory : DomainServiceEndpointFactory { /// <summary>Data Service metadata object corresponding to domain service description.</summary> private DomainDataServiceMetadata domainDataServiceMetadata; /// <summary> /// Creates endpoints based on the specified description. /// </summary> /// <param name="description">The <see cref="DomainServiceDescription"/> of the <see cref="DomainService"/> to create the endpoints for.</param> /// <param name="serviceHost">The service host for which the endpoints will be created.</param> /// <returns>The endpoints that were created.</returns> public override IEnumerable<ServiceEndpoint> CreateEndpoints(DomainServiceDescription description, DomainServiceHost serviceHost) { Debug.Assert(this.Name != null, "Name has not been set."); Debug.Assert(this.domainDataServiceMetadata == null, "this.domainDataServiceMetadata == null"); if (description.Attributes[typeof(EnableClientAccessAttribute)] != null) { // The metadata object will tell us which operations we should expose for the OData end point. this.domainDataServiceMetadata = new OData.DomainDataServiceMetadata(description); // The OData endpoint doesn't expose all operations in the DomainService, but only operations with parameter and return types // which are supported by the data service. WCF doesn't allow us to create a contract without any operation. if (this.domainDataServiceMetadata.Sets.Count > 0 || this.domainDataServiceMetadata.ServiceOperations.Count > 0) { // Infer the contract from Domain service description. ContractDescription contract = this.CreateContract(description); // Make endpoints that expose the inferred contract on the given base addresses. foreach (Uri address in serviceHost.BaseAddresses) { yield return this.CreateEndpointForAddress(description, contract, address); } } } } /// <summary> /// Creates a contract description for the domain data service endpoint based on the domain service description. /// </summary> /// <param name="description">Domain data service description.</param> /// <returns>Contract description for the domain data service endpoint.</returns> private ContractDescription CreateContract(DomainServiceDescription description) { Type domainServiceType = description.DomainServiceType; ServiceDescription serviceDesc = ServiceDescription.GetService(domainServiceType); // Use names from [ServiceContract], if specified. ServiceContractAttribute sca = TypeDescriptor.GetAttributes(domainServiceType)[typeof(ServiceContractAttribute)] as ServiceContractAttribute; if (sca != null) { if (!String.IsNullOrEmpty(sca.Name)) { serviceDesc.Name = sca.Name; } if (!String.IsNullOrEmpty(sca.Namespace)) { serviceDesc.Name = sca.Namespace; } } ContractDescription contractDesc = new ContractDescription(serviceDesc.Name + this.Name, serviceDesc.Namespace) { ConfigurationName = serviceDesc.ConfigurationName + this.Name, ContractType = domainServiceType }; // Disable metadata generation for the domain data service contract. contractDesc.Behaviors.Add(new ServiceMetadataContractBehavior(true)); // Add domain service behavior which takes care of instantiating DomainServices. ServiceUtils.EnsureBehavior<DomainDataServiceContractBehavior>(contractDesc); // Load the ContractDescription from the DomainServiceDescription. this.LoadContractDescription(contractDesc, description); return contractDesc; } /// <summary> /// Creates an endpoint based on the specified address. /// </summary> /// <param name="domainServiceDescription">Domain service description from which the <paramref name="contract"/> was inferred.</param> /// <param name="contract">The endpoint's contract.</param> /// <param name="address">The endpoint's base address.</param> /// <returns>An endpoint.</returns> private ServiceEndpoint CreateEndpointForAddress(DomainServiceDescription domainServiceDescription, ContractDescription contract, Uri address) { WebHttpBinding binding = new WebHttpBinding(); binding.MaxReceivedMessageSize = Int32.MaxValue; ServiceUtils.SetReaderQuotas(binding.ReaderQuotas); if (address.Scheme.Equals(Uri.UriSchemeHttps)) { binding.Security.Mode = WebHttpSecurityMode.Transport; } else if (ServiceUtils.CredentialType != HttpClientCredentialType.None) { binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly; } if (ServiceUtils.CredentialType != HttpClientCredentialType.None) { binding.Security.Transport.ClientCredentialType = ServiceUtils.CredentialType; } ServiceEndpoint ep = new ServiceEndpoint(contract, binding, new EndpointAddress(address.OriginalString + "/" + this.Name)); // Data service end point has data service behavior. ep.Behaviors.Add(new DomainDataServiceEndpointBehavior() { DomainDataServiceMetadata = this.domainDataServiceMetadata, DefaultBodyStyle = WebMessageBodyStyle.Wrapped }); return ep; } /// <summary> /// Create operation corresponding to given DomainService query operation. /// </summary> /// <param name="declaringContract">Contract to which operation will belong.</param> /// <param name="operation">DomainService query operation.</param> /// <returns>Created operation.</returns> private static OperationDescription CreateQueryOperationDescription(ContractDescription declaringContract, DomainOperationEntry operation) { OperationDescription operationDesc = ODataEndpointFactory.CreateOperationDescription(declaringContract, operation); // Change the return type to QueryResult<TEntity>. operationDesc.Messages[1].Body.ReturnValue.Type = typeof(IEnumerable<>).MakeGenericType(operation.AssociatedType); return operationDesc; } /// <summary> /// Create operation corresponding to given DomainService operation. /// </summary> /// <param name="declaringContract">Contract to which operation will belong.</param> /// <param name="operation">DomainService operation.</param> /// <returns>Created operation.</returns> private static OperationDescription CreateOperationDescription(ContractDescription declaringContract, DomainOperationEntry operation) { OperationDescription operationDesc = new OperationDescription(operation.Name, declaringContract); // Propagate behaviors. foreach (IOperationBehavior behavior in operation.Attributes.OfType<IOperationBehavior>()) { operationDesc.Behaviors.Add(behavior); } // Add standard web behaviors behaviors. if ((operation.Operation == DomainOperation.Query && ((QueryAttribute)operation.OperationAttribute).HasSideEffects) || (operation.Operation == DomainOperation.Invoke && ((InvokeAttribute)operation.OperationAttribute).HasSideEffects)) { // For operations with side-effects i.e. with WebInvoke attribute, we need to build a default GET like // URI template so that, the parameter processing is taken care of by the WebHttpBehavior selector. WebInvokeAttribute attrib = ServiceUtils.EnsureBehavior<WebInvokeAttribute>(operationDesc); if (attrib.UriTemplate == null) { attrib.UriTemplate = ODataEndpointFactory.BuildDefaultUriTemplate(operation); } } else { ServiceUtils.EnsureBehavior<WebGetAttribute>(operationDesc); } string action = ServiceUtils.GetRequestMessageAction(declaringContract, operationDesc.Name, null); // Define operation input. MessageDescription inputMessageDesc = new MessageDescription(action, MessageDirection.Input); inputMessageDesc.Body.WrapperName = operationDesc.Name; inputMessageDesc.Body.WrapperNamespace = ServiceUtils.DefaultNamespace; for (int i = 0; i < operation.Parameters.Count; i++) { DomainOperationParameter parameter = operation.Parameters[i]; MessagePartDescription parameterPartDesc = new MessagePartDescription(parameter.Name, ServiceUtils.DefaultNamespace) { Index = i, Type = TypeUtils.GetClientType(parameter.ParameterType) }; inputMessageDesc.Body.Parts.Add(parameterPartDesc); } operationDesc.Messages.Add(inputMessageDesc); // Define operation output. string responseAction = ServiceUtils.GetResponseMessageAction(declaringContract, operationDesc.Name, null); MessageDescription outputMessageDesc = new MessageDescription(responseAction, MessageDirection.Output); outputMessageDesc.Body.WrapperName = operationDesc.Name + "Response"; outputMessageDesc.Body.WrapperNamespace = ServiceUtils.DefaultNamespace; if (operation.ReturnType != typeof(void)) { outputMessageDesc.Body.ReturnValue = new MessagePartDescription(operationDesc.Name + "Result", ServiceUtils.DefaultNamespace) { Type = TypeUtils.GetClientType(operation.ReturnType) }; } operationDesc.Messages.Add(outputMessageDesc); return operationDesc; } /// <summary> /// Builds the default URI temaplate to be used for side-effecting (POST) operations. /// </summary> /// <param name="operation">Domain operation.</param> /// <returns>string representing the default URI temaplate.</returns> private static string BuildDefaultUriTemplate(DomainOperationEntry operation) { StringBuilder builder = new StringBuilder(operation.Name); if (operation.Parameters.Count > 0) { builder.Append("?"); foreach (var parameter in operation.Parameters) { builder.Append(parameter.Name); builder.Append("={"); builder.Append(parameter.Name); builder.Append("}&"); } builder.Remove(builder.Length - 1, 1); } return builder.ToString(); } /// <summary> /// Populates a contract description from a domain service description. /// </summary> /// <param name="contractDesc">Contract description to populate.</param> /// <param name="domainServiceDescription">Domain service description.</param> private void LoadContractDescription(ContractDescription contractDesc, DomainServiceDescription domainServiceDescription) { OperationDescription operationDesc; Debug.Assert(this.domainDataServiceMetadata != null, "this.domainDataServiceMetadata != null"); // Create contract operations by inferring them from the [Query] & [Invoke] methods on the domain service. foreach (DomainOperationEntry operation in domainServiceDescription.DomainOperationEntries) { if (this.domainDataServiceMetadata.Sets.ContainsKey(operation.Name) || this.domainDataServiceMetadata.ServiceOperations.ContainsKey(operation.Name)) { switch (operation.Operation) { case DomainOperation.Query: operationDesc = ODataEndpointFactory.CreateQueryOperationDescription(contractDesc, operation); Type queryOperationType = typeof(DomainDataServiceQueryOperationBehavior<>).MakeGenericType(operation.AssociatedType); // Add as first behavior such that our operation invoker is the first in the chain. operationDesc.Behaviors.Insert(0, (IOperationBehavior)Activator.CreateInstance(queryOperationType, operation)); contractDesc.Operations.Add(operationDesc); break; case DomainOperation.Invoke: operationDesc = ODataEndpointFactory.CreateOperationDescription(contractDesc, operation); // Add as first behavior such that our operation invoker is the first in the chain. operationDesc.Behaviors.Insert(0, new DomainDataServiceInvokeOperationBehavior(operation)); contractDesc.Operations.Add(operationDesc); break; default: break; } } } } } }
/* Copyright (c) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using Microsoft.Research.DryadLinq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DryadLinqTests { ////////////////////////////////////////////////////////////////////// // // Decorated and undecorated types // // A UDT with no attribute shouldn't autoserialize without an explicit [Serializable] attribute public class UDT_Undecorated { public UDT_Undecorated(int val) { m_field1 = val + 1; m_field2 = val + 2; } public int m_field1; public int m_field2; } // UDT which is marked as serializable. This should be autoserialized [Serializable] public class UDT_MarkedSerializable { public UDT_MarkedSerializable(int val) { m_field1 = val + 1; m_field2 = val + 2; } public int m_field1; public int m_field2; } // UDT that has the old style static serialization methods. This should be rejected. public class UDT_StaticSerializer { public UDT_StaticSerializer(int val) { m_field1 = val + 1; m_field2 = val + 2; } public int m_field1; public int m_field2; public static UDT_StaticSerializer Read(DryadLinqBinaryReader reader) { var val = new UDT_StaticSerializer(0); val.m_field1 = reader.ReadInt32(); val.m_field2 = reader.ReadInt32(); return val; } public static void Write(DryadLinqBinaryWriter writer, UDT_StaticSerializer val) { writer.Write(val.m_field1); writer.Write(val.m_field2); } } ////////////////////////////////////////////////////////////////////// // // UDTs with custom serializers // // UDT that has an attribute declaring itself as its custom serializer [CustomDryadLinqSerializer(typeof(UDT_SelfCustomSerializer))] public struct UDT_SelfCustomSerializer : IDryadLinqSerializer<UDT_SelfCustomSerializer> { public UDT_SelfCustomSerializer(int val) { m_field1 = val + 1; m_field2 = val + 2; } public int m_field1; public int m_field2; public UDT_SelfCustomSerializer Read(DryadLinqBinaryReader reader) { var val = new UDT_SelfCustomSerializer(0); val.m_field1 = reader.ReadInt32(); val.m_field2 = reader.ReadInt32(); return val; } public void Write(DryadLinqBinaryWriter writer, UDT_SelfCustomSerializer val) { writer.Write(val.m_field1); writer.Write(val.m_field2); } } // UDT that declares another type as its custom serializer [CustomDryadLinqSerializer(typeof(CustomUDTSerializer))] public struct UDT_ExternalCustomSerializer { public UDT_ExternalCustomSerializer(int val) { m_field1 = val + 1; m_field2 = val + 2; } public int m_field1; public int m_field2; } // this is the custom serializer for UDT_ExternalCustomSerializer public class CustomUDTSerializer : IDryadLinqSerializer<UDT_ExternalCustomSerializer> { public UDT_ExternalCustomSerializer Read(DryadLinqBinaryReader reader) { var val = new UDT_ExternalCustomSerializer(0); val.m_field1 = reader.ReadInt32(); val.m_field2 = reader.ReadInt32(); return val; } public void Write(DryadLinqBinaryWriter writer, UDT_ExternalCustomSerializer val) { writer.Write(val.m_field1); writer.Write(val.m_field2); } } // UDT with a CustomHpcSerializer attribute that points to an invalid type for the serializer [CustomDryadLinqSerializer(typeof(int))] public struct UDT_BadCustomSerializerType1 { public UDT_BadCustomSerializerType1(int val) { m_field1 = val + 1; } public int m_field1; } // UDT with a CustomHpcSerializer attribute that points to a serializer type that targets a different UDT [CustomDryadLinqSerializer(typeof(CustomUDTSerializer))] public struct UDT_BadCustomSerializerType2 { public UDT_BadCustomSerializerType2(int val) { m_field1 = val + 1; } public int m_field1; } ////////////////////////////////////////////////////////////////////// // // Inheritance // // A UDT that has sub types. This should be rejected [Serializable] public class UDT_BaseType { public UDT_BaseType(int val) { m_baseTypeField = val + 42; } public int m_baseTypeField; } // A UDT that has derives from a type other than object. This should be rejected [Serializable] public class UDT_DerivedType : UDT_BaseType { public UDT_DerivedType(int val) : base(val) { m_derivedTypeField = val + 84; } public int m_derivedTypeField; } ////////////////////////////////////////////////////////////////////// // // Field types // // A UDT with no data. This should be rejected [Serializable] public class UDT_EmptyType { public UDT_EmptyType(int val) { } } // A UDT with a public field of type System.Object. This should be rejected [Serializable] public class UDT_ObjectField { public UDT_ObjectField(int val) { m_intField = val + 84; m_objectField = null; } public int m_intField; public object m_objectField; } // A UDT with a public field of type System.Object[]. This should be rejected [Serializable] public class UDT_ObjectArrayField { public UDT_ObjectArrayField(int val) { m_intField = val + 84; m_objectArrayField = new object[1]; m_objectArrayField[0] = null; } public int m_intField; public object[] m_objectArrayField; } // A UDT with a public field of type List<System.Object>. This should be rejected [Serializable] public class UDT_ObjectListField { public UDT_ObjectListField(int val) { m_intField = val + 84; m_objectListField = new List<object>(); m_objectListField.Add(null); } public int m_intField; public List<object> m_objectListField; } // A UDT with an object field, and a custom serializer. This should not be rejected [CustomDryadLinqSerializer(typeof(UDT_ObjectFieldAndCustomSerializer))] public class UDT_ObjectFieldAndCustomSerializer : IDryadLinqSerializer<UDT_ObjectFieldAndCustomSerializer> { private object m_objectRecord = (object)""; // Required by CustomHpcSerializer public UDT_ObjectFieldAndCustomSerializer() { } public UDT_ObjectFieldAndCustomSerializer(int val) { m_objectRecord = (object)String.Format("{0}", val); } #region IHpcSerializer implementation public UDT_ObjectFieldAndCustomSerializer Read(DryadLinqBinaryReader reader) { string tmp = reader.ReadString(); int val = Int32.Parse(tmp); return new UDT_ObjectFieldAndCustomSerializer(val); } public void Write(DryadLinqBinaryWriter writer, UDT_ObjectFieldAndCustomSerializer record) { writer.Write((string)record.m_objectRecord); } #endregion } // An empty UDT with a custom serializer. This should be rejected, because even though the user has control over serialization // we will encounter runtime problems if the custom serializer reads/writer 0 bytes. This behavior is simply to discourage empty CS code. [CustomDryadLinqSerializer(typeof(UDT_EmptyTypeWithCustomSerializer))] public class UDT_EmptyTypeWithCustomSerializer : IDryadLinqSerializer<UDT_EmptyTypeWithCustomSerializer> { // Required by CustomHpcSerializer public UDT_EmptyTypeWithCustomSerializer() { } public UDT_EmptyTypeWithCustomSerializer(int val) { } #region IHpcSerializer implementation public UDT_EmptyTypeWithCustomSerializer Read(DryadLinqBinaryReader reader) { return new UDT_EmptyTypeWithCustomSerializer(0); } public void Write(DryadLinqBinaryWriter writer, UDT_EmptyTypeWithCustomSerializer record) { } #endregion } ////////////////////////////////////////////////////////////////////// // // Visibility // // UDT with a field of non-public type. We cannot handle these [Serializable] public class UDT_FieldOfNonPublicType { private enum SecretCodeLevel { Secret, SuperSecret, } public UDT_FieldOfNonPublicType(int val) { m_field = (SecretCodeLevel)val; } private SecretCodeLevel m_field; } // UDT with a private field of a public type. We do handle these using emitted IL code. [Serializable] public class UDT_PrivateFieldOfPublicType { public UDT_PrivateFieldOfPublicType(int val) { m_field = val + 1; } private int m_field; } ////////////////////////////////////////////////////////////////////// // // Nesting // [Serializable] public class UDT_Nested_InnerAndOuterSerializable { public UDT_Nested_InnerAndOuterSerializable(int val) { m_field = val + 1; m_field2 = new NestedSerializable(val); } private int m_field; private NestedSerializable m_field2; [Serializable] public class NestedSerializable { public NestedSerializable(int val) { m_field = val / 2.0; } private double m_field; } } [Serializable] public class UDT_Nested_InnerEnum_InnerAndOuterSerializable { public UDT_Nested_InnerEnum_InnerAndOuterSerializable(int val) { m_field = val + 1; m_field2 = (NestedEnum)(val % 3); } private int m_field; private NestedEnum m_field2; //[Serializable] public enum NestedEnum { Foo = 0, Bar = 1, Baz = 2, } } [Serializable] public class UDT_Nested_OuterSerializableInnerNotSerializable { public UDT_Nested_OuterSerializableInnerNotSerializable(int val) { m_field = val + 1; m_field2 = new NestedNotSerializable(val); } private int m_field; private NestedNotSerializable m_field2; public class NestedNotSerializable { public NestedNotSerializable(int val) { m_field = val / 2.0; } private double m_field; } } public class UDT_Nested_OuterNotSerializableInnerSerializable { public UDT_Nested_OuterNotSerializableInnerSerializable(int val) { m_field = val + 1; m_field2 = new NestedSerializable(val); } private int m_field; private NestedSerializable m_field2; [Serializable] public class NestedSerializable { public NestedSerializable(int val) { m_field = val / 2.0; } private double m_field; } } ////////////////////////////////////////////////////////////////////// // // Self reference // // First level circular type [Serializable] public class UDT_FirstLevelCircular { public UDT_FirstLevelCircular(int val) { m_field1 = val + 1; m_field2 = val + 2; m_circularRef = null; } public int m_field1; public int m_field2; public UDT_FirstLevelCircular m_circularRef; } // First level circular type with an array reference to self [Serializable] public class UDT_FirstLevelCircularArrayRef { public UDT_FirstLevelCircularArrayRef(int val) { m_field1 = val + 1; m_field2 = val + 2; m_circularRefArray = new UDT_FirstLevelCircular[5]; } public int m_field1; public int m_field2; public UDT_FirstLevelCircular[] m_circularRefArray; } // Second level circular type [Serializable] public class UDT_SecondLevelCircular { public UDT_SecondLevelCircular(int val) { m_field1 = val + 1; m_field2 = val + 2; m_child = new UDT_CircularRefChild(this); } public int m_field1; public int m_field2; public UDT_CircularRefChild m_child; } [Serializable] public class UDT_CircularRefChild { public UDT_CircularRefChild(UDT_SecondLevelCircular parent) { m_parent = parent; } public UDT_SecondLevelCircular m_parent; } // Circular type with custom serializer. Should not be rejected [CustomDryadLinqSerializer(typeof(UDT_CircularTypeWithCustomSerializer))] public class UDT_CircularTypeWithCustomSerializer : IDryadLinqSerializer<UDT_CircularTypeWithCustomSerializer> { public UDT_CircularTypeWithCustomSerializer() { } public UDT_CircularTypeWithCustomSerializer(int val) { m_field1 = val; // create each new object with log2(val) self references hanging off of m_next if (val == 0) m_next = null; else m_next = new UDT_CircularTypeWithCustomSerializer(val / 2); } public int m_field1; public UDT_CircularTypeWithCustomSerializer m_next; // // sample recursive custom serializer // public UDT_CircularTypeWithCustomSerializer Read(DryadLinqBinaryReader reader) { UDT_CircularTypeWithCustomSerializer obj = new UDT_CircularTypeWithCustomSerializer(); bool bHasValidNext = reader.ReadBool(); obj.m_field1 = reader.ReadInt32(); if (bHasValidNext) { obj.m_next = this.Read(reader); // recursively read the next } else { obj.m_next = null; // terminate recursion } return obj; } public void Write(DryadLinqBinaryWriter writer, UDT_CircularTypeWithCustomSerializer x) { if (x.m_next != null) { writer.Write(true); // bHasValidNext for the reader side writer.Write(x.m_field1); this.Write(writer, x.m_next); // write out recursively } else { writer.Write(false); // bHasValidNext = false for the reader side, makes sure recursive reads stop writer.Write(x.m_field1); } } } // This type itself isn't circular, but contains a field of a circular type that is custom serialized. Autoserialization should work for this guy [Serializable] public class UDT_TypeContainingCustomSerializedCircularType { public UDT_TypeContainingCustomSerializedCircularType(int val) { m_field1 = val; m_circularType = new UDT_CircularTypeWithCustomSerializer(val); } public int m_field1; public UDT_CircularTypeWithCustomSerializer m_circularType; } }
// 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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { protected override AbstractNodeLocator CreateNodeLocator() { return new NodeLocator(this); } private class NodeLocator : AbstractNodeLocator { public NodeLocator(CSharpCodeModelService codeModelService) : base(codeModelService) { } protected override EnvDTE.vsCMPart DefaultPart { get { return EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; } } protected override VirtualTreePoint? GetStartPoint(SourceText text, SyntaxNode node, EnvDTE.vsCMPart part) { switch (node.Kind()) { case SyntaxKind.Attribute: return GetStartPoint(text, (AttributeSyntax)node, part); case SyntaxKind.AttributeArgument: return GetStartPoint(text, (AttributeArgumentSyntax)node, part); case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.EnumDeclaration: return GetStartPoint(text, (BaseTypeDeclarationSyntax)node, part); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return GetStartPoint(text, (BaseMethodDeclarationSyntax)node, part); case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: return GetStartPoint(text, (BasePropertyDeclarationSyntax)node, part); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return GetStartPoint(text, (AccessorDeclarationSyntax)node, part); case SyntaxKind.DelegateDeclaration: return GetStartPoint(text, (DelegateDeclarationSyntax)node, part); case SyntaxKind.NamespaceDeclaration: return GetStartPoint(text, (NamespaceDeclarationSyntax)node, part); case SyntaxKind.UsingDirective: return GetStartPoint(text, (UsingDirectiveSyntax)node, part); case SyntaxKind.EnumMemberDeclaration: return GetStartPoint(text, (EnumMemberDeclarationSyntax)node, part); case SyntaxKind.VariableDeclarator: return GetStartPoint(text, (VariableDeclaratorSyntax)node, part); case SyntaxKind.Parameter: return GetStartPoint(text, (ParameterSyntax)node, part); default: Debug.Fail("Unsupported node kind: " + node.Kind()); throw new NotSupportedException(); } } protected override VirtualTreePoint? GetEndPoint(SourceText text, SyntaxNode node, EnvDTE.vsCMPart part) { switch (node.Kind()) { case SyntaxKind.Attribute: return GetEndPoint(text, (AttributeSyntax)node, part); case SyntaxKind.AttributeArgument: return GetEndPoint(text, (AttributeArgumentSyntax)node, part); case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.EnumDeclaration: return GetEndPoint(text, (BaseTypeDeclarationSyntax)node, part); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return GetEndPoint(text, (BaseMethodDeclarationSyntax)node, part); case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: return GetEndPoint(text, (BasePropertyDeclarationSyntax)node, part); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return GetEndPoint(text, (AccessorDeclarationSyntax)node, part); case SyntaxKind.DelegateDeclaration: return GetEndPoint(text, (DelegateDeclarationSyntax)node, part); case SyntaxKind.NamespaceDeclaration: return GetEndPoint(text, (NamespaceDeclarationSyntax)node, part); case SyntaxKind.UsingDirective: return GetEndPoint(text, (UsingDirectiveSyntax)node, part); case SyntaxKind.EnumMemberDeclaration: return GetEndPoint(text, (EnumMemberDeclarationSyntax)node, part); case SyntaxKind.VariableDeclarator: return GetEndPoint(text, (VariableDeclaratorSyntax)node, part); case SyntaxKind.Parameter: return GetEndPoint(text, (ParameterSyntax)node, part); default: Debug.Fail("Unsupported node kind: " + node.Kind()); throw new NotSupportedException(); } } private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace) { Debug.Assert(!openBrace.IsMissing); var openBraceLine = text.Lines.GetLineFromPosition(openBrace.Span.End); var textAfterBrace = text.ToString(TextSpan.FromBounds(openBrace.Span.End, openBraceLine.End)); return string.IsNullOrWhiteSpace(textAfterBrace) ? new VirtualTreePoint(openBrace.SyntaxTree, text, text.Lines[openBraceLine.LineNumber + 1].Start) : new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End); } private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace, SyntaxToken closeBrace, int memberStartColumn) { Debug.Assert(!openBrace.IsMissing); Debug.Assert(!closeBrace.IsMissing); Debug.Assert(memberStartColumn >= 0); var openBraceLine = text.Lines.GetLineFromPosition(openBrace.SpanStart); var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart); var tokenAfterOpenBrace = openBrace.GetNextToken(); var nextPosition = tokenAfterOpenBrace.SpanStart; // We need to check if there is any significant trivia trailing this token or leading // to the next token. This accounts for the fact that comments were included in the token // stream in Dev10. var significantTrivia = openBrace.GetAllTrailingTrivia() .Where(t => !t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia)) .FirstOrDefault(); if (significantTrivia.Kind() != SyntaxKind.None) { nextPosition = significantTrivia.SpanStart; } // If the opening and closing curlies are at least two lines apart then place the cursor // on the next line provided that there isn't any token on the line with the open curly. if (openBraceLine.LineNumber + 1 < closeBraceLine.LineNumber && openBraceLine.LineNumber < text.Lines.IndexOf(tokenAfterOpenBrace.SpanStart)) { var lineAfterOpenBrace = text.Lines[openBraceLine.LineNumber + 1]; var firstNonWhitespaceOffset = lineAfterOpenBrace.GetFirstNonWhitespaceOffset() ?? -1; // If the line contains any text, we return the start of the first non-whitespace character. if (firstNonWhitespaceOffset >= 0) { return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.Start + firstNonWhitespaceOffset); } // If the line is all whitespace then place the caret at the first indent after the start // of the member. var indentSize = GetTabSize(text); var lineText = lineAfterOpenBrace.ToString(); var lineEndColumn = lineText.GetColumnFromLineOffset(lineText.Length, indentSize); int indentColumn = memberStartColumn + indentSize; var virtualSpaces = indentColumn - lineEndColumn; return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.End, virtualSpaces); } else { // If the body is empty then place it after the open brace; otherwise, place // at the start of the first token after the open curly. if (closeBrace.SpanStart == nextPosition) { return new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End); } else { return new VirtualTreePoint(openBrace.SyntaxTree, text, nextPosition); } } } private VirtualTreePoint GetBodyEndPoint(SourceText text, SyntaxToken closeBrace) { var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart); var textBeforeBrace = text.ToString(TextSpan.FromBounds(closeBraceLine.Start, closeBrace.SpanStart)); return string.IsNullOrWhiteSpace(textBeforeBrace) ? new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBraceLine.Start) : new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBrace.SpanStart); } private VirtualTreePoint GetStartPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartHeader: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartHeader: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text)); return GetBodyStartPoint(text, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation); } else { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: startPosition = ((MethodDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.ConstructorDeclaration: startPosition = ((ConstructorDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.DestructorDeclaration: startPosition = ((DestructorDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.ConversionOperatorDeclaration: startPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.SpanStart; break; case SyntaxKind.OperatorDeclaration: startPosition = ((OperatorDeclarationSyntax)node).OperatorToken.SpanStart; break; default: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; } } break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.Body.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private AccessorDeclarationSyntax FindFirstAccessorNode(BasePropertyDeclarationSyntax node) { if (node.AccessorList == null) { return null; } return node.AccessorList.Accessors.FirstOrDefault(); } private VirtualTreePoint GetStartPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: var firstAccessorNode = FindFirstAccessorNode(node); if (firstAccessorNode != null) { var line = text.Lines.GetLineFromPosition(firstAccessorNode.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text)); if (firstAccessorNode.Body != null) { return GetBodyStartPoint(text, firstAccessorNode.Body.OpenBraceToken, firstAccessorNode.Body.CloseBraceToken, indentation); } else if (!firstAccessorNode.SemicolonToken.IsMissing) { // This is total weirdness from the old C# code model with auto props. // If there isn't a body, the semi-colon is used return GetBodyStartPoint(text, firstAccessorNode.SemicolonToken, firstAccessorNode.SemicolonToken, indentation); } } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.AccessorList != null && !node.AccessorList.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text)); return GetBodyStartPoint(text, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentation); } throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text)); return GetBodyStartPoint(text, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation); } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.Body.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, NamespaceDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part) { var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (field.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = field.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: return GetBodyEndPoint(text, node.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.CloseBraceToken.IsMissing) { return GetBodyEndPoint(text, node.Body.CloseBraceToken); } else { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: endPosition = ((MethodDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.ConstructorDeclaration: endPosition = ((ConstructorDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.DestructorDeclaration: endPosition = ((DestructorDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.ConversionOperatorDeclaration: endPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.Span.End; break; case SyntaxKind.OperatorDeclaration: endPosition = ((OperatorDeclarationSyntax)node).OperatorToken.Span.End; break; default: endPosition = node.GetFirstTokenAfterAttributes().Span.End; break; } } break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.Body.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: var firstAccessorNode = FindFirstAccessorNode(node); if (firstAccessorNode != null) { if (firstAccessorNode.Body != null) { return GetBodyEndPoint(text, firstAccessorNode.Body.CloseBraceToken); } else { // This is total weirdness from the old C# code model with auto props. // If there isn't a body, the semi-colon is used return GetBodyEndPoint(text, firstAccessorNode.SemicolonToken); } } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.AccessorList != null && !node.AccessorList.CloseBraceToken.IsMissing) { return GetBodyEndPoint(text, node.AccessorList.CloseBraceToken); } throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.Body.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, NamespaceDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part) { var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (field.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = field.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = field.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using LiteNetLib.Utils; namespace LiteNetLib { public enum ConnectionState { InProgress, Connected, Disconnected } public sealed class NetPeer { //Flow control private int _currentFlowMode; private int _sendedPacketsCount; private int _flowTimer; //Ping and RTT private int _ping; private int _rtt; private int _avgRtt; private int _rttCount; private int _goodRttCount; private ushort _pingSequence; private ushort _remotePingSequence; private int _pingSendTimer; private const int RttResetDelay = 1000; private int _rttResetTimer; private DateTime _pingTimeStart; private DateTime _lastPacketReceivedStart; //Common private readonly Stack<NetPacket> _packetPool; private readonly NetEndPoint _remoteEndPoint; private readonly NetManager _peerListener; //Channels private readonly ReliableChannel _reliableOrderedChannel; private readonly ReliableChannel _reliableUnorderedChannel; private readonly SequencedChannel _sequencedChannel; private readonly SimpleChannel _simpleChannel; private int _windowSize = NetConstants.DefaultWindowSize; //MTU private int _mtu = NetConstants.PossibleMtu[0]; private int _mtuIdx; private bool _finishMtu; private int _mtuCheckTimer; private int _mtuCheckAttempts; private const int MtuCheckDelay = 1000; private const int MaxMtuCheckAttempts = 4; private readonly object _mtuMutex = new object(); //Fragment private class IncomingFragments { public NetPacket[] Fragments; public int ReceivedCount; public int TotalSize; } private ushort _fragmentId; private readonly Dictionary<ushort, IncomingFragments> _holdedFragments; //Merging private readonly NetPacket _mergeData = new NetPacket(); private int _mergePos; private int _mergeCount; //Connection private int _connectAttempts; private int _connectTimer; private long _connectId; private ConnectionState _connectionState; public ConnectionState ConnectionState { get { return _connectionState; } } public long ConnectId { get { return _connectId; } } public NetEndPoint EndPoint { get { return _remoteEndPoint; } } public int Ping { get { return _ping; } } public int CurrentFlowMode { get { return _currentFlowMode; } } public int Mtu { get { return _mtu; } } public int TimeSinceLastPacket { get { return (int)(DateTime.UtcNow - _lastPacketReceivedStart).TotalMilliseconds; } } public NetManager NetManager { get { return _peerListener; } } public int PacketsCountInReliableQueue { get { return _reliableUnorderedChannel.PacketsInQueue; } } public int PacketsCountInReliableOrderedQueue { get { return _reliableOrderedChannel.PacketsInQueue; } } internal NetPeer(NetManager peerListener, NetEndPoint remoteEndPoint, long connectId) { _peerListener = peerListener; _remoteEndPoint = remoteEndPoint; _avgRtt = 0; _rtt = 0; _pingSendTimer = 0; _reliableOrderedChannel = new ReliableChannel(this, true, _windowSize); _reliableUnorderedChannel = new ReliableChannel(this, false, _windowSize); _sequencedChannel = new SequencedChannel(this); _simpleChannel = new SimpleChannel(this); _packetPool = new Stack<NetPacket>(); _holdedFragments = new Dictionary<ushort, IncomingFragments>(); _mergeData.Init(PacketProperty.Merged, NetConstants.PossibleMtu[NetConstants.PossibleMtu.Length - 1]); //if ID != 0 then we already connected _connectAttempts = 0; if (connectId == 0) { _connectId = DateTime.UtcNow.Ticks; SendConnectRequest(); } else { _connectId = connectId; _connectionState = ConnectionState.Connected; SendConnectAccept(); } NetUtils.DebugWrite(ConsoleColor.Cyan, "[CC] ConnectId: {0}", _connectId); } private void SendConnectRequest() { //Get connect key bytes byte[] keyData = Encoding.UTF8.GetBytes(_peerListener.ConnectKey); //Make initial packet var connectPacket = NetPacket.CreateRawPacket(PacketProperty.ConnectRequest, 12 + keyData.Length); //Add data FastBitConverter.GetBytes(connectPacket, 1, NetConstants.ProtocolId); FastBitConverter.GetBytes(connectPacket, 5, _connectId); Buffer.BlockCopy(keyData, 0, connectPacket, 13, keyData.Length); //Send raw _peerListener.SendRaw(connectPacket, _remoteEndPoint); } private void SendConnectAccept() { //Reset connection timer _lastPacketReceivedStart = DateTime.UtcNow; //Make initial packet var connectPacket = NetPacket.CreateRawPacket(PacketProperty.ConnectAccept, 8); //Add data FastBitConverter.GetBytes(connectPacket, 1, _connectId); //Send raw _peerListener.SendRaw(connectPacket, _remoteEndPoint); } internal bool ProcessConnectAccept(NetPacket packet) { if (_connectionState != ConnectionState.InProgress) return false; //check connection id if (BitConverter.ToInt64(packet.RawData, 1) != _connectId) { return false; } NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Received connection accept"); _lastPacketReceivedStart = DateTime.UtcNow; _connectionState = ConnectionState.Connected; return true; } private static PacketProperty SendOptionsToProperty(SendOptions options) { switch (options) { case SendOptions.ReliableUnordered: return PacketProperty.Reliable; case SendOptions.Sequenced: return PacketProperty.Sequenced; case SendOptions.ReliableOrdered: return PacketProperty.ReliableOrdered; default: return PacketProperty.Unreliable; } } public int GetMaxSinglePacketSize(SendOptions options) { return _mtu - NetPacket.GetHeaderSize(SendOptionsToProperty(options)); } public void Send(byte[] data, SendOptions options) { Send(data, 0, data.Length, options); } public void Send(NetDataWriter dataWriter, SendOptions options) { Send(dataWriter.Data, 0, dataWriter.Length, options); } public void Send(byte[] data, int start, int length, SendOptions options) { //Prepare PacketProperty property = SendOptionsToProperty(options); int headerSize = NetPacket.GetHeaderSize(property); //Check fragmentation if (length + headerSize > _mtu) { if (options == SendOptions.Sequenced || options == SendOptions.Unreliable) { throw new Exception("Unreliable packet size > allowed (" + (_mtu - headerSize) + ")"); } int packetFullSize = _mtu - headerSize; int packetDataSize = packetFullSize - NetConstants.FragmentHeaderSize; int fullPacketsCount = length / packetDataSize; int lastPacketSize = length % packetDataSize; int totalPackets = fullPacketsCount + (lastPacketSize == 0 ? 0 : 1); DebugWrite("MTU: {0}, HDR: {1}, PFS: {2}, PDS: {3}, FPC: {4}, LPS: {5}, TP: {6}", _mtu, headerSize, packetFullSize, packetDataSize, fullPacketsCount, lastPacketSize, totalPackets); if (totalPackets > ushort.MaxValue) { throw new Exception("Too many fragments: " + totalPackets + " > " + ushort.MaxValue); } for (ushort i = 0; i < fullPacketsCount; i++) { NetPacket p = GetPacketFromPool(property, packetFullSize); p.FragmentId = _fragmentId; p.FragmentPart = i; p.FragmentsTotal = (ushort)totalPackets; p.IsFragmented = true; p.PutData(data, i * packetDataSize, packetDataSize); SendPacket(p); } if (lastPacketSize > 0) { NetPacket p = GetPacketFromPool(property, lastPacketSize + NetConstants.FragmentHeaderSize); p.FragmentId = _fragmentId; p.FragmentPart = (ushort)fullPacketsCount; //last p.FragmentsTotal = (ushort)totalPackets; p.IsFragmented = true; p.PutData(data, fullPacketsCount * packetDataSize, lastPacketSize); SendPacket(p); } _fragmentId++; return; } //Else just send NetPacket packet = GetPacketFromPool(property, length); packet.PutData(data, start, length); SendPacket(packet); } private void CreateAndSend(PacketProperty property, ushort sequence) { NetPacket packet = GetPacketFromPool(property); packet.Sequence = sequence; SendPacket(packet); } //from user thread, our thread, or recv? private void SendPacket(NetPacket packet) { switch (packet.Property) { case PacketProperty.Reliable: DebugWrite("[RS]Packet reliable"); _reliableUnorderedChannel.AddToQueue(packet); break; case PacketProperty.Sequenced: DebugWrite("[RS]Packet sequenced"); _sequencedChannel.AddToQueue(packet); break; case PacketProperty.ReliableOrdered: DebugWrite("[RS]Packet reliable ordered"); _reliableOrderedChannel.AddToQueue(packet); break; case PacketProperty.Unreliable: DebugWrite("[RS]Packet simple"); _simpleChannel.AddToQueue(packet); break; case PacketProperty.MtuCheck: //Must check result for MTU fix if (!_peerListener.SendRaw(packet.RawData, 0, packet.RawData.Length, _remoteEndPoint)) { _finishMtu = true; } Recycle(packet); break; case PacketProperty.AckReliable: case PacketProperty.AckReliableOrdered: case PacketProperty.Ping: case PacketProperty.Pong: case PacketProperty.Disconnect: case PacketProperty.MtuOk: SendRawData(packet.RawData); Recycle(packet); break; default: throw new Exception("Unknown packet property: " + packet.Property); } } private void UpdateRoundTripTime(int roundTripTime) { //Calc average round trip time _rtt += roundTripTime; _rttCount++; _avgRtt = _rtt/_rttCount; //flowmode 0 = fastest //flowmode max = lowest if (_avgRtt < _peerListener.GetStartRtt(_currentFlowMode - 1)) { if (_currentFlowMode <= 0) { //Already maxed return; } _goodRttCount++; if (_goodRttCount > NetConstants.FlowIncreaseThreshold) { _goodRttCount = 0; _currentFlowMode--; DebugWrite("[PA]Increased flow speed, RTT: {0}, PPS: {1}", _avgRtt, _peerListener.GetPacketsPerSecond(_currentFlowMode)); } } else if(_avgRtt > _peerListener.GetStartRtt(_currentFlowMode)) { _goodRttCount = 0; if (_currentFlowMode < _peerListener.GetMaxFlowMode()) { _currentFlowMode++; DebugWrite("[PA]Decreased flow speed, RTT: {0}, PPS: {1}", _avgRtt, _peerListener.GetPacketsPerSecond(_currentFlowMode)); } } } [Conditional("DEBUG_MESSAGES")] internal void DebugWrite(string str, params object[] args) { NetUtils.DebugWrite(ConsoleColor.DarkGreen, str, args); } [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")] internal void DebugWriteForce(string str, params object[] args) { NetUtils.DebugWriteForce(ConsoleColor.DarkGreen, str, args); } internal NetPacket GetPacketFromPool(PacketProperty property = PacketProperty.Unreliable, int size=0, bool init=true) { NetPacket packet = null; lock (_packetPool) { if (_packetPool.Count > 0) { packet = _packetPool.Pop(); } } if(packet == null) { packet = new NetPacket(); } if(init) packet.Init(property, size); return packet; } internal void Recycle(NetPacket packet) { packet.RawData = null; lock (_packetPool) { _packetPool.Push(packet); } } internal void AddIncomingPacket(NetPacket p) { if (p.IsFragmented) { DebugWrite("Fragment. Id: {0}, Part: {1}, Total: {2}", p.FragmentId, p.FragmentPart, p.FragmentsTotal); //Get needed array from dictionary ushort packetFragId = p.FragmentId; IncomingFragments incomingFragments; if (!_holdedFragments.TryGetValue(packetFragId, out incomingFragments)) { incomingFragments = new IncomingFragments { Fragments = new NetPacket[p.FragmentsTotal] }; _holdedFragments.Add(packetFragId, incomingFragments); } //Cache var fragments = incomingFragments.Fragments; //Fill array fragments[p.FragmentPart] = p; //Increase received fragments count incomingFragments.ReceivedCount++; //Increase total size int dataOffset = p.GetHeaderSize() + NetConstants.FragmentHeaderSize; incomingFragments.TotalSize += p.RawData.Length - dataOffset; //Check for finish if (incomingFragments.ReceivedCount != fragments.Length) return; DebugWrite("Received all fragments!"); NetPacket resultingPacket = GetPacketFromPool(p.Property, incomingFragments.TotalSize); int resultingPacketOffset = resultingPacket.GetHeaderSize(); int firstFragmentSize = fragments[0].RawData.Length - dataOffset; for (int i = 0; i < incomingFragments.ReceivedCount; i++) { //Create resulting big packet int fragmentSize = fragments[i].RawData.Length - dataOffset; Buffer.BlockCopy( fragments[i].RawData, dataOffset, resultingPacket.RawData, resultingPacketOffset + firstFragmentSize * i, fragmentSize); //Free memory Recycle(fragments[i]); fragments[i] = null; } //Send to process _peerListener.ReceiveFromPeer(resultingPacket, _remoteEndPoint); //Clear memory Recycle(resultingPacket); _holdedFragments.Remove(packetFragId); } else //Just simple packet { _peerListener.ReceiveFromPeer(p, _remoteEndPoint); Recycle(p); } } private void ProcessMtuPacket(NetPacket packet) { if (packet.RawData.Length == 1 || packet.RawData[1] >= NetConstants.PossibleMtu.Length) return; //MTU auto increase if (packet.Property == PacketProperty.MtuCheck) { if (packet.RawData.Length != NetConstants.PossibleMtu[packet.RawData[1]]) { return; } _mtuCheckAttempts = 0; DebugWrite("MTU check. Resend: " + packet.RawData[1]); var mtuOkPacket = GetPacketFromPool(PacketProperty.MtuOk, 1); mtuOkPacket.RawData[1] = packet.RawData[1]; SendPacket(mtuOkPacket); } else if(packet.RawData[1] > _mtuIdx) //MtuOk { lock (_mtuMutex) { _mtuIdx = packet.RawData[1]; _mtu = NetConstants.PossibleMtu[_mtuIdx]; } //if maxed - finish. if (_mtuIdx == NetConstants.PossibleMtu.Length - 1) { _finishMtu = true; } DebugWrite("MTU ok. Increase to: " + _mtu); } } //Process incoming packet internal void ProcessPacket(NetPacket packet) { _lastPacketReceivedStart = DateTime.UtcNow; DebugWrite("[RR]PacketProperty: {0}", packet.Property); switch (packet.Property) { case PacketProperty.ConnectRequest: //response with connect long newId = BitConverter.ToInt64(packet.RawData, 1); if (newId > _connectId) { _connectId = newId; } DebugWrite("ConnectRequest LastId: {0}, NewId: {1}, EP: {2}", ConnectId, newId, _remoteEndPoint); SendConnectAccept(); Recycle(packet); break; case PacketProperty.Merged: int pos = NetConstants.HeaderSize; while (pos < packet.RawData.Length) { ushort size = BitConverter.ToUInt16(packet.RawData, pos); pos += 2; NetPacket mergedPacket = GetPacketFromPool(init: false); if (!mergedPacket.FromBytes(packet.RawData, pos, size)) { Recycle(packet); break; } pos += size; ProcessPacket(mergedPacket); } break; //If we get ping, send pong case PacketProperty.Ping: if (NetUtils.RelativeSequenceNumber(packet.Sequence, _remotePingSequence) < 0) { Recycle(packet); break; } DebugWrite("[PP]Ping receive, send pong"); _remotePingSequence = packet.Sequence; Recycle(packet); //send CreateAndSend(PacketProperty.Pong, _remotePingSequence); break; //If we get pong, calculate ping time and rtt case PacketProperty.Pong: if (NetUtils.RelativeSequenceNumber(packet.Sequence, _pingSequence) < 0) { Recycle(packet); break; } _pingSequence = packet.Sequence; int rtt = (int)(DateTime.UtcNow - _pingTimeStart).TotalMilliseconds; UpdateRoundTripTime(rtt); DebugWrite("[PP]Ping: {0}", rtt); Recycle(packet); break; //Process ack case PacketProperty.AckReliable: _reliableUnorderedChannel.ProcessAck(packet); Recycle(packet); break; case PacketProperty.AckReliableOrdered: _reliableOrderedChannel.ProcessAck(packet); Recycle(packet); break; //Process in order packets case PacketProperty.Sequenced: _sequencedChannel.ProcessPacket(packet); break; case PacketProperty.Reliable: _reliableUnorderedChannel.ProcessPacket(packet); break; case PacketProperty.ReliableOrdered: _reliableOrderedChannel.ProcessPacket(packet); break; //Simple packet without acks case PacketProperty.Unreliable: AddIncomingPacket(packet); return; case PacketProperty.MtuCheck: case PacketProperty.MtuOk: ProcessMtuPacket(packet); break; default: DebugWriteForce("Error! Unexpected packet type: " + packet.Property); break; } } internal void SendRawData(byte[] data) { //2 - merge byte + minimal packet size + datalen(ushort) if (_peerListener.MergeEnabled && _mergePos + data.Length + NetConstants.HeaderSize*2 + 2 < _mtu) { FastBitConverter.GetBytes(_mergeData.RawData, _mergePos + NetConstants.HeaderSize, (ushort)data.Length); Buffer.BlockCopy(data, 0, _mergeData.RawData, _mergePos + NetConstants.HeaderSize + 2, data.Length); _mergePos += data.Length + 2; _mergeCount++; //DebugWriteForce("Merged: " + _mergePos + "/" + (_mtu - 2) + ", count: " + _mergeCount); } else { _peerListener.SendRaw(data, 0, data.Length, _remoteEndPoint); } } internal void Update(int deltaTime) { if (_connectionState == ConnectionState.Disconnected) { return; } if (_connectionState == ConnectionState.InProgress) { _connectTimer += deltaTime; if (_connectTimer > _peerListener.ReconnectDelay) { _connectTimer = 0; _connectAttempts++; if (_connectAttempts > _peerListener.MaxConnectAttempts) { _connectionState = ConnectionState.Disconnected; return; } //else send connect again SendConnectRequest(); } return; } //Get current flow mode int maxSendPacketsCount = _peerListener.GetPacketsPerSecond(_currentFlowMode); int currentMaxSend; if (maxSendPacketsCount > 0) { int availableSendPacketsCount = maxSendPacketsCount - _sendedPacketsCount; currentMaxSend = Math.Min(availableSendPacketsCount, (maxSendPacketsCount*deltaTime)/NetConstants.FlowUpdateTime); } else { currentMaxSend = int.MaxValue; } DebugWrite("[UPDATE]Delta: {0}ms, MaxSend: {1}", deltaTime, currentMaxSend); //Pending acks _reliableOrderedChannel.SendAcks(); _reliableUnorderedChannel.SendAcks(); //Pending send int currentSended = 0; while (currentSended < currentMaxSend) { //Get one of packets if (_reliableOrderedChannel.SendNextPacket() || _reliableUnorderedChannel.SendNextPacket() || _sequencedChannel.SendNextPacket() || _simpleChannel.SendNextPacket()) { currentSended++; } else { //no outgoing packets break; } } //Increase counter _sendedPacketsCount += currentSended; //ResetFlowTimer _flowTimer += deltaTime; if (_flowTimer >= NetConstants.FlowUpdateTime) { DebugWrite("[UPDATE]Reset flow timer, _sendedPackets - {0}", _sendedPacketsCount); _sendedPacketsCount = 0; _flowTimer = 0; } //Send ping _pingSendTimer += deltaTime; if (_pingSendTimer >= _peerListener.PingInterval) { DebugWrite("[PP] Send ping..."); //reset timer _pingSendTimer = 0; //send ping CreateAndSend(PacketProperty.Ping, _pingSequence); //reset timer _pingTimeStart = DateTime.UtcNow; } //RTT - round trip time _rttResetTimer += deltaTime; if (_rttResetTimer >= RttResetDelay) { _rttResetTimer = 0; //Rtt update _rtt = _avgRtt; _ping = _avgRtt; _peerListener.ConnectionLatencyUpdated(this, _ping); _rttCount = 1; } //MTU - Maximum transmission unit if (!_finishMtu) { _mtuCheckTimer += deltaTime; if (_mtuCheckTimer >= MtuCheckDelay) { _mtuCheckTimer = 0; _mtuCheckAttempts++; if (_mtuCheckAttempts >= MaxMtuCheckAttempts) { _finishMtu = true; } else { lock (_mtuMutex) { //Send increased packet if (_mtuIdx < NetConstants.PossibleMtu.Length - 1) { int newMtu = NetConstants.PossibleMtu[_mtuIdx + 1] - NetConstants.HeaderSize; var p = GetPacketFromPool(PacketProperty.MtuCheck, newMtu); p.RawData[1] = (byte)(_mtuIdx + 1); SendPacket(p); } } } } } //MTU - end //Flush if (_mergePos > 0) { if (_mergeCount > 1) { DebugWrite("Send merged: " + _mergePos + ", count: " + _mergeCount); _peerListener.SendRaw(_mergeData.RawData, 0, NetConstants.HeaderSize + _mergePos, _remoteEndPoint); } else { //Send without length information and merging _peerListener.SendRaw(_mergeData.RawData, NetConstants.HeaderSize + 2, _mergePos - 2, _remoteEndPoint); } _mergePos = 0; _mergeCount = 0; } } } }
using System.Collections.Generic; using Cake.Common.Tests.Fixtures.Tools; using Cake.Common.Tools.Fixie; using Cake.Core; using Cake.Core.IO; using NSubstitute; using Xunit; namespace Cake.Common.Tests.Unit.Tools.Fixie { public sealed class FixieRunnerTests { public sealed class TheRunMethod { [Fact] public void Should_Throw_If_Assembly_Paths_Are_Null() { // Given var fixture = new FixieRunnerFixture(); fixture.AssemblyPaths = null; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsArgumentNullException(result, "assemblyPaths"); } [Fact] public void Should_Throw_If_Fixie_Runner_Was_Not_Found() { // Given var fixture = new FixieRunnerFixture(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Could not locate executable.", result.Message); } [Theory] [InlineData("C:/Fixie/Fixie.Console.exe", "C:/Fixie/Fixie.Console.exe")] [InlineData("./tools/Fixie/Fixie.Console.exe", "/Working/tools/Fixie/Fixie.Console.exe")] public void Should_Use_Fixie_Runner_From_Tool_Path_If_Provided(string toolPath, string expected) { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.ToolPath.FullPath); } [Fact] public void Should_Find_Fixie_Runner_If_Tool_Path_Not_Provided() { // Given var fixture = new FixieRunnerFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/Fixie.Console.exe", result.ToolPath.FullPath); } [Fact] public void Should_Use_Provided_Assembly_Path_In_Process_Arguments() { // Given var fixture = new FixieRunnerFixture(); // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\"", result.Args); } [Fact] public void Should_Use_Provided_Assembly_Paths_In_Process_Arguments() { // Given var fixture = new FixieRunnerFixture(); fixture.AssemblyPaths.Clear(); fixture.AssemblyPaths.Add("./Test1.dll"); fixture.AssemblyPaths.Add("./Test2.dll"); // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" \"/Working/Test2.dll\"", result.Args); } [Fact] public void Should_Set_Working_Directory() { // Given var fixture = new FixieRunnerFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working", result.Process.WorkingDirectory.FullPath); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new FixieRunnerFixture(); fixture.GivenProcessCannotStart(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Process was not started.", result.Message); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new FixieRunnerFixture(); fixture.GivenProcessExitsWithCode(1); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Process returned an error.", result.Message); } [Fact] public void Should_Set_NUnitXml_Output_File() { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.NUnitXml = "nunit-style-results.xml"; // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" " + "--NUnitXml \"/Working/nunit-style-results.xml\"", result.Args); } [Fact] public void Should_Set_xUnitXml_Output_File() { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.XUnitXml = "xunit-results.xml"; // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" " + "--xUnitXml \"/Working/xunit-results.xml\"", result.Args); } [Theory] [InlineData(true, "on", "\"/Working/Test1.dll\" --TeamCity on")] [InlineData(false, "off", "\"/Working/Test1.dll\" --TeamCity off")] public void Should_Set_TeamCity_Value(bool teamCityOutput, string teamCityValue, string expected) { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.TeamCity = teamCityOutput; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Fact] public void Should_Set_Custom_Options() { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.WithOption("--include", "CategoryA"); fixture.Settings.WithOption("--include", "CategoryB"); // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" " + "--include CategoryA " + "--include CategoryB", result.Args); } [Fact] public void Should_Set_Multiple_Options() { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.WithOption("--type", "fast"); fixture.Settings.WithOption("--include", "CategoryA", "CategoryB"); fixture.Settings.WithOption("--output", "fixie-log.txt"); // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" --type fast " + "--include CategoryA --include CategoryB " + "--output fixie-log.txt", result.Args); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Globalization; using mshtml; using OpenLiveWriter.Mshtml; namespace OpenLiveWriter.SpellChecker { //used to store the highlight segments in a post for tracking spelling changes public class HighlightSegmentTracker { SortedList list; private class SegmentDef { public IHighlightSegmentRaw segment; public IMarkupPointerRaw endPtr; public IMarkupPointerRaw startPtr; public string word; public SegmentDef(IHighlightSegmentRaw seg, IMarkupPointerRaw start, IMarkupPointerRaw end, string wd) { segment = seg; startPtr = start; endPtr = end; word = wd; } } public class MatchingSegment { public IHighlightSegmentRaw _segment; public IMarkupPointerRaw _pointer; public MatchingSegment(IHighlightSegmentRaw seg, IMarkupPointerRaw pointer) { _segment = seg; _pointer = pointer; } } //this needs to be on a post by post basis public HighlightSegmentTracker() { list = new SortedList(new MarkupPointerComparer()); } //adds a segment to the list //used when a misspelled word is found public void AddSegment(IHighlightSegmentRaw segment, string wordHere, IMarkupServicesRaw markupServices) { IMarkupPointerRaw start, end; markupServices.CreateMarkupPointer(out start); markupServices.CreateMarkupPointer(out end); segment.GetPointers(start, end); if (!list.ContainsKey(start)) list.Add(start, new SegmentDef(segment, start, end, wordHere)); } //find all the segments in a specific range //used to clear out a section when it is getting rechecked //need to expand selection from these bounds out around full words public IHighlightSegmentRaw[] GetSegments(IMarkupPointerRaw start, IMarkupPointerRaw end) { if (list.Count == 0) return null; int firstSegmentInd = -1; int lastSegmentInd = list.Count; bool test; //find the first segment after the start pointer do { firstSegmentInd++; //check if we have gone through the whole selection if (firstSegmentInd >= lastSegmentInd) return null; SegmentDef x = (SegmentDef) list.GetByIndex(firstSegmentInd); start.IsRightOf(x.startPtr, out test); } while (test); do { lastSegmentInd--; //check if we have gone through the whole selection if (lastSegmentInd < firstSegmentInd) return null; SegmentDef x = (SegmentDef) list.GetByIndex(lastSegmentInd); end.IsLeftOf(x.startPtr, out test); } while (test); return Subarray(firstSegmentInd, lastSegmentInd); } public IHighlightSegmentRaw[] ClearAllSegments() { return Subarray(0, list.Count - 1); } public delegate bool CheckWordSpelling(string word); //find all the segments with a specific misspelled word //used to clear for ignore all, add to dictionary public MatchingSegment[] GetSegments(string word, CheckWordSpelling checkSpelling) { ArrayList segments = new ArrayList(); for (int i = 0; i < list.Count; i++) { SegmentDef x = (SegmentDef) list.GetByIndex(i); //TODO: Change with new cultures added!!! if (0 == String.Compare(word, x.word, true, CultureInfo.InvariantCulture)) { //check spelling--capitalized word may be ok, but not mixed case, etc. if (!checkSpelling(x.word)) { segments.Add(new MatchingSegment(x.segment, x.startPtr)); } } } return (MatchingSegment[])segments.ToArray(typeof (MatchingSegment)); } public void RemoveSegment(IMarkupPointerRaw pointer) { list.Remove(pointer); } public MisspelledWordInfo FindSegment(MshtmlMarkupServices markupServices, IMarkupPointerRaw current) { //binary search int start = 0; int end = list.Count - 1; int i = Middle(start, end); while (-1 != i) { SegmentDef x = (SegmentDef)list.GetByIndex(i); bool startTest; current.IsRightOfOrEqualTo(x.startPtr, out startTest); if (startTest) { bool endTest; current.IsLeftOfOrEqualTo(x.endPtr, out endTest); if (endTest) { MarkupPointer pStart = markupServices.CreateMarkupPointer(x.startPtr); MarkupPointer pEnd = markupServices.CreateMarkupPointer(x.endPtr); MarkupRange range = markupServices.CreateMarkupRange(pStart, pEnd); //this could be a "phantom" range...no more content due to uncommitted damage or other reasons //if it is phantom, remove it from the tracker and return null if (range.Text == null) { list.RemoveAt(i); return null; } return new MisspelledWordInfo(range, x.word); } start = i + 1; } else { end = i - 1; } i = Middle(start, end); } return null; } private int Middle(int start, int end) { if (start <= end) { return (int)Math.Floor(Convert.ToDouble((start + end)/2)); } return -1; } private IHighlightSegmentRaw[] Subarray(int start, int end) { int count = end - start + 1; IHighlightSegmentRaw[] segments = new IHighlightSegmentRaw[count]; //fill in array by removing from the list starting at the end, so that // deleting from the list doesn't change the other indices for (int i = end; i >= start; i--) { segments[--count] = ((SegmentDef) list.GetByIndex(i)).segment; list.RemoveAt(i); } return segments; } public void Clear() { list.Clear(); } } internal class MarkupPointerComparer : IComparer, System.Collections.Generic.IComparer<IMarkupPointerRaw> { public int Compare(object x, object y) { IMarkupPointerRaw a = (IMarkupPointerRaw) x; IMarkupPointerRaw b = (IMarkupPointerRaw) y; return Compare(a, b); } public int Compare(IMarkupPointerRaw a, IMarkupPointerRaw b) { bool test; a.IsEqualTo(b, out test); if (test) return 0; a.IsLeftOf(b, out test); if (test) return -1; return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Xml; using System.Xml.Serialization; using System.Xml.Schema; using System.Data.Common; using System.Diagnostics; using System.Text; using System.Reflection; namespace System.Data.SqlTypes { [XmlSchemaProvider("GetXsdType")] public sealed class SqlXml : INullable, IXmlSerializable { private static readonly Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader> s_sqlReaderDelegate = CreateSqlReaderDelegate(); private static readonly XmlReaderSettings s_defaultXmlReaderSettings = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment }; private static readonly XmlReaderSettings s_defaultXmlReaderSettingsCloseInput = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true }; private static MethodInfo s_createSqlReaderMethodInfo; private MethodInfo _createSqlReaderMethodInfo; private bool _fNotNull; // false if null, the default ctor (plain 0) will make it Null private Stream _stream; private bool _firstCreateReader; public SqlXml() { SetNull(); } // constructor // construct a Null private SqlXml(bool fNull) { SetNull(); } public SqlXml(XmlReader value) { // whoever pass in the XmlReader is responsible for closing it if (value == null) { SetNull(); } else { _fNotNull = true; _firstCreateReader = true; _stream = CreateMemoryStreamFromXmlReader(value); } } public SqlXml(Stream value) { // whoever pass in the stream is responsible for closing it // similar to SqlBytes implementation if (value == null) { SetNull(); } else { _firstCreateReader = true; _fNotNull = true; _stream = value; } } public XmlReader CreateReader() { if (IsNull) { throw new SqlNullValueException(); } SqlXmlStreamWrapper stream = new SqlXmlStreamWrapper(_stream); // if it is the first time we create reader and stream does not support CanSeek, no need to reset position if ((!_firstCreateReader || stream.CanSeek) && stream.Position != 0) { stream.Seek(0, SeekOrigin.Begin); } // NOTE: Maintaining createSqlReaderMethodInfo private field member to preserve the serialization of the class if (_createSqlReaderMethodInfo == null) { _createSqlReaderMethodInfo = CreateSqlReaderMethodInfo; } Debug.Assert(_createSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); XmlReader r = CreateSqlXmlReader(stream); _firstCreateReader = false; return r; } internal static XmlReader CreateSqlXmlReader(Stream stream, bool closeInput = false, bool throwTargetInvocationExceptions = false) { // Call the internal delegate XmlReaderSettings settingsToUse = closeInput ? s_defaultXmlReaderSettingsCloseInput : s_defaultXmlReaderSettings; try { return s_sqlReaderDelegate(stream, settingsToUse, null); } // For particular callers, we need to wrap all exceptions inside a TargetInvocationException to simulate calling CreateSqlReader via MethodInfo.Invoke catch (Exception ex) { if ((!throwTargetInvocationExceptions) || (!ADP.IsCatchableExceptionType(ex))) { throw; } else { throw new TargetInvocationException(ex); } } } private static Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader> CreateSqlReaderDelegate() { Debug.Assert(CreateSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); return (Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader>)CreateSqlReaderMethodInfo.CreateDelegate(typeof(Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader>)); } private static MethodInfo CreateSqlReaderMethodInfo { get { if (s_createSqlReaderMethodInfo == null) { s_createSqlReaderMethodInfo = typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic); } return s_createSqlReaderMethodInfo; } } // INullable public bool IsNull { get { return !_fNotNull; } } public string Value { get { if (IsNull) throw new SqlNullValueException(); StringWriter sw = new StringWriter((System.IFormatProvider)null); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; // don't close the memory stream writerSettings.ConformanceLevel = ConformanceLevel.Fragment; XmlWriter ww = XmlWriter.Create(sw, writerSettings); XmlReader reader = CreateReader(); if (reader.ReadState == ReadState.Initial) reader.Read(); while (!reader.EOF) { ww.WriteNode(reader, true); } ww.Flush(); return sw.ToString(); } } public static SqlXml Null { get { return new SqlXml(true); } } private void SetNull() { _fNotNull = false; _stream = null; _firstCreateReader = true; } private Stream CreateMemoryStreamFromXmlReader(XmlReader reader) { XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; // don't close the memory stream writerSettings.ConformanceLevel = ConformanceLevel.Fragment; writerSettings.Encoding = Encoding.GetEncoding("utf-16"); writerSettings.OmitXmlDeclaration = true; MemoryStream writerStream = new MemoryStream(); XmlWriter ww = XmlWriter.Create(writerStream, writerSettings); if (reader.ReadState == ReadState.Closed) throw new InvalidOperationException(SQLResource.ClosedXmlReaderMessage); if (reader.ReadState == ReadState.Initial) reader.Read(); while (!reader.EOF) { ww.WriteNode(reader, true); } ww.Flush(); // set the stream to the beginning writerStream.Seek(0, SeekOrigin.Begin); return writerStream; } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader r) { string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadInnerXml(); SetNull(); } else { _fNotNull = true; _firstCreateReader = true; _stream = new MemoryStream(); StreamWriter sw = new StreamWriter(_stream); sw.Write(r.ReadInnerXml()); sw.Flush(); if (_stream.CanSeek) _stream.Seek(0, SeekOrigin.Begin); } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { // Instead of the WriteRaw use the WriteNode. As Tds sends a binary stream - Create a XmlReader to convert // get the Xml string value from the binary and call WriteNode to pass that out to the XmlWriter. XmlReader reader = CreateReader(); if (reader.ReadState == ReadState.Initial) reader.Read(); while (!reader.EOF) { writer.WriteNode(reader, true); } } writer.Flush(); } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("anyType", XmlSchema.Namespace); } } // SqlXml // two purposes for this class // 1) keep its internal position so one reader positions on the orginial stream // will not interface with the other // 2) when xmlreader calls close, do not close the orginial stream // internal sealed class SqlXmlStreamWrapper : Stream { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private readonly Stream _stream; private long _lPosition; private bool _isClosed; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal SqlXmlStreamWrapper(Stream stream) { _stream = stream; Debug.Assert(_stream != null, "stream can not be null"); _lPosition = 0; _isClosed = false; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // Always can read/write/seek, unless stream is null, // which means the stream has been closed. public override bool CanRead { get { if (IsStreamClosed()) return false; return _stream.CanRead; } } public override bool CanSeek { get { if (IsStreamClosed()) return false; return _stream.CanSeek; } } public override bool CanWrite { get { if (IsStreamClosed()) return false; return _stream.CanWrite; } } public override long Length { get { ThrowIfStreamClosed("get_Length"); ThrowIfStreamCannotSeek("get_Length"); return _stream.Length; } } public override long Position { get { ThrowIfStreamClosed("get_Position"); ThrowIfStreamCannotSeek("get_Position"); return _lPosition; } set { ThrowIfStreamClosed("set_Position"); ThrowIfStreamCannotSeek("set_Position"); if (value < 0 || value > _stream.Length) throw new ArgumentOutOfRangeException(nameof(value)); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { long lPosition = 0; ThrowIfStreamClosed(nameof(Seek)); ThrowIfStreamCannotSeek(nameof(Seek)); switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _stream.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _stream.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _stream.Length + offset; if (lPosition < 0 || lPosition > _stream.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = lPosition; break; default: throw ADP.InvalidSeekOrigin(nameof(offset)); } return _lPosition; } public override int Read(byte[] buffer, int offset, int count) { ThrowIfStreamClosed(nameof(Read)); ThrowIfStreamCannotRead(nameof(Read)); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); int iBytesRead = _stream.Read(buffer, offset, count); _lPosition += iBytesRead; return iBytesRead; } public override void Write(byte[] buffer, int offset, int count) { ThrowIfStreamClosed(nameof(Write)); ThrowIfStreamCannotWrite(nameof(Write)); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); _stream.Write(buffer, offset, count); _lPosition += count; } public override int ReadByte() { ThrowIfStreamClosed(nameof(ReadByte)); ThrowIfStreamCannotRead(nameof(ReadByte)); // If at the end of stream, return -1, rather than call ReadByte, // which will throw exception. This is the behavior for Stream. // if (_stream.CanSeek && _lPosition >= _stream.Length) return -1; if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); int ret = _stream.ReadByte(); _lPosition++; return ret; } public override void WriteByte(byte value) { ThrowIfStreamClosed(nameof(WriteByte)); ThrowIfStreamCannotWrite(nameof(WriteByte)); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); _stream.WriteByte(value); _lPosition++; } public override void SetLength(long value) { ThrowIfStreamClosed(nameof(SetLength)); ThrowIfStreamCannotSeek(nameof(SetLength)); _stream.SetLength(value); if (_lPosition > value) _lPosition = value; } public override void Flush() { if (_stream != null) _stream.Flush(); } protected override void Dispose(bool disposing) { try { // does not close the underline stream but mark itself as closed _isClosed = true; } finally { base.Dispose(disposing); } } private void ThrowIfStreamCannotSeek(string method) { if (!_stream.CanSeek) throw new NotSupportedException(SQLResource.InvalidOpStreamNonSeekable(method)); } private void ThrowIfStreamCannotRead(string method) { if (!_stream.CanRead) throw new NotSupportedException(SQLResource.InvalidOpStreamNonReadable(method)); } private void ThrowIfStreamCannotWrite(string method) { if (!_stream.CanWrite) throw new NotSupportedException(SQLResource.InvalidOpStreamNonWritable(method)); } private void ThrowIfStreamClosed(string method) { if (IsStreamClosed()) throw new ObjectDisposedException(SQLResource.InvalidOpStreamClosed(method)); } private bool IsStreamClosed() { // Check the .CanRead and .CanWrite and .CanSeek properties to make sure stream is really closed if (_isClosed || _stream == null || (!_stream.CanRead && !_stream.CanWrite && !_stream.CanSeek)) return true; else return false; } } // class SqlXmlStreamWrapper }
/* -- ============================================= -- Author: Jonathan F. Minond -- Create date: April 2006 -- Description: Item Type is the basic type that all type definitions will inherit from -- ============================================= */ using System; using System.ComponentModel; using System.Collections.Generic; using System.Globalization; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; namespace Content.API.Types { [Serializable] public class ItemType { #region Fields private int _typeID = 0; private string _title = string.Empty; private string _description = string.Empty; private Guid _typeGUID = Guid.Empty; private bool _GUIDSET = false; private ItemBaseType _itemBaseType = ItemBaseType.User; /// <summary> /// The xml document is used for loading and storing, while the type is an object /// the settings will be handled by the list. /// upon item initialiazation the settings will be put into _typeSettings /// </summary> private XmlDocument _typeSettingXML = null; private Settings _typeSettings = new Settings(); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:ItemType"/> class. /// </summary> public ItemType() { } /// <summary> /// Initializes a new instance of the <see cref="T:ItemType"/> class. /// </summary> /// <param name="typeGuid">The type GUID.</param> public ItemType(Guid typeGuid) { _typeGUID = typeGuid; LoadItemByGUID(); } /// <summary> /// Initializes a new instance of the <see cref="T:ItemType"/> class. /// </summary> /// <param name="typeID">The type ID.</param> public ItemType(int typeID) { // TODO: GetGUID //_typeGUID = typeGuid; LoadItemByGUID(); } /// <summary> /// Initializes a new instance of the <see cref="T:ContentItemType"/> class. /// </summary> /// <param name="typeGuid">The type GUID.</param> /// <param name="title">The title.</param> /// <param name="description">The description.</param> /// <param name="xmlSettings">The XML settings.</param> /// <param name="baseType">Type of the base.</param> public ItemType(Guid typeGuid, string title, string description, string xmlSettings, int baseType) { _typeGUID = typeGuid; LoadItemByGUID(); _itemBaseType = (ItemBaseType)baseType; FetchTypeSettings(xmlSettings); // TODO: Convert settings to list, and clear xml document. //_typeID = typeID; _title = title; _description = description; } /// <summary> /// Initializes a new instance of the <see cref="T:ContentItemType"/> class. /// </summary> /// <param name="typeGuid">The type GUID.</param> /// <param name="typeID">The type ID.</param> /// <param name="title">The title.</param> /// <param name="description">The description.</param> /// <param name="xmlSettings">The XML settings.</param> /// <param name="baseType">Type of the base.</param> public ItemType(Guid typeGuid, int typeID,string title, string description, string xmlSettings, int baseType) { LoadItemByGUID(); _itemBaseType = (ItemBaseType)baseType; FetchTypeSettings(xmlSettings); // TODO: Convert settings to list, and clear xml document. _typeID = typeID; _typeGUID = typeGuid; _title = title; _description = description; } /// <summary> /// Initializes a new instance of the <see cref="T:ContentItemType"/> class. /// </summary> /// <param name="typeID">The type ID.</param> /// <param name="title">The title.</param> /// <param name="description">The description.</param> /// <param name="xmlSettings">The XML settings.</param> /// <param name="baseType">Type of the base.</param> public ItemType(int typeID, string title, string description, string xmlSettings, int baseType) { // TODO: GetGUID //_typeGUID = typeGuid; LoadItemByGUID(); _itemBaseType = (ItemBaseType)baseType; FetchTypeSettings(xmlSettings); // TODO: Convert settings to list, and clear xml document. _typeID = typeID; _title = title; _description = description; } #endregion #region Public Properties /// <summary> /// Gets the type ID. /// Note, this is an applciation local ID, and you may want to consider using TypeGUID to ensure /// cross portal / application uniqueness. /// </summary> /// <value>The type ID.</value> [Bindable(true)] public int TypeID { get { return _typeID; } } /// <summary> /// Gets the title. /// </summary> /// <value>The title.</value> [Bindable(true)] public string Title { get { return _title; } set { _title = value; } } /// <summary> /// Gets the description. /// </summary> /// <value>The description.</value> [Bindable(true)] public string Description { get { return _description; } set { _description = value; } } /// <summary> /// Gets or sets the type GUID. /// </summary> /// <value>The type GUID.</value> public Guid TypeGUID { get { return _typeGUID; } set { if (_GUIDSET == false) { _typeGUID = value; _GUIDSET = true; } else throw new Exception("Item Type GUID cannot be changed once it has been set."); } } /// <summary> /// Gets the type settings. /// </summary> /// <value>The type settings.</value> [Bindable(true)] public Settings TypeSettings { get { return _typeSettings; } } /// <summary> /// Gets or sets the type of the base. /// </summary> /// <value>The type of the base.</value> [Bindable(true)] public ItemBaseType BaseType { get { return _itemBaseType; } set { _itemBaseType = value; } } #endregion /// <summary> /// Loads the item by GUID. /// </summary> protected virtual void LoadItemByGUID() { throw new System.NotImplementedException(); } private List<string> _SettingKeys; /// <summary> /// Gets the item setting keys. /// </summary> /// <value>The item setting keys.</value> public List<string> SettingKeys { get { return _SettingKeys; } } /// <summary> /// Fetches the type settings. /// </summary> /// <param name="xmlSettings">The XML settings.</param> protected virtual void FetchTypeSettings(string xmlSettings) { throw new System.NotImplementedException(); // TODO: This is an important method :-) //TH XmlSerializer serializer = new XmlSerializer(typeof(Settings)); using (StringReader reader = new StringReader(xmlSettings)) { _typeSettings = serializer.Deserialize(reader) as Settings; } } } }
// // System.IO.StringWriter // // Authors: // Marcin Szczepanski (marcins@zipworld.com.au) // Ben Maurer <bmaurer@users.sourceforge.net> // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2004 Novell (http://www.novell.com) // using NUnit.Framework; using System.IO; using System; using System.Globalization; using System.Text; namespace MonoTests.System.IO { [TestFixture] public class StringWriterTest : Assertion { public void TestConstructors() { StringBuilder sb = new StringBuilder("Test String"); StringWriter writer = new StringWriter( sb ); AssertEquals( sb, writer.GetStringBuilder() ); } public void TestCultureInfoConstructor() { StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); AssertNotNull( writer.GetStringBuilder() ); AssertEquals( String.Empty, writer.ToString() ); writer.Write( 'A' ); AssertEquals( "A", writer.ToString() ); writer.Write( " foo" ); AssertEquals( "A foo", writer.ToString() ); char[] testBuffer = "Test String".ToCharArray(); writer.Write( testBuffer, 0, 4 ); AssertEquals( "A fooTest", writer.ToString() ); writer.Write( testBuffer, 5, 6 ); AssertEquals( "A fooTestString", writer.ToString() ); writer = new StringWriter(CultureInfo.InvariantCulture); writer.Write(null as string); AssertEquals( "", writer.ToString() ); } public void TestWrite() { StringWriter writer = new StringWriter(); AssertEquals( String.Empty, writer.ToString() ); writer.Write( 'A' ); AssertEquals( "A", writer.ToString() ); writer.Write( " foo" ); AssertEquals( "A foo", writer.ToString() ); char[] testBuffer = "Test String".ToCharArray(); writer.Write( testBuffer, 0, 4 ); AssertEquals( "A fooTest", writer.ToString() ); writer.Write( testBuffer, 5, 6 ); AssertEquals( "A fooTestString", writer.ToString() ); writer = new StringWriter (); writer.Write(null as string); AssertEquals( "", writer.ToString() ); } public void TestNewLine() { StringWriter writer = new StringWriter(); writer.NewLine = "\n\r"; AssertEquals ("NewLine 1", "\n\r", writer.NewLine); writer.WriteLine ("first"); AssertEquals ("NewLine 2", "first\n\r", writer.ToString()); writer.NewLine = "\n"; AssertEquals ("NewLine 3", "first\n\r", writer.ToString()); writer.WriteLine ("second"); AssertEquals ("NewLine 4", "first\n\rsecond\n", writer.ToString()); } public void TestWriteLine() { StringWriter writer = new StringWriter(); writer.NewLine = "\n"; writer.WriteLine ("first line"); writer.WriteLine ("second line"); AssertEquals ("WriteLine 1", "first line\nsecond line\n", writer.ToString ()); writer.Close (); } public void TestGetStringBuilder() { StringWriter writer = new StringWriter (); writer.Write ("line"); StringBuilder builder = writer.GetStringBuilder (); builder.Append (12); AssertEquals ("GetStringBuilder 1", "line12", writer.ToString ()); writer.Write ("test"); AssertEquals ("GetStringBuilder 2", "line12test", builder.ToString ()); } public void TestClose() { StringWriter writer = new StringWriter (); writer.Write ("mono"); writer.Close (); try { writer.Write ("kicks ass"); Fail ("Close 1"); } catch (Exception e) { AssertEquals ("Close 2", typeof (ObjectDisposedException), e.GetType ()); } AssertEquals ("Close 3", "mono", writer.ToString ()); writer.Flush (); StringBuilder builder = writer.GetStringBuilder (); AssertEquals ("Close 4", "mono", builder.ToString ()); builder.Append (" kicks ass"); AssertEquals ("Close 5", "mono kicks ass", writer.ToString ()); } public void TestExceptions () { try { StringWriter writer = new StringWriter (null as StringBuilder); Fail(); } catch (Exception e) { AssertEquals ("Exceptions 1", typeof (ArgumentNullException), e.GetType ()); } { StringWriter writer = new StringWriter (null as IFormatProvider); } try { StringWriter writer = new StringWriter (null as StringBuilder, null as IFormatProvider); Fail (); } catch (Exception e) { AssertEquals ("Exceptions 2", typeof (ArgumentNullException), e.GetType ()); } } [Test] // strangely this is accepted [ExpectedException (typeof (ArgumentNullException))] public void WriteString_Null () { StringWriter writer = new StringWriter (); writer.Write (null as String); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void WriteChars_Null () { StringWriter writer = new StringWriter (); writer.Write (null, 0, 0); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void WriteChars_IndexNegative () { char[] c = new char [2] { 'a', 'b' }; StringWriter writer = new StringWriter (); writer.Write (c, -1, 0); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void WriteChars_CountNegative () { char[] c = new char [2] { 'a', 'b' }; StringWriter writer = new StringWriter (); writer.Write (c, 0, -1); } [Test] [ExpectedException (typeof (ArgumentException))] public void WriteChars_IndexOverflow () { char[] c = new char [2] { 'a', 'b' }; StringWriter writer = new StringWriter (); writer.Write (c, Int32.MaxValue, 0); } [Test] [ExpectedException (typeof (ArgumentException))] public void WriteChars_CountOverflow () { char[] c = new char [2] { 'a', 'b' }; StringWriter writer = new StringWriter (); writer.Write (c, 0, Int32.MaxValue); } [Test] public void Disposed_Encoding () { StringWriter writer = new StringWriter (); writer.Close (); AssertNotNull ("Disposed-Encoding", writer.Encoding); } [Test] public void Disposed_DoubleClose () { StringWriter writer = new StringWriter (); writer.Close (); writer.Close (); } [Test] public void Disposed_GetStringBuilder () { StringWriter writer = new StringWriter (); writer.Write ("Mono"); writer.Close (); AssertNotNull ("Disposed-GetStringBuilder", writer.GetStringBuilder ()); } [Test] public void Disposed_ToString () { StringWriter writer = new StringWriter (); writer.Write ("Mono"); writer.Close (); AssertEquals ("Disposed-ToString", "Mono", writer.ToString ()); } [Test] [ExpectedException (typeof (ObjectDisposedException))] public void Disposed_WriteChar () { StringWriter writer = new StringWriter (); writer.Close (); writer.Write ('c'); } [Test] [ExpectedException (typeof (ObjectDisposedException))] public void Disposed_WriteString () { StringWriter writer = new StringWriter (); writer.Close (); writer.Write ("mono"); } [Test] [ExpectedException (typeof (ObjectDisposedException))] public void Disposed_WriteChars () { char[] c = new char [2] { 'a', 'b' }; StringWriter writer = new StringWriter (); writer.Close (); writer.Write (c, 0, 2); } } }
// ZipConstants.cs // ------------------------------------------------------------------ // // Copyright (c) 2006, 2007, 2008, 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-August-27 23:22:32> // // ------------------------------------------------------------------ // // This module defines a few constants that are used in the project. // // ------------------------------------------------------------------ using System; using System.IO; namespace Ionic.Zip { static class ZipConstants { public const UInt32 PackedToRemovableMedia = 0x30304b50; public const UInt32 Zip64EndOfCentralDirectoryRecordSignature = 0x06064b50; public const UInt32 Zip64EndOfCentralDirectoryLocatorSignature = 0x07064b50; public const UInt32 EndOfCentralDirectorySignature = 0x06054b50; public const int ZipEntrySignature = 0x04034b50; public const int ZipEntryDataDescriptorSignature = 0x08074b50; public const int SplitArchiveSignature = 0x08074b50; public const int ZipDirEntrySignature = 0x02014b50; // These are dictated by the Zip Spec.See APPNOTE.txt public const int AesKeySize = 192; // 128, 192, 256 public const int AesBlockSize = 128; // ??? public const UInt16 AesAlgId128 = 0x660E; public const UInt16 AesAlgId192 = 0x660F; public const UInt16 AesAlgId256 = 0x6610; } /// <summary> /// An enum that provides the various encryption algorithms supported by this /// library. /// </summary> /// /// <remarks> /// /// <para> /// <c>PkzipWeak</c> implies the use of Zip 2.0 encryption, which is known to be /// weak and subvertible. /// </para> /// /// <para> /// A note on interoperability: Values of <c>PkzipWeak</c> and <c>None</c> are /// specified in <see /// href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT">PKWARE's zip /// specification</see>, and are considered to be "standard". Zip archives /// produced using these options will be interoperable with many other zip tools /// and libraries, including Windows Explorer. /// </para> /// /// <para> /// Values of <c>WinZipAes128</c> and <c>WinZipAes256</c> are not part of the Zip /// specification, but rather imply the use of a vendor-specific extension from /// WinZip. If you want to produce interoperable Zip archives, do not use these /// values. For example, if you produce a zip archive using WinZipAes256, you /// will be able to open it in Windows Explorer on Windows XP and Vista, but you /// will not be able to extract entries; trying this will lead to an "unspecified /// error". For this reason, some people have said that a zip archive that uses /// WinZip's AES encryption is not actually a zip archive at all. A zip archive /// produced this way will be readable with the WinZip tool (Version 11 and /// beyond). /// </para> /// /// <para> /// There are other third-party tools and libraries, both commercial and /// otherwise, that support WinZip's AES encryption. These will be able to read /// AES-encrypted zip archives produced by DotNetZip, and conversely applications /// that use DotNetZip to read zip archives will be able to read AES-encrypted /// archives produced by those tools or libraries. Consult the documentation for /// those other tools and libraries to find out if WinZip's AES encryption is /// supported. /// </para> /// /// <para> /// In case you care: According to <see /// href="http://www.winzip.com/aes_info.htm">the WinZip specification</see>, the /// actual AES key used is derived from the <see cref="ZipEntry.Password"/> via an /// algorithm that complies with <see /// href="http://www.ietf.org/rfc/rfc2898.txt">RFC 2898</see>, using an iteration /// count of 1000. The algorithm is sometimes referred to as PBKDF2, which stands /// for "Password Based Key Derivation Function #2". /// </para> /// /// <para> /// A word about password strength and length: The AES encryption technology is /// very good, but any system is only as secure as the weakest link. If you want /// to secure your data, be sure to use a password that is hard to guess. To make /// it harder to guess (increase its "entropy"), you should make it longer. If /// you use normal characters from an ASCII keyboard, a password of length 20 will /// be strong enough that it will be impossible to guess. For more information on /// that, I'd encourage you to read <see /// href="http://www.redkestrel.co.uk/Articles/RandomPasswordStrength.html">this /// article.</see> /// </para> /// /// <para> /// The WinZip AES algorithms are not supported with the version of DotNetZip that /// runs on the .NET Compact Framework. This is because .NET CF lacks the /// HMACSHA1 class that is required for producing the archive. /// </para> /// </remarks> internal enum EncryptionAlgorithm { /// <summary> /// No encryption at all. /// </summary> None = 0, /// <summary> /// Traditional or Classic pkzip encryption. /// </summary> PkzipWeak, #if AESCRYPTO /// <summary> /// WinZip AES encryption (128 key bits). /// </summary> WinZipAes128, /// <summary> /// WinZip AES encryption (256 key bits). /// </summary> WinZipAes256, #endif /// <summary> /// An encryption algorithm that is not supported by DotNetZip. /// </summary> Unsupported = 4, // others... not implemented (yet?) } /// <summary> /// An enum that specifies the source of the ZipEntry. /// </summary> enum ZipEntrySource { /// <summary> /// Default value. Invalid on a bonafide ZipEntry. /// </summary> None = 0, /// <summary> /// The entry was instantiated by calling AddFile() or another method that /// added an entry from the filesystem. /// </summary> FileSystem, /// <summary> /// The entry was instantiated via <see cref="Ionic.Zip.ZipFile.AddEntry(string,string)"/> or /// <see cref="Ionic.Zip.ZipFile.AddEntry(string,System.IO.Stream)"/> . /// </summary> Stream, /// <summary> /// The ZipEntry was instantiated by reading a zipfile. /// </summary> ZipFile, /// <summary> /// The content for the ZipEntry will be or was provided by the WriteDelegate. /// </summary> WriteDelegate, /// <summary> /// The content for the ZipEntry will be obtained from the stream dispensed by the <c>OpenDelegate</c>. /// The entry was instantiated via <see cref="Ionic.Zip.ZipFile.AddEntry(string,OpenDelegate,CloseDelegate)"/>. /// </summary> JitStream, /// <summary> /// The content for the ZipEntry will be or was obtained from a <c>ZipOutputStream</c>. /// </summary> ZipOutputStream, } /// <summary> /// An enum providing the options when an error occurs during opening or reading /// of a file or directory that is being saved to a zip file. /// </summary> /// /// <remarks> /// <para> /// This enum describes the actions that the library can take when an error occurs /// opening or reading a file, as it is being saved into a Zip archive. /// </para> /// /// <para> /// In some cases an error will occur when DotNetZip tries to open a file to be /// added to the zip archive. In other cases, an error might occur after the /// file has been successfully opened, while DotNetZip is reading the file. /// </para> /// /// <para> /// The first problem might occur when calling AddDirectory() on a directory /// that contains a Clipper .dbf file; the file is locked by Clipper and /// cannot be opened by another process. An example of the second problem is /// the ERROR_LOCK_VIOLATION that results when a file is opened by another /// process, but not locked, and a range lock has been taken on the file. /// Microsoft Outlook takes range locks on .PST files. /// </para> /// </remarks> enum ZipErrorAction { /// <summary> /// Throw an exception when an error occurs while zipping. This is the default /// behavior. (For COM clients, this is a 0 (zero).) /// </summary> Throw, /// <summary> /// When an error occurs during zipping, for example a file cannot be opened, /// skip the file causing the error, and continue zipping. (For COM clients, /// this is a 1.) /// </summary> Skip, /// <summary> /// When an error occurs during zipping, for example a file cannot be opened, /// retry the operation that caused the error. Be careful with this option. If /// the error is not temporary, the library will retry forever. (For COM /// clients, this is a 2.) /// </summary> Retry, /// <summary> /// When an error occurs, invoke the zipError event. The event type used is /// <see cref="ZipProgressEventType.Error_Saving"/>. A typical use of this option: /// a GUI application may wish to pop up a dialog to allow the user to view the /// error that occurred, and choose an appropriate action. After your /// processing in the error event, if you want to skip the file, set <see /// cref="ZipEntry.ZipErrorAction"/> on the /// <c>ZipProgressEventArgs.CurrentEntry</c> to <c>Skip</c>. If you want the /// exception to be thrown, set <c>ZipErrorAction</c> on the <c>CurrentEntry</c> /// to <c>Throw</c>. If you want to cancel the zip, set /// <c>ZipProgressEventArgs.Cancel</c> to true. Cancelling differs from using /// Skip in that a cancel will not save any further entries, if there are any. /// (For COM clients, the value of this enum is a 3.) /// </summary> InvokeErrorEvent, } /// <summary> /// A class for collecting the various options that can be used when /// Reading zip files for extraction or update. /// </summary> /// /// <remarks> /// <para> /// When reading a zip file, there are several options an /// application can set, to modify how the file is read, or what /// the library does while reading. This class collects those /// options into one container. /// </para> /// /// <para> /// Pass an instance of the <c>ReadOptions</c> class into the /// <c>ZipFile.Read()</c> method. /// </para> /// /// <seealso cref="ZipFile.Read(String, ReadOptions)"/>. /// <seealso cref="ZipFile.Read(Stream, ReadOptions)"/>. /// </remarks> class ReadOptions { /// <summary> /// An event handler for Read operations. When opening large zip /// archives, you may want to display a progress bar or other /// indicator of status progress while reading. This parameter /// allows you to specify a ReadProgress Event Handler directly. /// When you call <c>Read()</c>, the progress event is invoked as /// necessary. /// </summary> public EventHandler<ReadProgressEventArgs> ReadProgress { get; set; } /// <summary> /// The <c>System.IO.TextWriter</c> to use for writing verbose status messages /// during operations on the zip archive. A console application may wish to /// pass <c>System.Console.Out</c> to get messages on the Console. A graphical /// or headless application may wish to capture the messages in a different /// <c>TextWriter</c>, such as a <c>System.IO.StringWriter</c>. /// </summary> public TextWriter StatusMessageWriter { get; set; } /// <summary> /// The <c>System.Text.Encoding</c> to use when reading in the zip archive. Be /// careful specifying the encoding. If the value you use here is not the same /// as the Encoding used when the zip archive was created (possibly by a /// different archiver) you will get unexpected results and possibly exceptions. /// </summary> /// /// <seealso cref="ZipFile.ProvisionalAlternateEncoding"/> /// public System.Text.Encoding @Encoding { get; set; } } /// <summary> /// This class implements the "traditional" or "classic" PKZip encryption, /// which today is considered to be weak. On the other hand it is /// ubiquitous. This class is intended for use only by the DotNetZip /// library. /// </summary> /// /// <remarks> /// Most uses of the DotNetZip library will not involve direct calls into /// the ZipCrypto class. Instead, the ZipCrypto class is instantiated and /// used by the ZipEntry() class when encryption or decryption on an entry /// is employed. If for some reason you really wanted to use a weak /// encryption algorithm in some other application, you might use this /// library. But you would be much better off using one of the built-in /// strong encryption libraries in the .NET Framework, like the AES /// algorithm or SHA. /// </remarks> internal class ZipCrypto { /// <summary> /// The default constructor for ZipCrypto. /// </summary> /// /// <remarks> /// This class is intended for internal use by the library only. It's /// probably not useful to you. Seriously. Stop reading this /// documentation. It's a waste of your time. Go do something else. /// Check the football scores. Go get an ice cream with a friend. /// Seriously. /// </remarks> /// private ZipCrypto() { } public static ZipCrypto ForWrite(string password) { ZipCrypto z = new ZipCrypto(); if (password == null) throw new BadPasswordException("This entry requires a password."); z.InitCipher(password); return z; } public static ZipCrypto ForRead(string password, ZipEntry e) { System.IO.Stream s = e._archiveStream; e._WeakEncryptionHeader = new byte[12]; byte[] eh = e._WeakEncryptionHeader; ZipCrypto z = new ZipCrypto(); if (password == null) throw new BadPasswordException("This entry requires a password."); z.InitCipher(password); ZipEntry.ReadWeakEncryptionHeader(s, eh); // Decrypt the header. This has a side effect of "further initializing the // encryption keys" in the traditional zip encryption. byte[] DecryptedHeader = z.DecryptMessage(eh, eh.Length); // CRC check // According to the pkzip spec, the final byte in the decrypted header // is the highest-order byte in the CRC. We check it here. if (DecryptedHeader[11] != (byte)((e._Crc32 >> 24) & 0xff)) { // In the case that bit 3 of the general purpose bit flag is set to // indicate the presence of an 'Extended File Header' or a 'data // descriptor' (signature 0x08074b50), the last byte of the decrypted // header is sometimes compared with the high-order byte of the // lastmodified time, rather than the high-order byte of the CRC, to // verify the password. // // This is not documented in the PKWare Appnote.txt. It was // discovered this by analysis of the Crypt.c source file in the // InfoZip library http://www.info-zip.org/pub/infozip/ // // The reason for this is that the CRC for a file cannot be known // until the entire contents of the file have been streamed. This // means a tool would have to read the file content TWICE in its // entirety in order to perform PKZIP encryption - once to compute // the CRC, and again to actually encrypt. // // This is so important for performance that using the timeblob as // the verification should be the standard practice for DotNetZip // when using PKZIP encryption. This implies that bit 3 must be // set. The downside is that some tools still cannot cope with ZIP // files that use bit 3. Therefore, DotNetZip DOES NOT force bit 3 // when PKZIP encryption is in use, and instead, reads the stream // twice. // if ((e._BitField & 0x0008) != 0x0008) { throw new BadPasswordException("The password did not match."); } else if (DecryptedHeader[11] != (byte)((e._TimeBlob >> 8) & 0xff)) { throw new BadPasswordException("The password did not match."); } // We have a good password. } else { // A-OK } return z; } /// <summary> /// From AppNote.txt: /// unsigned char decrypt_byte() /// local unsigned short temp /// temp :=- Key(2) | 2 /// decrypt_byte := (temp * (temp ^ 1)) bitshift-right 8 /// end decrypt_byte /// </summary> private byte MagicByte { get { UInt16 t = (UInt16)((UInt16)(_Keys[2] & 0xFFFF) | 2); return (byte)((t * (t ^ 1)) >> 8); } } // Decrypting: // From AppNote.txt: // loop for i from 0 to 11 // C := buffer(i) ^ decrypt_byte() // update_keys(C) // buffer(i) := C // end loop /// <summary> /// Call this method on a cipher text to render the plaintext. You must /// first initialize the cipher with a call to InitCipher. /// </summary> /// /// <example> /// <code> /// var cipher = new ZipCrypto(); /// cipher.InitCipher(Password); /// // Decrypt the header. This has a side effect of "further initializing the /// // encryption keys" in the traditional zip encryption. /// byte[] DecryptedMessage = cipher.DecryptMessage(EncryptedMessage); /// </code> /// </example> /// /// <param name="cipherText">The encrypted buffer.</param> /// <param name="length"> /// The number of bytes to encrypt. /// Should be less than or equal to CipherText.Length. /// </param> /// /// <returns>The plaintext.</returns> public byte[] DecryptMessage(byte[] cipherText, int length) { if (cipherText == null) throw new ArgumentNullException("cipherText"); if (length > cipherText.Length) throw new ArgumentOutOfRangeException("length", "Bad length during Decryption: the length parameter must be smaller than or equal to the size of the destination array."); byte[] plainText = new byte[length]; for (int i = 0; i < length; i++) { byte C = (byte)(cipherText[i] ^ MagicByte); UpdateKeys(C); plainText[i] = C; } return plainText; } /// <summary> /// This is the converse of DecryptMessage. It encrypts the plaintext /// and produces a ciphertext. /// </summary> /// /// <param name="plainText">The plain text buffer.</param> /// /// <param name="length"> /// The number of bytes to encrypt. /// Should be less than or equal to plainText.Length. /// </param> /// /// <returns>The ciphertext.</returns> public byte[] EncryptMessage(byte[] plainText, int length) { if (plainText == null) throw new ArgumentNullException("plaintext"); if (length > plainText.Length) throw new ArgumentOutOfRangeException("length", "Bad length during Encryption: The length parameter must be smaller than or equal to the size of the destination array."); byte[] cipherText = new byte[length]; for (int i = 0; i < length; i++) { byte C = plainText[i]; cipherText[i] = (byte)(plainText[i] ^ MagicByte); UpdateKeys(C); } return cipherText; } /// <summary> /// This initializes the cipher with the given password. /// See AppNote.txt for details. /// </summary> /// /// <param name="passphrase"> /// The passphrase for encrypting or decrypting with this cipher. /// </param> /// /// <remarks> /// <code> /// Step 1 - Initializing the encryption keys /// ----------------------------------------- /// Start with these keys: /// Key(0) := 305419896 (0x12345678) /// Key(1) := 591751049 (0x23456789) /// Key(2) := 878082192 (0x34567890) /// /// Then, initialize the keys with a password: /// /// loop for i from 0 to length(password)-1 /// update_keys(password(i)) /// end loop /// /// Where update_keys() is defined as: /// /// update_keys(char): /// Key(0) := crc32(key(0),char) /// Key(1) := Key(1) + (Key(0) bitwiseAND 000000ffH) /// Key(1) := Key(1) * 134775813 + 1 /// Key(2) := crc32(key(2),key(1) rightshift 24) /// end update_keys /// /// Where crc32(old_crc,char) is a routine that given a CRC value and a /// character, returns an updated CRC value after applying the CRC-32 /// algorithm described elsewhere in this document. /// /// </code> /// /// <para> /// After the keys are initialized, then you can use the cipher to /// encrypt the plaintext. /// </para> /// /// <para> /// Essentially we encrypt the password with the keys, then discard the /// ciphertext for the password. This initializes the keys for later use. /// </para> /// /// </remarks> public void InitCipher(string passphrase) { byte[] p = SharedUtilities.StringToByteArray(passphrase); for (int i = 0; i < passphrase.Length; i++) UpdateKeys(p[i]); } private void UpdateKeys(byte byteValue) { _Keys[0] = (UInt32)crc32.ComputeCrc32((int)_Keys[0], byteValue); _Keys[1] = _Keys[1] + (byte)_Keys[0]; _Keys[1] = _Keys[1] * 0x08088405 + 1; _Keys[2] = (UInt32)crc32.ComputeCrc32((int)_Keys[2], (byte)(_Keys[1] >> 24)); } ///// <summary> ///// The byte array representing the seed keys used. ///// Get this after calling InitCipher. The 12 bytes represents ///// what the zip spec calls the "EncryptionHeader". ///// </summary> //public byte[] KeyHeader //{ // get // { // byte[] result = new byte[12]; // result[0] = (byte)(_Keys[0] & 0xff); // result[1] = (byte)((_Keys[0] >> 8) & 0xff); // result[2] = (byte)((_Keys[0] >> 16) & 0xff); // result[3] = (byte)((_Keys[0] >> 24) & 0xff); // result[4] = (byte)(_Keys[1] & 0xff); // result[5] = (byte)((_Keys[1] >> 8) & 0xff); // result[6] = (byte)((_Keys[1] >> 16) & 0xff); // result[7] = (byte)((_Keys[1] >> 24) & 0xff); // result[8] = (byte)(_Keys[2] & 0xff); // result[9] = (byte)((_Keys[2] >> 8) & 0xff); // result[10] = (byte)((_Keys[2] >> 16) & 0xff); // result[11] = (byte)((_Keys[2] >> 24) & 0xff); // return result; // } //} // private fields for the crypto stuff: private UInt32[] _Keys = { 0x12345678, 0x23456789, 0x34567890 }; private Ionic.Crc.CRC32 crc32 = new Ionic.Crc.CRC32(); } internal enum CryptoMode { Encrypt, Decrypt } /// <summary> /// A Stream for reading and concurrently decrypting data from a zip file, /// or for writing and concurrently encrypting data to a zip file. /// </summary> internal class ZipCipherStream : System.IO.Stream { private ZipCrypto _cipher; private System.IO.Stream _s; private CryptoMode _mode; /// <summary> The constructor. </summary> /// <param name="s">The underlying stream</param> /// <param name="mode">To either encrypt or decrypt.</param> /// <param name="cipher">The pre-initialized ZipCrypto object.</param> public ZipCipherStream(System.IO.Stream s, ZipCrypto cipher, CryptoMode mode) : base() { _cipher = cipher; _s = s; _mode = mode; } public override int Read(byte[] buffer, int offset, int count) { if (_mode == CryptoMode.Encrypt) throw new NotSupportedException("This stream does not encrypt via Read()"); if (buffer == null) throw new ArgumentNullException("buffer"); byte[] db = new byte[count]; int n = _s.Read(db, 0, count); byte[] decrypted = _cipher.DecryptMessage(db, n); for (int i = 0; i < n; i++) { buffer[offset + i] = decrypted[i]; } return n; } public override void Write(byte[] buffer, int offset, int count) { if (_mode == CryptoMode.Decrypt) throw new NotSupportedException("This stream does not Decrypt via Write()"); if (buffer == null) throw new ArgumentNullException("buffer"); // workitem 7696 if (count == 0) return; byte[] plaintext = null; if (offset != 0) { plaintext = new byte[count]; for (int i = 0; i < count; i++) { plaintext[i] = buffer[offset + i]; } } else plaintext = buffer; byte[] encrypted = _cipher.EncryptMessage(plaintext, count); _s.Write(encrypted, 0, encrypted.Length); } public override bool CanRead { get { return (_mode == CryptoMode.Decrypt); } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return (_mode == CryptoMode.Encrypt); } } public override void Flush() { //throw new NotSupportedException(); } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } /// <summary> /// An enum for the options when extracting an entry would overwrite an existing file. /// </summary> /// /// <remarks> /// <para> /// This enum describes the actions that the library can take when an /// <c>Extract()</c> or <c>ExtractWithPassword()</c> method is called to extract an /// entry to a filesystem, and the extraction would overwrite an existing filesystem /// file. /// </para> /// </remarks> /// internal enum ExtractExistingFileAction { /// <summary> /// Throw an exception when extraction would overwrite an existing file. (For /// COM clients, this is a 0 (zero).) /// </summary> Throw, /// <summary> /// When extraction would overwrite an existing file, overwrite the file silently. /// The overwrite will happen even if the target file is marked as read-only. /// (For COM clients, this is a 1.) /// </summary> OverwriteSilently, /// <summary> /// When extraction would overwrite an existing file, don't overwrite the file, silently. /// (For COM clients, this is a 2.) /// </summary> DoNotOverwrite, /// <summary> /// When extraction would overwrite an existing file, invoke the ExtractProgress /// event, using an event type of <see /// cref="ZipProgressEventType.Extracting_ExtractEntryWouldOverwrite"/>. In /// this way, the application can decide, just-in-time, whether to overwrite the /// file. For example, a GUI application may wish to pop up a dialog to allow /// the user to choose. You may want to examine the <see /// cref="ExtractProgressEventArgs.ExtractLocation"/> property before making /// the decision. If, after your processing in the Extract progress event, you /// want to NOT extract the file, set <see cref="ZipEntry.ExtractExistingFile"/> /// on the <c>ZipProgressEventArgs.CurrentEntry</c> to <c>DoNotOverwrite</c>. /// If you do want to extract the file, set <c>ZipEntry.ExtractExistingFile</c> /// to <c>OverwriteSilently</c>. If you want to cancel the Extraction, set /// <c>ZipProgressEventArgs.Cancel</c> to true. Cancelling differs from using /// DoNotOverwrite in that a cancel will not extract any further entries, if /// there are any. (For COM clients, the value of this enum is a 3.) /// </summary> InvokeExtractProgressEvent, } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using NUnit.Framework; using System.Linq; package com.quantconnect.lean.Tests { [TestFixture, Category( "TravisExclude")] public class RegressionTests { [Test, TestCaseSource( "GetRegressionTestParameters")] public void AlgorithmStatisticsRegression(AlgorithmStatisticsTestParameters parameters) { AlgorithmRunner.RunLocalBacktest(parameters.Algorithm, parameters.Statistics, parameters.Language); } private static TestCaseData[] GetRegressionTestParameters() { basicTemplateStatistics = new Map<String,String> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "264.956%"}, {"Drawdown", "2.200%"}, {"Expectancy", "0"}, {"Net Profit", "0%"}, {"Sharpe Ratio", "4.411"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.002"}, {"Beta", "1"}, {"Annual Standard Deviation", "0.193"}, {"Annual Variance", "0.037"}, {"Information Ratio", "6.816"}, {"Tracking Error", "0"}, {"Treynor Ratio", "0.851"}, {"Total Fees", "$3.09"} }; basicTemplateOptionsStatistics = new Map<String,String> { {"Total Trades", "2"}, {"Average Win", "18.70%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "79228162514264337593543950335%"}, {"Drawdown", "40.500%"}, {"Expectancy", "0"}, {"Net Profit", "18.700%"}, {"Sharpe Ratio", "0"}, {"Loss Rate", "0%"}, {"Win Rate", "100%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0"}, {"Beta", "0"}, {"Annual Standard Deviation", "0"}, {"Annual Variance", "0"}, {"Information Ratio", "0"}, {"Tracking Error", "0"}, {"Treynor Ratio", "0"}, {"Total Fees", "$0.00"}, }; limitFillRegressionStatistics = new Map<String,String> { {"Total Trades", "34"}, {"Average Win", "0.02%"}, {"Average Loss", "-0.02%"}, {"Compounding Annual Return", "8.350%"}, {"Drawdown", "0.400%"}, {"Expectancy", "0.447"}, {"Net Profit", "0.103%"}, {"Sharpe Ratio", "1.747"}, {"Loss Rate", "31%"}, {"Win Rate", "69%"}, {"Profit-Loss Ratio", "1.10"}, {"Alpha", "-0.077"}, {"Beta", "0.152"}, {"Annual Standard Deviation", "0.03"}, {"Annual Variance", "0.001"}, {"Information Ratio", "-4.87"}, {"Tracking Error", "0.164"}, {"Treynor Ratio", "0.343"}, {"Total Fees", "$34.00"} }; updateOrderRegressionStatistics = new Map<String,String> { {"Total Trades", "21"}, {"Average Win", "0%"}, {"Average Loss", "-1.71%"}, {"Compounding Annual Return", "-8.289%"}, {"Drawdown", "16.700%"}, {"Expectancy", "-1"}, {"Net Profit", "-15.892%"}, {"Sharpe Ratio", "-1.225"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.011"}, {"Beta", "-0.469"}, {"Annual Standard Deviation", "0.056"}, {"Annual Variance", "0.003"}, {"Information Ratio", "-1.573"}, {"Tracking Error", "0.152"}, {"Treynor Ratio", "0.147"}, {"Total Fees", "$21.00"} }; regressionStatistics = new Map<String,String> { {"Total Trades", "5433"}, {"Average Win", "0.00%"}, {"Average Loss", "0.00%"}, {"Compounding Annual Return", "-3.886%"}, {"Drawdown", "0.100%"}, {"Expectancy", "-0.991"}, {"Net Profit", "-0.054%"}, {"Sharpe Ratio", "-30.336"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "2.40"}, {"Alpha", "-0.022"}, {"Beta", "-0.001"}, {"Annual Standard Deviation", "0.001"}, {"Annual Variance", "0"}, {"Information Ratio", "-4.198"}, {"Tracking Error", "0.174"}, {"Treynor Ratio", "35.023"}, {"Total Fees", "$5433.00"} }; universeSelectionRegressionStatistics = new Map<String,String> { {"Total Trades", "4"}, {"Average Win", "0.70%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "-56.034%"}, {"Drawdown", "3.800%"}, {"Expectancy", "0"}, {"Net Profit", "-3.755%"}, {"Sharpe Ratio", "-3.629"}, {"Loss Rate", "0%"}, {"Win Rate", "100%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "-0.424"}, {"Beta", "1.25"}, {"Annual Standard Deviation", "0.173"}, {"Annual Variance", "0.03"}, {"Information Ratio", "-3.62"}, {"Tracking Error", "0.128"}, {"Treynor Ratio", "-0.502"}, {"Total Fees", "$2.00"} }; customDataRegressionStatistics = new Map<String,String> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "155.210%"}, {"Drawdown", "99.900%"}, {"Expectancy", "0"}, {"Net Profit", "0%"}, {"Sharpe Ratio", "0.453"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "46.332"}, {"Beta", "73.501"}, {"Annual Standard Deviation", "118.922"}, {"Annual Variance", "14142.47"}, {"Information Ratio", "0.452"}, {"Tracking Error", "118.915"}, {"Treynor Ratio", "0.733"}, {"Total Fees", "$0.00"} }; addRemoveSecurityRegressionStatistics = new Map<String,String> { {"Total Trades", "5"}, {"Average Win", "0.49%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "307.853%"}, {"Drawdown", "1.400%"}, {"Expectancy", "0"}, {"Net Profit", "1.814%"}, {"Sharpe Ratio", "6.474"}, {"Loss Rate", "0%"}, {"Win Rate", "100%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.306"}, {"Beta", "0.718"}, {"Annual Standard Deviation", "0.141"}, {"Annual Variance", "0.02"}, {"Information Ratio", "1.077"}, {"Tracking Error", "0.062"}, {"Treynor Ratio", "1.275"}, {"Total Fees", "$25.20"} }; dropboxBaseDataUniverseSelectionStatistics = new Map<String,String> { {"Total Trades", "67"}, {"Average Win", "1.13%"}, {"Average Loss", "-0.69%"}, {"Compounding Annual Return", "17.718%"}, {"Drawdown", "5.100%"}, {"Expectancy", "0.813"}, {"Net Profit", "17.718%"}, {"Sharpe Ratio", "1.38"}, {"Loss Rate", "31%"}, {"Win Rate", "69%"}, {"Profit-Loss Ratio", "1.64"}, {"Alpha", "0.055"}, {"Beta", "0.379"}, {"Annual Standard Deviation", "0.099"}, {"Annual Variance", "0.01"}, {"Information Ratio", "-0.703"}, {"Tracking Error", "0.11"}, {"Treynor Ratio", "0.359"}, {"Total Fees", "$300.15"} }; dropboxUniverseSelectionStatistics = new Map<String,String> { {"Total Trades", "49"}, {"Average Win", "1.58%"}, {"Average Loss", "-1.03%"}, {"Compounding Annual Return", "21.281%"}, {"Drawdown", "8.200%"}, {"Expectancy", "0.646"}, {"Net Profit", "21.281%"}, {"Sharpe Ratio", "1.362"}, {"Loss Rate", "35%"}, {"Win Rate", "65%"}, {"Profit-Loss Ratio", "1.52"}, {"Alpha", "0.012"}, {"Beta", "0.705"}, {"Annual Standard Deviation", "0.12"}, {"Annual Variance", "0.014"}, {"Information Ratio", "-0.51"}, {"Tracking Error", "0.101"}, {"Treynor Ratio", "0.232"}, {"Total Fees", "$232.92"} }; parameterizedStatistics = new Map<String,String> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "278.616%"}, {"Drawdown", "0.300%"}, {"Expectancy", "0"}, {"Net Profit", "0%"}, {"Sharpe Ratio", "11.017"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.553"}, {"Beta", "0.364"}, {"Annual Standard Deviation", "0.078"}, {"Annual Variance", "0.006"}, {"Information Ratio", "0.101"}, {"Tracking Error", "0.127"}, {"Treynor Ratio", "2.367"}, {"Total Fees", "$3.09"}, }; historyAlgorithmStatistics = new Map<String,String> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "372.677%"}, {"Drawdown", "1.100%"}, {"Expectancy", "0"}, {"Net Profit", "0%"}, {"Sharpe Ratio", "4.521"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.774"}, {"Beta", "0.182"}, {"Annual Standard Deviation", "0.193"}, {"Annual Variance", "0.037"}, {"Information Ratio", "1.319"}, {"Tracking Error", "0.247"}, {"Treynor Ratio", "4.798"}, {"Total Fees", "$3.09"}, }; coarseFundamentalTop5AlgorithmStatistics = new Map<String,String> { {"Total Trades", "8"}, {"Average Win", "1.15%"}, {"Average Loss", "-0.60%"}, {"Compounding Annual Return", "-0.660%"}, {"Drawdown", "2.600%"}, {"Expectancy", "-0.271"}, {"Net Profit", "-0.660%"}, {"Sharpe Ratio", "-0.255"}, {"Loss Rate", "75%"}, {"Win Rate", "25%"}, {"Profit-Loss Ratio", "1.92"}, {"Alpha", "-0.009"}, {"Beta", "0.037"}, {"Annual Standard Deviation", "0.02"}, {"Annual Variance", "0"}, {"Information Ratio", "-0.967"}, {"Tracking Error", "0.1"}, {"Treynor Ratio", "-0.142"}, {"Total Fees", "$8.61"}, }; return new List<AlgorithmStatisticsTestParameters> { // CSharp new AlgorithmStatisticsTestParameters( "AddRemoveSecurityRegressionAlgorithm", addRemoveSecurityRegressionStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "BasicTemplateAlgorithm", basicTemplateStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "BasicTemplateOptionsAlgorithm", basicTemplateOptionsStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "CustomDataRegressionAlgorithm", customDataRegressionStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "DropboxBaseDataUniverseSelectionAlgorithm", dropboxBaseDataUniverseSelectionStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "DropboxUniverseSelectionAlgorithm", dropboxUniverseSelectionStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "LimitFillRegressionAlgorithm", limitFillRegressionStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "ParameterizedAlgorithm", parameterizedStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "RegressionAlgorithm", regressionStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "UniverseSelectionRegressionAlgorithm", universeSelectionRegressionStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "UpdateOrderRegressionAlgorithm", updateOrderRegressionStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "HistoryAlgorithm", historyAlgorithmStatistics, Language.CSharp), new AlgorithmStatisticsTestParameters( "CoarseFundamentalTop5Algorithm", coarseFundamentalTop5AlgorithmStatistics, Language.CSharp), // FSharp // new AlgorithmStatisticsTestParameters( "BasicTemplateAlgorithm", basicTemplateStatistics, Language.FSharp), // VisualBasic // new AlgorithmStatisticsTestParameters( "BasicTemplateAlgorithm", basicTemplateStatistics, Language.VisualBasic), }.Select(x -> new TestCaseData(x).SetName(x.Language + "/" + x.Algorithm)).ToArray(); } public class AlgorithmStatisticsTestParameters { public final String Algorithm; public final Map<String,String> Statistics; public final Language Language; public AlgorithmStatisticsTestParameters( String algorithm, Map<String,String> statistics, Language language) { Algorithm = algorithm; Statistics = statistics; Language = language; } } } }
/* * * (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. * */ #region Usings using System; using System.Collections.Generic; using ASC.Blogs.Core.Security; using ASC.Common.Security; using ASC.Common.Security.Authorizing; using ASC.Core.Users; using HtmlAgilityPack; #endregion namespace ASC.Blogs.Core.Domain { public enum BlogType { Personal, Corporate } public class Post : ISecurityObject { #region members //private UserInfo _User; private Guid id; private string content; private List<Tag> tagList = new List<Tag>(); #endregion #region Properties public virtual BlogType BlogType { get { return BlogType.Personal; } } public virtual Guid ID { get { return id; } set { id = value; } } public virtual int AutoIncrementID { get; set; } public long BlogId { get; set; } public string BlogTitle { get; set; } public virtual Guid UserID { get; set; } public virtual string Title { get; set; } public virtual string Content { get { return content; } set { content = value; } } public virtual DateTime Datetime { get; set; } public virtual List<Tag> TagList { get { return tagList; } set { tagList = value; } } public virtual void ClearTags() { tagList.Clear(); } public virtual UserInfo Author { get { return ASC.Core.CoreContext.UserManager.GetUsers(UserID); } } #endregion #region Methods public override int GetHashCode() { return (GetType().FullName + "|" + id).GetHashCode(); } public virtual string GetPreviewText(int maxCharCount) { string result = string.Empty; if (string.IsNullOrEmpty(this.content)) return result; string content = ResizeImgForLetter(this.content).Replace("\r\n", ""); content = ASC.Web.Studio.Utility.HtmlUtility.HtmlUtility.GetFull(content); IList<string> tagExcludeList = new List<string>(); tagExcludeList.Add("img"); tagExcludeList.Add("!--"); tagExcludeList.Add("meta"); tagExcludeList.Add("embed"); tagExcludeList.Add("col"); tagExcludeList.Add("input"); tagExcludeList.Add("object"); tagExcludeList.Add("hr"); tagExcludeList.Add("br"); tagExcludeList.Add("li"); var tagList = new Stack<string>(); int charCount = 0; int index = 0; while (index < content.Length) { int posBeginOpenTag = content.IndexOf("<", index); int posEndOpenTag = content.IndexOf(">", index); int posBeginCloseTag = content.IndexOf("</", index); int posEndCloseTag = content.IndexOf("/>", index); if (posBeginOpenTag == -1) { AddHTMLText(content, index, content.Length - index, ref result, ref charCount, maxCharCount); break; } if (index < posBeginOpenTag) { if (AddHTMLText(content, index, posBeginOpenTag - index, ref result, ref charCount, maxCharCount) == 1) break; index = posBeginOpenTag; } else { index = AddHTMLTag(tagExcludeList, content, posBeginOpenTag, posEndOpenTag, posBeginCloseTag, posEndCloseTag, ref result, ref tagList); if (index == -1) break; } } while (tagList.Count != 0) { string temp = tagList.Pop(); if (!tagExcludeList.Contains(temp.ToLower())) result += "</" + temp + ">"; } return result; } private int AddHTMLText(string sourceStr, int startPos, int len, ref string outStr, ref int charCount, int maxCharCount) { string str = sourceStr.Substring(startPos, len); if (str.Replace("&nbsp;", " ").Length + charCount > maxCharCount) { int dif = maxCharCount - charCount; int sublen = str.Replace("&nbsp;", " ").IndexOf(" ", dif); if (len > str.Replace("&nbsp;", " ").Length) len = str.Replace("&nbsp;", " ").Length; outStr += str.Replace("&nbsp;", " ").Substring(0, (sublen == -1 ? len : sublen)).Replace(" ", "&nbsp;&nbsp;"); if (sourceStr.Length > startPos + len) { outStr += " ..."; } return 1; } outStr += str; charCount += str.Replace("&nbsp;", " ").Length; return 0; } private int AddHTMLTag(IList<string> tagExcludeList, string sourceStr, int posBeginOpenTag, int posEndOpenTag, int posBeginCloseTag, int posEndCloseTag, ref string outStr, ref Stack<string> tagList) { if (posEndOpenTag == posEndCloseTag + 1) { if (sourceStr.Substring(posBeginOpenTag, posEndOpenTag - posBeginOpenTag + 1) == "<hr class=\"display-none\" />") { return -1; } outStr += sourceStr.Substring(posBeginOpenTag, posEndOpenTag - posBeginOpenTag + 1); return posEndOpenTag + 1; } if (posBeginOpenTag == posBeginCloseTag && tagList.Count > 0) { string closeTag = sourceStr.Substring(posBeginCloseTag + 2, posEndOpenTag - posBeginCloseTag - 2); if (tagList.Peek() != closeTag) { while (tagList.Count > 0 && tagExcludeList.Contains(tagList.Peek().ToLower())) { tagList.Pop(); } } if (tagList.Count > 0 && tagList.Peek() == closeTag) outStr += "</" + tagList.Pop() + ">"; else outStr += "</" + closeTag + ">"; return posEndOpenTag + 1; } if (posEndOpenTag != -1) { string tagName = sourceStr.Substring(posBeginOpenTag + 1, posEndOpenTag - posBeginOpenTag - 1).Split(' ')[0]; tagList.Push(tagName); outStr += sourceStr.Substring(posBeginOpenTag, posEndOpenTag - posBeginOpenTag + 1); } return posEndOpenTag + 1; } public string ResizeImgForLetter(string text) { if (!string.IsNullOrEmpty(text)) { var doc = new HtmlDocument(); doc.LoadHtml(text); var imgs = doc.DocumentNode.SelectNodes(".//img"); if (imgs != null) { foreach (var img in imgs) { img.SetAttributeValue("style", "max-width: 540px;"); } text = doc.DocumentNode.OuterHtml; } } return text; } #endregion #region ISecurityObjectId Members public Type ObjectType { get { return GetType(); } } public object SecurityId { get { return ID; } } #endregion #region ISecurityObjectProvider Members public IEnumerable<IRole> GetObjectRoles(ISubject account, ISecurityObjectId objectId, SecurityCallContext callContext) { var roles = new List<IRole>(); if (Equals(account.ID, UserID)) { roles.Add(Common.Security.Authorizing.Constants.Owner); } return roles; } public ISecurityObjectId InheritFrom(ISecurityObjectId objectId) { return Equals(UserID, objectId.SecurityId) ? new PersonalBlogSecObject(Author) : null; } public bool InheritSupported { get { return true; } } public bool ObjectRolesSupported { get { return true; } } public DateTime Updated { get; set; } #endregion } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// AccountsReceivableRetryConfig /// </summary> [DataContract] public partial class AccountsReceivableRetryConfig : IEquatable<AccountsReceivableRetryConfig>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="AccountsReceivableRetryConfig" /> class. /// </summary> /// <param name="active">True if the retry should run daily. False puts the retry service into an inactive state for this merchant..</param> /// <param name="allowProcessLinkedAccounts">True if this account has linked accounts that it can process..</param> /// <param name="cancelAutoOrder">If true also cancel the auto order if the order is rejected at the end.</param> /// <param name="currentServicePlan">The current service plan that the account is on..</param> /// <param name="dailyActivityList">A list of days and what actions should take place on those days after an order reaches accounts receivable.</param> /// <param name="managedByLinkedAccountMerchantId">If not null, this account is managed by the specified parent merchant id..</param> /// <param name="merchantId">UltraCart merchant ID.</param> /// <param name="notifyEmails">A list of email addresses to receive summary notifications from the retry service..</param> /// <param name="notifyRejections">If true, email addresses are notified of rejections..</param> /// <param name="notifySuccesses">If true, email addresses are notified of successful charges..</param> /// <param name="processLinkedAccounts">If true, all linked accounts are also processed using the same rules..</param> /// <param name="processingPercentage">The percentage rate charged for the service..</param> /// <param name="rejectAtEnd">If true, the order is rejected the day after the last configured activity day.</param> /// <param name="trialMode">True if the account is currently in trial mode. Set to false to exit trial mode..</param> /// <param name="trialModeExpirationDts">The date when trial mode expires. If this date is reached without exiting trial mode, the service will de-activate..</param> public AccountsReceivableRetryConfig(bool? active = default(bool?), bool? allowProcessLinkedAccounts = default(bool?), bool? cancelAutoOrder = default(bool?), string currentServicePlan = default(string), List<AccountsReceivableRetryDayActivity> dailyActivityList = default(List<AccountsReceivableRetryDayActivity>), bool? managedByLinkedAccountMerchantId = default(bool?), string merchantId = default(string), List<string> notifyEmails = default(List<string>), bool? notifyRejections = default(bool?), bool? notifySuccesses = default(bool?), bool? processLinkedAccounts = default(bool?), string processingPercentage = default(string), bool? rejectAtEnd = default(bool?), bool? trialMode = default(bool?), string trialModeExpirationDts = default(string)) { this.Active = active; this.AllowProcessLinkedAccounts = allowProcessLinkedAccounts; this.CancelAutoOrder = cancelAutoOrder; this.CurrentServicePlan = currentServicePlan; this.DailyActivityList = dailyActivityList; this.ManagedByLinkedAccountMerchantId = managedByLinkedAccountMerchantId; this.MerchantId = merchantId; this.NotifyEmails = notifyEmails; this.NotifyRejections = notifyRejections; this.NotifySuccesses = notifySuccesses; this.ProcessLinkedAccounts = processLinkedAccounts; this.ProcessingPercentage = processingPercentage; this.RejectAtEnd = rejectAtEnd; this.TrialMode = trialMode; this.TrialModeExpirationDts = trialModeExpirationDts; } /// <summary> /// True if the retry should run daily. False puts the retry service into an inactive state for this merchant. /// </summary> /// <value>True if the retry should run daily. False puts the retry service into an inactive state for this merchant.</value> [DataMember(Name="active", EmitDefaultValue=false)] public bool? Active { get; set; } /// <summary> /// True if this account has linked accounts that it can process. /// </summary> /// <value>True if this account has linked accounts that it can process.</value> [DataMember(Name="allow_process_linked_accounts", EmitDefaultValue=false)] public bool? AllowProcessLinkedAccounts { get; set; } /// <summary> /// If true also cancel the auto order if the order is rejected at the end /// </summary> /// <value>If true also cancel the auto order if the order is rejected at the end</value> [DataMember(Name="cancel_auto_order", EmitDefaultValue=false)] public bool? CancelAutoOrder { get; set; } /// <summary> /// The current service plan that the account is on. /// </summary> /// <value>The current service plan that the account is on.</value> [DataMember(Name="current_service_plan", EmitDefaultValue=false)] public string CurrentServicePlan { get; set; } /// <summary> /// A list of days and what actions should take place on those days after an order reaches accounts receivable /// </summary> /// <value>A list of days and what actions should take place on those days after an order reaches accounts receivable</value> [DataMember(Name="daily_activity_list", EmitDefaultValue=false)] public List<AccountsReceivableRetryDayActivity> DailyActivityList { get; set; } /// <summary> /// If not null, this account is managed by the specified parent merchant id. /// </summary> /// <value>If not null, this account is managed by the specified parent merchant id.</value> [DataMember(Name="managed_by_linked_account_merchant_id", EmitDefaultValue=false)] public bool? ManagedByLinkedAccountMerchantId { get; set; } /// <summary> /// UltraCart merchant ID /// </summary> /// <value>UltraCart merchant ID</value> [DataMember(Name="merchant_id", EmitDefaultValue=false)] public string MerchantId { get; set; } /// <summary> /// A list of email addresses to receive summary notifications from the retry service. /// </summary> /// <value>A list of email addresses to receive summary notifications from the retry service.</value> [DataMember(Name="notify_emails", EmitDefaultValue=false)] public List<string> NotifyEmails { get; set; } /// <summary> /// If true, email addresses are notified of rejections. /// </summary> /// <value>If true, email addresses are notified of rejections.</value> [DataMember(Name="notify_rejections", EmitDefaultValue=false)] public bool? NotifyRejections { get; set; } /// <summary> /// If true, email addresses are notified of successful charges. /// </summary> /// <value>If true, email addresses are notified of successful charges.</value> [DataMember(Name="notify_successes", EmitDefaultValue=false)] public bool? NotifySuccesses { get; set; } /// <summary> /// If true, all linked accounts are also processed using the same rules. /// </summary> /// <value>If true, all linked accounts are also processed using the same rules.</value> [DataMember(Name="process_linked_accounts", EmitDefaultValue=false)] public bool? ProcessLinkedAccounts { get; set; } /// <summary> /// The percentage rate charged for the service. /// </summary> /// <value>The percentage rate charged for the service.</value> [DataMember(Name="processing_percentage", EmitDefaultValue=false)] public string ProcessingPercentage { get; set; } /// <summary> /// If true, the order is rejected the day after the last configured activity day /// </summary> /// <value>If true, the order is rejected the day after the last configured activity day</value> [DataMember(Name="reject_at_end", EmitDefaultValue=false)] public bool? RejectAtEnd { get; set; } /// <summary> /// True if the account is currently in trial mode. Set to false to exit trial mode. /// </summary> /// <value>True if the account is currently in trial mode. Set to false to exit trial mode.</value> [DataMember(Name="trial_mode", EmitDefaultValue=false)] public bool? TrialMode { get; set; } /// <summary> /// The date when trial mode expires. If this date is reached without exiting trial mode, the service will de-activate. /// </summary> /// <value>The date when trial mode expires. If this date is reached without exiting trial mode, the service will de-activate.</value> [DataMember(Name="trial_mode_expiration_dts", EmitDefaultValue=false)] public string TrialModeExpirationDts { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AccountsReceivableRetryConfig {\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" AllowProcessLinkedAccounts: ").Append(AllowProcessLinkedAccounts).Append("\n"); sb.Append(" CancelAutoOrder: ").Append(CancelAutoOrder).Append("\n"); sb.Append(" CurrentServicePlan: ").Append(CurrentServicePlan).Append("\n"); sb.Append(" DailyActivityList: ").Append(DailyActivityList).Append("\n"); sb.Append(" ManagedByLinkedAccountMerchantId: ").Append(ManagedByLinkedAccountMerchantId).Append("\n"); sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); sb.Append(" NotifyEmails: ").Append(NotifyEmails).Append("\n"); sb.Append(" NotifyRejections: ").Append(NotifyRejections).Append("\n"); sb.Append(" NotifySuccesses: ").Append(NotifySuccesses).Append("\n"); sb.Append(" ProcessLinkedAccounts: ").Append(ProcessLinkedAccounts).Append("\n"); sb.Append(" ProcessingPercentage: ").Append(ProcessingPercentage).Append("\n"); sb.Append(" RejectAtEnd: ").Append(RejectAtEnd).Append("\n"); sb.Append(" TrialMode: ").Append(TrialMode).Append("\n"); sb.Append(" TrialModeExpirationDts: ").Append(TrialModeExpirationDts).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as AccountsReceivableRetryConfig); } /// <summary> /// Returns true if AccountsReceivableRetryConfig instances are equal /// </summary> /// <param name="input">Instance of AccountsReceivableRetryConfig to be compared</param> /// <returns>Boolean</returns> public bool Equals(AccountsReceivableRetryConfig input) { if (input == null) return false; return ( this.Active == input.Active || (this.Active != null && this.Active.Equals(input.Active)) ) && ( this.AllowProcessLinkedAccounts == input.AllowProcessLinkedAccounts || (this.AllowProcessLinkedAccounts != null && this.AllowProcessLinkedAccounts.Equals(input.AllowProcessLinkedAccounts)) ) && ( this.CancelAutoOrder == input.CancelAutoOrder || (this.CancelAutoOrder != null && this.CancelAutoOrder.Equals(input.CancelAutoOrder)) ) && ( this.CurrentServicePlan == input.CurrentServicePlan || (this.CurrentServicePlan != null && this.CurrentServicePlan.Equals(input.CurrentServicePlan)) ) && ( this.DailyActivityList == input.DailyActivityList || this.DailyActivityList != null && this.DailyActivityList.SequenceEqual(input.DailyActivityList) ) && ( this.ManagedByLinkedAccountMerchantId == input.ManagedByLinkedAccountMerchantId || (this.ManagedByLinkedAccountMerchantId != null && this.ManagedByLinkedAccountMerchantId.Equals(input.ManagedByLinkedAccountMerchantId)) ) && ( this.MerchantId == input.MerchantId || (this.MerchantId != null && this.MerchantId.Equals(input.MerchantId)) ) && ( this.NotifyEmails == input.NotifyEmails || this.NotifyEmails != null && this.NotifyEmails.SequenceEqual(input.NotifyEmails) ) && ( this.NotifyRejections == input.NotifyRejections || (this.NotifyRejections != null && this.NotifyRejections.Equals(input.NotifyRejections)) ) && ( this.NotifySuccesses == input.NotifySuccesses || (this.NotifySuccesses != null && this.NotifySuccesses.Equals(input.NotifySuccesses)) ) && ( this.ProcessLinkedAccounts == input.ProcessLinkedAccounts || (this.ProcessLinkedAccounts != null && this.ProcessLinkedAccounts.Equals(input.ProcessLinkedAccounts)) ) && ( this.ProcessingPercentage == input.ProcessingPercentage || (this.ProcessingPercentage != null && this.ProcessingPercentage.Equals(input.ProcessingPercentage)) ) && ( this.RejectAtEnd == input.RejectAtEnd || (this.RejectAtEnd != null && this.RejectAtEnd.Equals(input.RejectAtEnd)) ) && ( this.TrialMode == input.TrialMode || (this.TrialMode != null && this.TrialMode.Equals(input.TrialMode)) ) && ( this.TrialModeExpirationDts == input.TrialModeExpirationDts || (this.TrialModeExpirationDts != null && this.TrialModeExpirationDts.Equals(input.TrialModeExpirationDts)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Active != null) hashCode = hashCode * 59 + this.Active.GetHashCode(); if (this.AllowProcessLinkedAccounts != null) hashCode = hashCode * 59 + this.AllowProcessLinkedAccounts.GetHashCode(); if (this.CancelAutoOrder != null) hashCode = hashCode * 59 + this.CancelAutoOrder.GetHashCode(); if (this.CurrentServicePlan != null) hashCode = hashCode * 59 + this.CurrentServicePlan.GetHashCode(); if (this.DailyActivityList != null) hashCode = hashCode * 59 + this.DailyActivityList.GetHashCode(); if (this.ManagedByLinkedAccountMerchantId != null) hashCode = hashCode * 59 + this.ManagedByLinkedAccountMerchantId.GetHashCode(); if (this.MerchantId != null) hashCode = hashCode * 59 + this.MerchantId.GetHashCode(); if (this.NotifyEmails != null) hashCode = hashCode * 59 + this.NotifyEmails.GetHashCode(); if (this.NotifyRejections != null) hashCode = hashCode * 59 + this.NotifyRejections.GetHashCode(); if (this.NotifySuccesses != null) hashCode = hashCode * 59 + this.NotifySuccesses.GetHashCode(); if (this.ProcessLinkedAccounts != null) hashCode = hashCode * 59 + this.ProcessLinkedAccounts.GetHashCode(); if (this.ProcessingPercentage != null) hashCode = hashCode * 59 + this.ProcessingPercentage.GetHashCode(); if (this.RejectAtEnd != null) hashCode = hashCode * 59 + this.RejectAtEnd.GetHashCode(); if (this.TrialMode != null) hashCode = hashCode * 59 + this.TrialMode.GetHashCode(); if (this.TrialModeExpirationDts != null) hashCode = hashCode * 59 + this.TrialModeExpirationDts.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Common.Logging; using Spring.Expressions; using Spring.Messaging.Nms.Core; using Spring.Messaging.Nms.Support; using Spring.Messaging.Nms.Support.Converter; using Spring.Messaging.Nms.Support.Destinations; using Spring.Messaging.Nms.Listener; using Spring.Util; using Apache.NMS; namespace Spring.Messaging.Nms.Listener.Adapter { /// <summary> /// Message listener adapter that delegates the handling of messages to target /// listener methods via reflection, with flexible message type conversion. /// Allows listener methods to operate on message content types, completely /// independent from the NMS API. /// </summary> /// <remarks> /// <para>By default, the content of incoming messages gets extracted before /// being passed into the target listener method, to let the target method /// operate on message content types such as String or byte array instead of /// the raw Message. Message type conversion is delegated to a Spring /// <see cref="IMessageConverter"/>. By default, a <see cref="SimpleMessageConverter"/> /// will be used. (If you do not want such automatic message conversion taking /// place, then be sure to set the <see cref="MessageConverter"/> property /// to <code>null</code>.) /// </para> /// <para>If a target listener method returns a non-null object (typically of a /// message content type such as <code>String</code> or byte array), it will get /// wrapped in a NMS <code>Message</code> and sent to the response destination /// (either the NMS "reply-to" destination or the <see cref="defaultResponseDestination"/> /// specified. /// </para> /// <para> /// The sending of response messages is only available when /// using the <see cref="ISessionAwareMessageListener"/> entry point (typically through a /// Spring message listener container). Usage as standard NMS MessageListener /// does <i>not</i> support the generation of response messages. /// </para> /// <para>Consult the reference documentation for examples of method signatures compliant with this /// adapter class. /// </para> /// </remarks> /// <author>Juergen Hoeller</author> /// <author>Mark Pollack (.NET)</author> public class MessageListenerAdapter : IMessageListener, ISessionAwareMessageListener { #region Logging private readonly ILog logger = LogManager.GetLogger(typeof (MessageListenerAdapter)); #endregion #region Fields /// <summary> /// The default handler method name. /// </summary> public static string ORIGINAL_DEFAULT_HANDLER_METHOD = "HandleMessage"; private object handlerObject; private string defaultHandlerMethod = ORIGINAL_DEFAULT_HANDLER_METHOD; private IExpression processingExpression; private object defaultResponseDestination; private IDestinationResolver destinationResolver = new DynamicDestinationResolver(); private IMessageConverter messageConverter; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MessageListenerAdapter"/> class with default settings. /// </summary> public MessageListenerAdapter() { InitDefaultStrategies(); handlerObject = this; } /// <summary> /// Initializes a new instance of the <see cref="MessageListenerAdapter"/> class for the given handler object /// </summary> /// <param name="handlerObject">The delegate object.</param> public MessageListenerAdapter(object handlerObject) { InitDefaultStrategies(); this.handlerObject = handlerObject; } #endregion /// <summary> /// Gets or sets the handler object to delegate message listening to. /// </summary> /// <remarks> /// Specified listener methods have to be present on this target object. /// If no explicit handler object has been specified, listener /// methods are expected to present on this adapter instance, that is, /// on a custom subclass of this adapter, defining listener methods. /// </remarks> /// <value>The handler object.</value> public object HandlerObject { get { return handlerObject; } set { handlerObject = value; } } /// <summary> /// Gets or sets the default handler method to delegate to, /// for the case where no specific listener method has been determined. /// Out-of-the-box value is <see cref="ORIGINAL_DEFAULT_HANDLER_METHOD"/> ("HandleMessage"}. /// </summary> /// <value>The default handler method.</value> public string DefaultHandlerMethod { get { return defaultHandlerMethod; } set { defaultHandlerMethod = value; processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)"); } } /// <summary> /// Sets the default destination to send response messages to. This will be applied /// in case of a request message that does not carry a "JMSReplyTo" field. /// Response destinations are only relevant for listener methods that return /// result objects, which will be wrapped in a response message and sent to a /// response destination. /// <para> /// Alternatively, specify a "DefaultResponseQueueName" or "DefaultResponseTopicName", /// to be dynamically resolved via the DestinationResolver. /// </para> /// </summary> /// <value>The default response destination.</value> public object DefaultResponseDestination { set { defaultResponseDestination = value; } } /// <summary> /// Sets the name of the default response queue to send response messages to. /// This will be applied in case of a request message that does not carry a /// "NMSReplyTo" field. /// <para>Alternatively, specify a JMS Destination object as "defaultResponseDestination".</para> /// </summary> /// <value>The name of the default response destination queue.</value> public string DefaultResponseQueueName { set { defaultResponseDestination = new DestinationNameHolder(value, false); } } /// <summary> /// Sets the name of the default response topic to send response messages to. /// This will be applied in case of a request message that does not carry a /// "NMSReplyTo" field. /// <para>Alternatively, specify a JMS Destination object as "defaultResponseDestination".</para> /// </summary> /// <value>The name of the default response destination topic.</value> public string DefaultResponseTopicName { set { defaultResponseDestination = new DestinationNameHolder(value, true); } } /// <summary> /// Gets or sets the destination resolver that should be used to resolve response /// destination names for this adapter. /// <para>The default resolver is a <see cref="DynamicDestinationResolver"/>. /// Specify another implementation, for other strategies, perhaps from a directory service.</para> /// </summary> /// <value>The destination resolver.</value> public IDestinationResolver DestinationResolver { get { return destinationResolver; } set { AssertUtils.ArgumentNotNull(value, "DestinationResolver must not be null"); destinationResolver = value; } } /// <summary> /// Gets or sets the message converter that will convert incoming JMS messages to /// listener method arguments, and objects returned from listener /// methods back to NMS messages. /// </summary> /// <remarks> /// <para>The default converter is a {@link SimpleMessageConverter}, which is able /// to handle BytesMessages}, TextMessages, MapMessages, and ObjectMessages. /// </para> /// </remarks> /// <value>The message converter.</value> public IMessageConverter MessageConverter { get { return messageConverter; } set { messageConverter = value; } } /// <summary> /// Standard JMS {@link MessageListener} entry point. /// <para>Delegates the message to the target listener method, with appropriate /// conversion of the message arguments /// </para> /// </summary> /// <remarks> /// In case of an exception, the <see cref="HandleListenerException"/> method will be invoked. /// <b>Note</b> /// Does not support sending response messages based on /// result objects returned from listener methods. Use the /// <see cref="ISessionAwareMessageListener"/> entry point (typically through a Spring /// message listener container) for handling result objects as well. /// </remarks> /// <param name="message">The incoming message.</param> public void OnMessage(IMessage message) { try { OnMessage(message, null); } catch (Exception e) { HandleListenerException(e); } } /// <summary> /// Spring <see cref="ISessionAwareMessageListener"/> entry point. /// <para> /// Delegates the message to the target listener method, with appropriate /// conversion of the message argument. If the target method returns a /// non-null object, wrap in a NMS message and send it back. /// </para> /// </summary> /// <param name="message">The incoming message.</param> /// <param name="session">The session to operate on.</param> public void OnMessage(IMessage message, ISession session) { if (handlerObject != this) { if (typeof(ISessionAwareMessageListener).IsInstanceOfType(handlerObject)) { if (session != null) { ((ISessionAwareMessageListener) handlerObject).OnMessage(message, session); return; } else if (!typeof(IMessageListener).IsInstanceOfType(handlerObject)) { throw new InvalidOperationException("MessageListenerAdapter cannot handle a " + "SessionAwareMessageListener delegate if it hasn't been invoked with a Session itself"); } } if (typeof(IMessageListener).IsInstanceOfType(handlerObject)) { ((IMessageListener)handlerObject).OnMessage(message); return; } } // Regular case: find a handler method reflectively. object convertedMessage = ExtractMessage(message); IDictionary<string, object> vars = new Dictionary<string, object>(); vars["convertedObject"] = convertedMessage; //Need to parse each time since have overloaded methods and //expression processor caches target of first invocation. //TODO - check JIRA as I believe this has been fixed, otherwise, use regular reflection. -MLP //processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)"); //Invoke message handler method and get result. object result; try { result = processingExpression.GetValue(handlerObject, vars); } catch (NMSException) { throw; } // Will only happen if dynamic method invocation falls back to standard reflection. catch (TargetInvocationException ex) { Exception targetEx = ex.InnerException; if (ObjectUtils.IsAssignable(typeof(NMSException), targetEx)) { throw ReflectionUtils.UnwrapTargetInvocationException(ex); } else { throw new ListenerExecutionFailedException("Listener method '" + defaultHandlerMethod + "' threw exception", targetEx); } } catch (Exception ex) { throw new ListenerExecutionFailedException("Failed to invoke target method '" + defaultHandlerMethod + "' with argument " + convertedMessage, ex); } if (result != null) { HandleResult(result, message, session); } else { logger.Debug("No result object given - no result to handle"); } } /// <summary> /// Initialize the default implementations for the adapter's strategies. /// </summary> protected virtual void InitDefaultStrategies() { MessageConverter = new SimpleMessageConverter(); processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)"); } /// <summary> /// Handle the given exception that arose during listener execution. /// The default implementation logs the exception at error level. /// <para>This method only applies when used as standard NMS MessageListener. /// In case of the Spring <see cref="ISessionAwareMessageListener"/> mechanism, /// exceptions get handled by the caller instead. /// </para> /// </summary> /// <param name="ex">The exception to handle.</param> protected virtual void HandleListenerException(Exception ex) { logger.Error("Listener execution failed", ex); } /// <summary> /// Extract the message body from the given message. /// </summary> /// <param name="message">The message.</param> /// <returns>the content of the message, to be passed into the /// listener method as argument</returns> /// <exception cref="NMSException">if thrown by NMS API methods</exception> private object ExtractMessage(IMessage message) { IMessageConverter converter = MessageConverter; if (converter != null) { return converter.FromMessage(message); } return message; } /// <summary> /// Gets the name of the listener method that is supposed to /// handle the given message. /// The default implementation simply returns the configured /// default listener method, if any. /// </summary> /// <param name="originalIMessage">The NMS request message.</param> /// <param name="extractedMessage">The converted JMS request message, /// to be passed into the listener method as argument.</param> /// <returns>the name of the listener method (never <code>null</code>)</returns> /// <exception cref="NMSException">if thrown by NMS API methods</exception> protected virtual string GetHandlerMethodName(IMessage originalIMessage, object extractedMessage) { return DefaultHandlerMethod; } /// <summary> /// Handles the given result object returned from the listener method, sending a response message back. /// </summary> /// <param name="result">The result object to handle (never <code>null</code>).</param> /// <param name="request">The original request message.</param> /// <param name="session">The session to operate on (may be <code>null</code>).</param> protected virtual void HandleResult(object result, IMessage request, ISession session) { if (session != null) { if (logger.IsDebugEnabled) { logger.Debug("Listener method returned result [" + result + "] - generating response message for it"); } IMessage response = BuildMessage(session, result); PostProcessResponse(request, response); IDestination destination = GetResponseDestination(request, response, session); SendResponse(session, destination, response); } else { if (logger.IsDebugEnabled) { logger.Debug("Listener method returned result [" + result + "]: not generating response message for it because of no NMS ISession given"); } } } /// <summary> /// Builds a JMS message to be sent as response based on the given result object. /// </summary> /// <param name="session">The JMS Session to operate on.</param> /// <param name="result">The content of the message, as returned from the listener method.</param> /// <returns>the JMS <code>Message</code> (never <code>null</code>)</returns> /// <exception cref="MessageConversionException">If there was an error in message conversion</exception> /// <exception cref="NMSException">if thrown by NMS API methods</exception> protected virtual IMessage BuildMessage(ISession session, Object result) { IMessageConverter converter = MessageConverter; if (converter != null) { return converter.ToMessage(result, session); } else { IMessage msg = result as IMessage; if (msg == null) { throw new MessageConversionException( "No IMessageConverter specified - cannot handle message [" + result + "]"); } return msg; } } /// <summary> /// Post-process the given response message before it will be sent. The default implementation /// sets the response's correlation id to the request message's correlation id. /// </summary> /// <param name="request">The original incoming message.</param> /// <param name="response">The outgoing JMS message about to be sent.</param> /// <exception cref="NMSException">if thrown by NMS API methods</exception> protected virtual void PostProcessResponse(IMessage request, IMessage response) { response.NMSCorrelationID = request.NMSCorrelationID; } /// <summary> /// Determine a response destination for the given message. /// </summary> /// <remarks> /// <para>The default implementation first checks the JMS Reply-To /// Destination of the supplied request; if that is not <code>null</code> /// it is returned; if it is <code>null</code>, then the configured /// <see cref="DefaultResponseDestination"/> default response destination /// is returned; if this too is <code>null</code>, then an /// <see cref="InvalidDestinationException"/>is thrown. /// </para> /// </remarks> /// <param name="request">The original incoming message.</param> /// <param name="response">The outgoing message about to be sent.</param> /// <param name="session">The session to operate on.</param> /// <returns>the response destination (never <code>null</code>)</returns> /// <exception cref="NMSException">if thrown by NMS API methods</exception> /// <exception cref="InvalidDestinationException">if no destination can be determined.</exception> protected virtual IDestination GetResponseDestination(IMessage request, IMessage response, ISession session) { IDestination replyTo = request.NMSReplyTo; if (replyTo == null) { replyTo = ResolveDefaultResponseDestination(session); if (replyTo == null) { throw new InvalidDestinationException("Cannot determine response destination: " + "Request message does not contain reply-to destination, and no default response destination set."); } } return replyTo; } /// <summary> /// Resolves the default response destination into a Destination, using this /// accessor's <see cref="IDestinationResolver"/> in case of a destination name. /// </summary> /// <param name="session">The session to operate on.</param> /// <returns>The located destination</returns> protected virtual IDestination ResolveDefaultResponseDestination(ISession session) { IDestination dest = defaultResponseDestination as IDestination; if (dest != null) { return dest; } DestinationNameHolder destNameHolder = defaultResponseDestination as DestinationNameHolder; if (destNameHolder != null) { return DestinationResolver.ResolveDestinationName(session, destNameHolder.Name, destNameHolder.IsTopic); } return null; } /// <summary> /// Sends the given response message to the given destination. /// </summary> /// <param name="session">The session to operate on.</param> /// <param name="destination">The destination to send to.</param> /// <param name="response">The outgoing message about to be sent.</param> protected virtual void SendResponse(ISession session, IDestination destination, IMessage response) { IMessageProducer producer = session.CreateProducer(destination); try { PostProcessProducer(producer, response); producer.Send(response); } finally { NmsUtils.CloseMessageProducer(producer); } } /// <summary> /// Post-process the given message producer before using it to send the response. /// The default implementation is empty. /// </summary> /// <param name="producer">The producer that will be used to send the message.</param> /// <param name="response">The outgoing message about to be sent.</param> protected virtual void PostProcessProducer(IMessageProducer producer, IMessage response) { } } /// <summary> /// Internal class combining a destination name and its target destination type (queue or topic). /// </summary> internal class DestinationNameHolder { private readonly string name; private readonly bool isTopic; public DestinationNameHolder(string name, bool isTopic) { this.name = name; this.isTopic = isTopic; } public string Name { get { return name; } } public bool IsTopic { get { return isTopic; } } } }
/* ==================================================================== 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 NPOI { using System; using NUnit.Framework; using NPOI.XSSF.UserModel; using NPOI.OpenXmlFormats; using NPOI.XSSF; using NPOI.XWPF.UserModel; using NPOI.XWPF; /** * Test Setting extended and custom OOXML properties */ [TestFixture] public class TestPOIXMLProperties { private POIXMLProperties _props; private CoreProperties _coreProperties; [SetUp] public void SetUp() { XWPFDocument sampleDoc = XWPFTestDataSamples.OpenSampleDocument("documentProperties.docx"); _props = sampleDoc.GetProperties(); _coreProperties = _props.CoreProperties; Assert.IsNotNull(_props); } [Test] public void TestWorkbookExtendedProperties() { XSSFWorkbook workbook = new XSSFWorkbook(); POIXMLProperties props = workbook.GetProperties(); Assert.IsNotNull(props); ExtendedProperties properties = props.ExtendedProperties; CT_ExtendedProperties ctProps = properties.GetUnderlyingProperties(); String appVersion = "3.5 beta"; String application = "POI"; ctProps.Application = (application); ctProps.AppVersion = (appVersion); ctProps = null; properties = null; props = null; XSSFWorkbook newWorkbook = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook); Assert.IsTrue(workbook != newWorkbook); POIXMLProperties newProps = newWorkbook.GetProperties(); Assert.IsNotNull(newProps); ExtendedProperties newProperties = newProps.ExtendedProperties; CT_ExtendedProperties newCtProps = newProperties.GetUnderlyingProperties(); Assert.AreEqual(application, newCtProps.Application); Assert.AreEqual(appVersion, newCtProps.AppVersion); } /** * Test usermodel API for Setting custom properties */ [Test] public void TestCustomProperties() { POIXMLDocument wb = new XSSFWorkbook(); CustomProperties customProps = wb.GetProperties().CustomProperties; customProps.AddProperty("test-1", "string val"); customProps.AddProperty("test-2", 1974); customProps.AddProperty("test-3", 36.6); //Adding a duplicate try { customProps.AddProperty("test-3", 36.6); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.AreEqual("A property with this name already exists in the custom properties", e.Message); } customProps.AddProperty("test-4", true); wb = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack((XSSFWorkbook)wb); CT_CustomProperties ctProps = wb.GetProperties().CustomProperties.GetUnderlyingProperties(); Assert.AreEqual(6, ctProps.sizeOfPropertyArray()); CT_Property p; p = ctProps.GetPropertyArray(0); Assert.AreEqual("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.fmtid); Assert.AreEqual("test-1", p.name); Assert.AreEqual("string val", p.Item.ToString()); Assert.AreEqual(2, p.pid); p = ctProps.GetPropertyArray(1); Assert.AreEqual("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.fmtid); Assert.AreEqual("test-2", p.name); Assert.AreEqual(1974, p.Item); Assert.AreEqual(3, p.pid); p = ctProps.GetPropertyArray(2); Assert.AreEqual("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.fmtid); Assert.AreEqual("test-3", p.name); Assert.AreEqual(36.6, p.Item); Assert.AreEqual(4, p.pid); p = ctProps.GetPropertyArray(3); Assert.AreEqual("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.fmtid); Assert.AreEqual("test-4", p.name); Assert.AreEqual(true, p.Item); Assert.AreEqual(5, p.pid); p = ctProps.GetPropertyArray(4); Assert.AreEqual("Generator", p.name); Assert.AreEqual("NPOI", p.Item); Assert.AreEqual(6, p.pid); //p = ctProps.GetPropertyArray(5); //Assert.AreEqual("Generator Version", p.name); //Assert.AreEqual("2.0.9", p.Item); //Assert.AreEqual(7, p.pid); } [Ignore] public void TestDocumentProperties() { String category = _coreProperties.Category; Assert.AreEqual("test", category); String contentStatus = "Draft"; _coreProperties.ContentStatus = contentStatus; Assert.AreEqual("Draft", contentStatus); DateTime? Created = _coreProperties.Created; // the original file Contains a following value: 2009-07-20T13:12:00Z Assert.IsTrue(DateTimeEqualToUTCString(Created, "2009-07-20T13:12:00Z")); String creator = _coreProperties.Creator; Assert.AreEqual("Paolo Mottadelli", creator); String subject = _coreProperties.Subject; Assert.AreEqual("Greetings", subject); String title = _coreProperties.Title; Assert.AreEqual("Hello World", title); } public void TestTransitiveSetters() { XWPFDocument doc = new XWPFDocument(); CoreProperties cp = doc.GetProperties().CoreProperties; DateTime dateCreated = new DateTime(2010, 6, 15, 10, 0, 0); cp.Created = new DateTime(2010, 6, 15, 10, 0, 0); Assert.AreEqual(dateCreated.ToString(), cp.Created.ToString()); doc = XWPFTestDataSamples.WriteOutAndReadBack(doc); cp = doc.GetProperties().CoreProperties; DateTime? dt3 = cp.Created; Assert.AreEqual(dateCreated.ToString(), dt3.ToString()); } [Ignore] public void TestGetSetRevision() { String revision = _coreProperties.Revision; Assert.IsTrue(Int32.Parse(revision) > 1, "Revision number is 1"); _coreProperties.Revision = "20"; Assert.AreEqual("20", _coreProperties.Revision); _coreProperties.Revision = "20xx"; Assert.AreEqual("20", _coreProperties.Revision); } public static bool DateTimeEqualToUTCString(DateTime? dateTime, String utcString) { DateTime utcDt = DateTime.SpecifyKind((DateTime)dateTime, DateTimeKind.Utc); string dateTimeUtcString = utcDt.ToString("yyyy-MM-ddThh:mm:ssZ"); return utcString.Equals(dateTimeUtcString); } private static String ZeroPad(long i) { if (i >= 0 && i <= 9) { return "0" + i; } else { return i.ToString(); } } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Text; using Encog.App.Analyst.CSV.Basic; using Encog.App.Quant; using Encog.MathUtil; using Encog.Util.CSV; namespace Encog.Util.Arrayutil { /// <summary> /// This object holds the normalization stats for a column. This includes the /// actual and desired high-low range for this column. /// </summary> /// public class NormalizedField { /// <summary> /// The list of classes. /// </summary> /// private readonly IList<ClassItem> _classes; /// <summary> /// Allows the index of a field to be looked up. /// </summary> /// private readonly IDictionary<String, Int32> _lookup; /// <summary> /// The action that should be taken on this column. /// </summary> /// private NormalizationAction _action; /// <summary> /// The actual high from the sample data. /// </summary> /// private double _actualHigh; /// <summary> /// The actual low from the sample data. /// </summary> /// private double _actualLow; /// <summary> /// If equilateral classification is used, this is the Equilateral object. /// </summary> /// private Equilateral _eq; /// <summary> /// The name of this column. /// </summary> /// private String _name; /// <summary> /// The desired normalized high. /// </summary> /// private double _normalizedHigh; /// <summary> /// The desired normalized low from the sample data. /// </summary> /// private double _normalizedLow; /// <summary> /// Construct the object with a range of 1 and -1. /// </summary> /// public NormalizedField() : this(1, -1) { } /// <summary> /// Construct the object. /// </summary> /// /// <param name="theNormalizedHigh">The normalized high.</param> /// <param name="theNormalizedLow">The normalized low.</param> public NormalizedField(double theNormalizedHigh, double theNormalizedLow) { _classes = new List<ClassItem>(); _lookup = new Dictionary<String, Int32>(); _normalizedHigh = theNormalizedHigh; _normalizedLow = theNormalizedLow; _actualHigh = Double.MinValue; _actualLow = Double.MaxValue; _action = NormalizationAction.Normalize; } /// <summary> /// Construct an object. /// </summary> /// /// <param name="theAction">The desired action.</param> /// <param name="theName">The name of this column.</param> public NormalizedField(NormalizationAction theAction, String theName) : this(theAction, theName, 0, 0, 0, 0) { } /// <summary> /// Construct the field, with no defaults. /// </summary> /// /// <param name="theAction">The normalization action to take.</param> /// <param name="theName">The name of this field.</param> /// <param name="ahigh">The actual high.</param> /// <param name="alow">The actual low.</param> /// <param name="nhigh">The normalized high.</param> /// <param name="nlow">The normalized low.</param> public NormalizedField(NormalizationAction theAction, String theName, double ahigh, double alow, double nhigh, double nlow) { _classes = new List<ClassItem>(); _lookup = new Dictionary<String, Int32>(); _action = theAction; _actualHigh = ahigh; _actualLow = alow; _normalizedHigh = nhigh; _normalizedLow = nlow; _name = theName; } /// <summary> /// Construct the object. /// </summary> /// /// <param name="theName">The name of the field.</param> /// <param name="theAction">The action of the field.</param> /// <param name="high">The high end of the range for the field.</param> /// <param name="low">The low end of the range for the field.</param> public NormalizedField(String theName, NormalizationAction theAction, double high, double low) { _classes = new List<ClassItem>(); _lookup = new Dictionary<String, Int32>(); _name = theName; _action = theAction; _normalizedHigh = high; _normalizedLow = low; } /// <summary> /// Set the action for the field. /// </summary> public NormalizationAction Action { get { return _action; } set { _action = value; } } /// <summary> /// Set the actual high for the field. /// </summary> public double ActualHigh { get { return _actualHigh; } set { _actualHigh = value; } } /// <summary> /// Set the actual low for the field. /// </summary> public double ActualLow { get { return _actualLow; } set { _actualLow = value; } } /// <value>A list of any classes in this field.</value> public IList<ClassItem> Classes { get { return _classes; } } /// <value>Returns the number of columns needed for this classification. The /// number of columns needed will vary, depending on the /// classification method used.</value> public int ColumnsNeeded { get { switch (_action) { case NormalizationAction.Ignore: return 0; case NormalizationAction.Equilateral: return _classes.Count - 1; case NormalizationAction.OneOf: return _classes.Count; default: return 1; } } } /// <value>The equilateral object used by this class, null if none.</value> public Equilateral Eq { get { return _eq; } } /// <summary> /// Set the name of the field. /// </summary> public String Name { get { return _name; } set { _name = value; } } /// <summary> /// Set the normalized high for the field. /// </summary> public double NormalizedHigh { get { return _normalizedHigh; } set { _normalizedHigh = value; } } /// <summary> /// Set the normalized low for the field. /// </summary> public double NormalizedLow { get { return _normalizedLow; } set { _normalizedLow = value; } } /// <value>Is this field a classify field.</value> public bool Classify { get { return (_action == NormalizationAction.Equilateral) || (_action == NormalizationAction.OneOf) || (_action == NormalizationAction.SingleField); } } /// <summary> /// Analyze the specified value. Adjust min/max as needed. Usually used only /// internally. /// </summary> /// /// <param name="d">The value to analyze.</param> public void Analyze(double d) { _actualHigh = Math.Max(_actualHigh, d); _actualLow = Math.Min(_actualLow, d); } /// <summary> /// Denormalize the specified value. /// </summary> /// /// <param name="v">The value to normalize.</param> /// <returns>The normalized value.</returns> public double DeNormalize(double v) { double result = ((_actualLow - _actualHigh)*v - _normalizedHigh*_actualLow + _actualHigh *_normalizedLow) /(_normalizedLow - _normalizedHigh); return result; } /// <summary> /// Determine what class the specified data belongs to. /// </summary> /// /// <param name="data">The data to analyze.</param> /// <returns>The class the data belongs to.</returns> public ClassItem DetermineClass(double[] data) { int resultIndex; switch (_action) { case NormalizationAction.Equilateral: resultIndex = _eq.Decode(data); break; case NormalizationAction.OneOf: resultIndex = EngineArray.IndexOfLargest(data); break; case NormalizationAction.SingleField: resultIndex = (int) data[0]; break; default: throw new QuantError("Unknown action: " + _action); } return _classes[resultIndex]; } /// <summary> /// Encode the headers used by this field. /// </summary> /// /// <returns>A string containing a comma separated list with the headers.</returns> public String EncodeHeaders() { var line = new StringBuilder(); switch (_action) { case NormalizationAction.SingleField: BasicFile.AppendSeparator(line, CSVFormat.EgFormat); line.Append('\"'); line.Append(_name); line.Append('\"'); break; case NormalizationAction.Equilateral: for (int i = 0; i < _classes.Count - 1; i++) { BasicFile.AppendSeparator(line, CSVFormat.EgFormat); line.Append('\"'); line.Append(_name); line.Append('-'); line.Append(i); line.Append('\"'); } break; case NormalizationAction.OneOf: for (int i = 0; i < _classes.Count; i++) { BasicFile.AppendSeparator(line, CSVFormat.EgFormat); line.Append('\"'); line.Append(_name); line.Append('-'); line.Append(i); line.Append('\"'); } break; default: return null; } return line.ToString(); } /// <summary> /// Encode a single field. /// </summary> /// /// <param name="classNumber">The class number to encode.</param> /// <returns>The encoded columns.</returns> public String EncodeSingleField(int classNumber) { var result = new StringBuilder(); result.Append(classNumber); return result.ToString(); } /// <summary> /// Fix normalized fields that have a single value for the min/max. Separate /// them by 2 units. /// </summary> /// public void FixSingleValue() { if (_action == NormalizationAction.Normalize) { if (Math.Abs(_actualHigh - _actualLow) < EncogFramework.DefaultDoubleEqual) { _actualHigh += 1; _actualLow -= 1; } } } /// <summary> /// Init any internal structures. /// </summary> /// public void Init() { if (_action == NormalizationAction.Equilateral) { if (_classes.Count < Equilateral.MinEq) { throw new QuantError("There must be at least three classes " + "to make use of equilateral normalization."); } _eq = new Equilateral(_classes.Count, _normalizedHigh, _normalizedLow); } // build lookup map foreach (ClassItem t in _classes) { _lookup[t.Name] = t.Index; } } /// <summary> /// Lookup the specified field. /// </summary> /// /// <param name="str">The name of the field to lookup.</param> /// <returns>The index of the field, or -1 if not found.</returns> public int Lookup(String str) { if (!_lookup.ContainsKey(str)) { return -1; } return _lookup[str]; } /// <summary> /// Make a field to hold a class. Use a numeric range for class items. /// </summary> /// /// <param name="theAction">The action to take.</param> /// <param name="classFrom">The beginning class item.</param> /// <param name="classTo">The ending class item.</param> /// <param name="high">The output high value.</param> /// <param name="low">The output low value.</param> public void MakeClass(NormalizationAction theAction, int classFrom, int classTo, int high, int low) { if ((theAction != NormalizationAction.Equilateral) && (theAction != NormalizationAction.OneOf) && (theAction != NormalizationAction.SingleField)) { throw new QuantError("Unsupported normalization type"); } _action = theAction; _classes.Clear(); _normalizedHigh = high; _normalizedLow = low; _actualHigh = 0; _actualLow = 0; int index = 0; for (int i = classFrom; i < classTo; i++) { _classes.Add(new ClassItem("" + i, index++)); } } /// <summary> /// Create a field that will be used to hold a class. /// </summary> /// /// <param name="theAction">The action for this field.</param> /// <param name="cls">The class items.</param> /// <param name="high">The output high value.</param> /// <param name="low">The output low value.</param> public void MakeClass(NormalizationAction theAction, String[] cls, double high, double low) { if ((theAction != NormalizationAction.Equilateral) && (theAction != NormalizationAction.OneOf) && (theAction != NormalizationAction.SingleField)) { throw new QuantError("Unsupported normalization type"); } _action = theAction; _classes.Clear(); _normalizedHigh = high; _normalizedLow = low; _actualHigh = 0; _actualLow = 0; for (int i = 0; i < cls.Length; i++) { _classes.Insert(i, new ClassItem(cls[i], i)); } } /// <summary> /// Make this a pass-through field. /// </summary> /// public void MakePassThrough() { _normalizedHigh = 0; _normalizedLow = 0; _actualHigh = 0; _actualLow = 0; _action = NormalizationAction.PassThrough; } /// <summary> /// Normalize the specified value. /// </summary> /// <param name="v">The value to normalize.</param> /// <returns>The normalized value.</returns> public double Normalize(double v) { return ((v - _actualLow)/(_actualHigh - _actualLow)) *(_normalizedHigh - _normalizedLow) + _normalizedLow; } /// <inheritdoc/> public override sealed String ToString() { var result = new StringBuilder("["); result.Append(GetType().Name); result.Append(" name="); result.Append(_name); result.Append(", actualHigh="); result.Append(_actualHigh); result.Append(", actualLow="); result.Append(_actualLow); result.Append("]"); return result.ToString(); } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TBS.ScreenManager; namespace TBS.Screens { /// <summary> /// Base class for screens that contain a menu of options. The user can /// move up and down to select an entry, or cancel to back out of the screen. /// </summary> abstract class MenuScreen : GameScreen { #region Fields readonly List<MenuEntry> _menuEntries = new List<MenuEntry>(); int _selectedEntry; readonly string _menuTitle; #endregion #region Properties /// <summary> /// Gets the list of menu entries, so derived classes can add /// or change the menu contents. /// </summary> protected IList<MenuEntry> MenuEntries { get { return _menuEntries; } } #endregion #region Initialization /// <summary> /// Constructor. /// </summary> protected MenuScreen(string menuTitle) { _menuTitle = menuTitle; TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); } protected void AddMenuEntry(MenuEntry e) { MenuEntries.Add(e); if (MenuEntries.Count == 1) OnFocusEntry(0, 0); } #endregion #region Handle Input /// <summary> /// Responds to user input, changing the selected entry and accepting /// or cancelling the menu. /// </summary> public override void HandleInput(InputState input) { PlayerIndex playerIndex; // Move to the previous menu entry? if (input.IsMenuUp(ControllingPlayer)) { OnUnfocusEntry(_selectedEntry, 0); _selectedEntry--; if (_selectedEntry < 0) _selectedEntry = _menuEntries.Count - 1; OnFocusEntry(_selectedEntry, 0); } // Move to the next menu entry? if (input.IsMenuDown(ControllingPlayer)) { OnUnfocusEntry(_selectedEntry, 0); _selectedEntry++; if (_selectedEntry >= _menuEntries.Count) _selectedEntry = 0; OnFocusEntry(_selectedEntry, 0); } // Accept or cancel the menu? We pass in our ControllingPlayer, which may // either be null (to accept input from any player) or a specific index. // If we pass a null controlling player, the InputState helper returns to // us which player actually provided the input. We pass that through to // OnSelectEntry and OnCancel, so they can tell which player triggered them. if (input.IsMenuSelect(ControllingPlayer, out playerIndex)) { OnSelectEntry(_selectedEntry, playerIndex); } else if (input.IsMenuCancel(ControllingPlayer, out playerIndex)) { OnCancel(playerIndex); } } /// <summary> /// Handler for when the user has chosen a menu entry. /// </summary> protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex) { _menuEntries[entryIndex].OnSelectEntry(playerIndex); } protected virtual void OnFocusEntry(int entryIndex, PlayerIndex playerIndex) { _menuEntries[entryIndex].OnFocusEntry(playerIndex); } protected virtual void OnUnfocusEntry(int entryIndex, PlayerIndex playerIndex) { _menuEntries[entryIndex].OnUnfocusEntry(playerIndex); } /// <summary> /// Handler for when the user has cancelled the menu. /// </summary> protected virtual void OnCancel(PlayerIndex playerIndex) { ExitScreen(); } /// <summary> /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler. /// </summary> protected void OnCancel(object sender, PlayerIndexEventArgs e) { OnCancel(e.PlayerIndex); } #endregion #region Update and Draw /// <summary> /// Allows the screen the chance to position the menu entries. By default /// all menu entries are lined up in a vertical list, centered on the screen. /// </summary> protected virtual void UpdateMenuEntryLocations() { // Make the menu slide into place during transitions, using a // power curve to make things look more interesting (this makes // the movement slow down as it nears the end). var transitionOffset = (float)Math.Pow(TransitionPosition, 2); // start at Y = 175; each X value is generated per entry var position = new Vector2(0f, 175f); // update each menu entry's location in turn foreach (var menuEntry in _menuEntries) { // each entry is to be centered horizontally position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2; if (ScreenState == ScreenState.TransitionOn) position.X -= transitionOffset * 256; else position.X += transitionOffset * 512; // set the entry's position menuEntry.Position = position; // move down for the next entry the size of this entry position.Y += menuEntry.GetHeight(this); } } /// <summary> /// Updates the menu. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // Update each nested MenuEntry object. for (var i = 0; i < _menuEntries.Count; i++) _menuEntries[i].Update(this, IsActive && i == _selectedEntry, gameTime); } /// <summary> /// Draws the menu. /// </summary> public override void Draw(GameTime gameTime) { // make sure our entries are in the right place before we draw them UpdateMenuEntryLocations(); var graphics = ScreenManager.GraphicsDevice; var spriteBatch = ScreenManager.SpriteBatch; var font = ScreenManager.Font; spriteBatch.Begin(); // Draw each menu entry in turn. for (var i = 0; i < _menuEntries.Count; i++) { var menuEntry = _menuEntries[i]; var isSelected = IsActive && (i == _selectedEntry); menuEntry.Draw(this, isSelected, gameTime); } // Make the menu slide into place during transitions, using a // power curve to make things look more interesting (this makes // the movement slow down as it nears the end). var transitionOffset = (float)Math.Pow(TransitionPosition, 2); // Draw the menu title centered on the screen var titlePosition = new Vector2(graphics.Viewport.Width / 2f, 80); var titleOrigin = font.MeasureString(_menuTitle) / 2; var titleColor = new Color(192, 192, 192) * TransitionAlpha; const float titleScale = 1.25f; titlePosition.Y -= transitionOffset * 100; spriteBatch.DrawString(font, _menuTitle, titlePosition, titleColor, 0, titleOrigin, titleScale, SpriteEffects.None, 0); spriteBatch.End(); } #endregion } }
/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ // [AUTO_HEADER] namespace TakaoPreference { partial class PanelGeneral { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PanelGeneral)); this.u_titleLabel = new System.Windows.Forms.Label(); this.u_shiftKeyCheckBox = new System.Windows.Forms.CheckBox(); this.u_ctrlBackslashCheckBox = new System.Windows.Forms.CheckBox(); this.u_notifyCheckBox = new System.Windows.Forms.CheckBox(); this.u_labelShorcut = new System.Windows.Forms.Label(); this.u_shortcutComboBox = new System.Windows.Forms.ComboBox(); this.u_moduleCheckListBox = new System.Windows.Forms.CheckedListBox(); this.u_moduleLabel = new System.Windows.Forms.Label(); this.u_labelChineseToggle = new System.Windows.Forms.Label(); this.u_labelRepeat = new System.Windows.Forms.Label(); this.u_chineseConverterToggleComboBox = new System.Windows.Forms.ComboBox(); this.u_repeatComboBox = new System.Windows.Forms.ComboBox(); this.u_labelCtrlAlt1 = new System.Windows.Forms.Label(); this.u_labelCtrlAlt2 = new System.Windows.Forms.Label(); this.u_lookupLabel = new System.Windows.Forms.Label(); this.u_reverseLookupComboBox = new System.Windows.Forms.ComboBox(); this.u_shortcutGroup = new System.Windows.Forms.GroupBox(); this.u_basicGroup = new System.Windows.Forms.GroupBox(); this.u_capslockCheckBox = new System.Windows.Forms.CheckBox(); this.u_shortcutGroup.SuspendLayout(); this.u_basicGroup.SuspendLayout(); this.SuspendLayout(); // // u_titleLabel // this.u_titleLabel.AccessibleDescription = null; this.u_titleLabel.AccessibleName = null; resources.ApplyResources(this.u_titleLabel, "u_titleLabel"); this.u_titleLabel.Font = null; this.u_titleLabel.Name = "u_titleLabel"; // // u_shiftKeyCheckBox // this.u_shiftKeyCheckBox.AccessibleDescription = null; this.u_shiftKeyCheckBox.AccessibleName = null; resources.ApplyResources(this.u_shiftKeyCheckBox, "u_shiftKeyCheckBox"); this.u_shiftKeyCheckBox.BackgroundImage = null; this.u_shiftKeyCheckBox.Font = null; this.u_shiftKeyCheckBox.Name = "u_shiftKeyCheckBox"; this.u_shiftKeyCheckBox.UseVisualStyleBackColor = true; this.u_shiftKeyCheckBox.CheckedChanged += new System.EventHandler(this.u_chkAssociatedPhrases_CheckedChanged); // // u_ctrlBackslashCheckBox // this.u_ctrlBackslashCheckBox.AccessibleDescription = null; this.u_ctrlBackslashCheckBox.AccessibleName = null; resources.ApplyResources(this.u_ctrlBackslashCheckBox, "u_ctrlBackslashCheckBox"); this.u_ctrlBackslashCheckBox.BackgroundImage = null; this.u_ctrlBackslashCheckBox.Font = null; this.u_ctrlBackslashCheckBox.Name = "u_ctrlBackslashCheckBox"; this.u_ctrlBackslashCheckBox.UseVisualStyleBackColor = true; this.u_ctrlBackslashCheckBox.CheckedChanged += new System.EventHandler(this.u_chkCtrlBackslash_CheckedChanged); // // u_notifyCheckBox // this.u_notifyCheckBox.AccessibleDescription = null; this.u_notifyCheckBox.AccessibleName = null; resources.ApplyResources(this.u_notifyCheckBox, "u_notifyCheckBox"); this.u_notifyCheckBox.BackgroundImage = null; this.u_notifyCheckBox.Font = null; this.u_notifyCheckBox.Name = "u_notifyCheckBox"; this.u_notifyCheckBox.UseVisualStyleBackColor = true; this.u_notifyCheckBox.CheckedChanged += new System.EventHandler(this.u_chkNotify_CheckedChanged); // // u_labelShorcut // this.u_labelShorcut.AccessibleDescription = null; this.u_labelShorcut.AccessibleName = null; resources.ApplyResources(this.u_labelShorcut, "u_labelShorcut"); this.u_labelShorcut.Font = null; this.u_labelShorcut.Name = "u_labelShorcut"; // // u_shortcutComboBox // this.u_shortcutComboBox.AccessibleDescription = null; this.u_shortcutComboBox.AccessibleName = null; resources.ApplyResources(this.u_shortcutComboBox, "u_shortcutComboBox"); this.u_shortcutComboBox.BackgroundImage = null; this.u_shortcutComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_shortcutComboBox.Font = null; this.u_shortcutComboBox.FormattingEnabled = true; this.u_shortcutComboBox.Items.AddRange(new object[] { resources.GetString("u_shortcutComboBox.Items"), resources.GetString("u_shortcutComboBox.Items1")}); this.u_shortcutComboBox.Name = "u_shortcutComboBox"; this.u_shortcutComboBox.SelectedIndexChanged += new System.EventHandler(this.u_shortcut_SelectedIndexChanged); // // u_moduleCheckListBox // this.u_moduleCheckListBox.AccessibleDescription = null; this.u_moduleCheckListBox.AccessibleName = null; resources.ApplyResources(this.u_moduleCheckListBox, "u_moduleCheckListBox"); this.u_moduleCheckListBox.BackgroundImage = null; this.u_moduleCheckListBox.CheckOnClick = true; this.u_moduleCheckListBox.Font = null; this.u_moduleCheckListBox.FormattingEnabled = true; this.u_moduleCheckListBox.Name = "u_moduleCheckListBox"; this.u_moduleCheckListBox.UseCompatibleTextRendering = true; this.u_moduleCheckListBox.SelectedValueChanged += new System.EventHandler(this.u_moduleCheckListBox_SelectedValueChanged); // // u_moduleLabel // this.u_moduleLabel.AccessibleDescription = null; this.u_moduleLabel.AccessibleName = null; resources.ApplyResources(this.u_moduleLabel, "u_moduleLabel"); this.u_moduleLabel.Font = null; this.u_moduleLabel.Name = "u_moduleLabel"; // // u_labelChineseToggle // this.u_labelChineseToggle.AccessibleDescription = null; this.u_labelChineseToggle.AccessibleName = null; resources.ApplyResources(this.u_labelChineseToggle, "u_labelChineseToggle"); this.u_labelChineseToggle.Font = null; this.u_labelChineseToggle.Name = "u_labelChineseToggle"; // // u_labelRepeat // this.u_labelRepeat.AccessibleDescription = null; this.u_labelRepeat.AccessibleName = null; resources.ApplyResources(this.u_labelRepeat, "u_labelRepeat"); this.u_labelRepeat.Font = null; this.u_labelRepeat.Name = "u_labelRepeat"; // // u_chineseConverterToggleComboBox // this.u_chineseConverterToggleComboBox.AccessibleDescription = null; this.u_chineseConverterToggleComboBox.AccessibleName = null; resources.ApplyResources(this.u_chineseConverterToggleComboBox, "u_chineseConverterToggleComboBox"); this.u_chineseConverterToggleComboBox.BackgroundImage = null; this.u_chineseConverterToggleComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_chineseConverterToggleComboBox.Font = null; this.u_chineseConverterToggleComboBox.FormattingEnabled = true; this.u_chineseConverterToggleComboBox.Name = "u_chineseConverterToggleComboBox"; this.u_chineseConverterToggleComboBox.SelectedIndexChanged += new System.EventHandler(this.u_comboChineseConverterToggle_SelectedIndexChanged); // // u_repeatComboBox // this.u_repeatComboBox.AccessibleDescription = null; this.u_repeatComboBox.AccessibleName = null; resources.ApplyResources(this.u_repeatComboBox, "u_repeatComboBox"); this.u_repeatComboBox.BackgroundImage = null; this.u_repeatComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_repeatComboBox.Font = null; this.u_repeatComboBox.FormattingEnabled = true; this.u_repeatComboBox.Name = "u_repeatComboBox"; this.u_repeatComboBox.SelectedIndexChanged += new System.EventHandler(this.u_comboRepeat_SelectedIndexChanged); // // u_labelCtrlAlt1 // this.u_labelCtrlAlt1.AccessibleDescription = null; this.u_labelCtrlAlt1.AccessibleName = null; resources.ApplyResources(this.u_labelCtrlAlt1, "u_labelCtrlAlt1"); this.u_labelCtrlAlt1.Font = null; this.u_labelCtrlAlt1.Name = "u_labelCtrlAlt1"; // // u_labelCtrlAlt2 // this.u_labelCtrlAlt2.AccessibleDescription = null; this.u_labelCtrlAlt2.AccessibleName = null; resources.ApplyResources(this.u_labelCtrlAlt2, "u_labelCtrlAlt2"); this.u_labelCtrlAlt2.Font = null; this.u_labelCtrlAlt2.Name = "u_labelCtrlAlt2"; // // u_lookupLabel // this.u_lookupLabel.AccessibleDescription = null; this.u_lookupLabel.AccessibleName = null; resources.ApplyResources(this.u_lookupLabel, "u_lookupLabel"); this.u_lookupLabel.Font = null; this.u_lookupLabel.Name = "u_lookupLabel"; // // u_reverseLookupComboBox // this.u_reverseLookupComboBox.AccessibleDescription = null; this.u_reverseLookupComboBox.AccessibleName = null; resources.ApplyResources(this.u_reverseLookupComboBox, "u_reverseLookupComboBox"); this.u_reverseLookupComboBox.BackgroundImage = null; this.u_reverseLookupComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_reverseLookupComboBox.Font = null; this.u_reverseLookupComboBox.FormattingEnabled = true; this.u_reverseLookupComboBox.Items.AddRange(new object[] { resources.GetString("u_reverseLookupComboBox.Items"), resources.GetString("u_reverseLookupComboBox.Items1"), resources.GetString("u_reverseLookupComboBox.Items2"), resources.GetString("u_reverseLookupComboBox.Items3")}); this.u_reverseLookupComboBox.Name = "u_reverseLookupComboBox"; this.u_reverseLookupComboBox.SelectedIndexChanged += new System.EventHandler(this.u_reverseLookupComboBox_SelectedIndexChanged); // // u_shortcutGroup // this.u_shortcutGroup.AccessibleDescription = null; this.u_shortcutGroup.AccessibleName = null; resources.ApplyResources(this.u_shortcutGroup, "u_shortcutGroup"); this.u_shortcutGroup.BackgroundImage = null; this.u_shortcutGroup.Controls.Add(this.u_labelShorcut); this.u_shortcutGroup.Controls.Add(this.u_shortcutComboBox); this.u_shortcutGroup.Controls.Add(this.u_labelChineseToggle); this.u_shortcutGroup.Controls.Add(this.u_labelCtrlAlt2); this.u_shortcutGroup.Controls.Add(this.u_labelRepeat); this.u_shortcutGroup.Controls.Add(this.u_labelCtrlAlt1); this.u_shortcutGroup.Controls.Add(this.u_chineseConverterToggleComboBox); this.u_shortcutGroup.Controls.Add(this.u_repeatComboBox); this.u_shortcutGroup.Font = null; this.u_shortcutGroup.Name = "u_shortcutGroup"; this.u_shortcutGroup.TabStop = false; // // u_basicGroup // this.u_basicGroup.AccessibleDescription = null; this.u_basicGroup.AccessibleName = null; resources.ApplyResources(this.u_basicGroup, "u_basicGroup"); this.u_basicGroup.BackgroundImage = null; this.u_basicGroup.Controls.Add(this.u_capslockCheckBox); this.u_basicGroup.Controls.Add(this.u_moduleLabel); this.u_basicGroup.Controls.Add(this.u_shiftKeyCheckBox); this.u_basicGroup.Controls.Add(this.u_ctrlBackslashCheckBox); this.u_basicGroup.Controls.Add(this.u_notifyCheckBox); this.u_basicGroup.Controls.Add(this.u_moduleCheckListBox); this.u_basicGroup.Font = null; this.u_basicGroup.Name = "u_basicGroup"; this.u_basicGroup.TabStop = false; // // u_capslockCheckBox // this.u_capslockCheckBox.AccessibleDescription = null; this.u_capslockCheckBox.AccessibleName = null; resources.ApplyResources(this.u_capslockCheckBox, "u_capslockCheckBox"); this.u_capslockCheckBox.BackgroundImage = null; this.u_capslockCheckBox.Font = null; this.u_capslockCheckBox.Name = "u_capslockCheckBox"; this.u_capslockCheckBox.UseVisualStyleBackColor = true; this.u_capslockCheckBox.CheckedChanged += new System.EventHandler(this.u_capslockCheckBox_CheckedChanged); // // PanelGeneral // this.AccessibleDescription = null; this.AccessibleName = null; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; resources.ApplyResources(this, "$this"); this.BackgroundImage = null; this.Controls.Add(this.u_basicGroup); this.Controls.Add(this.u_shortcutGroup); this.Controls.Add(this.u_reverseLookupComboBox); this.Controls.Add(this.u_lookupLabel); this.Controls.Add(this.u_titleLabel); this.Font = null; this.Name = "PanelGeneral"; this.u_shortcutGroup.ResumeLayout(false); this.u_shortcutGroup.PerformLayout(); this.u_basicGroup.ResumeLayout(false); this.u_basicGroup.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label u_titleLabel; private System.Windows.Forms.CheckBox u_shiftKeyCheckBox; private System.Windows.Forms.CheckBox u_ctrlBackslashCheckBox; private System.Windows.Forms.CheckBox u_notifyCheckBox; private System.Windows.Forms.Label u_labelShorcut; private System.Windows.Forms.ComboBox u_shortcutComboBox; private System.Windows.Forms.CheckedListBox u_moduleCheckListBox; private System.Windows.Forms.Label u_moduleLabel; private System.Windows.Forms.Label u_labelChineseToggle; private System.Windows.Forms.Label u_labelRepeat; private System.Windows.Forms.ComboBox u_chineseConverterToggleComboBox; private System.Windows.Forms.ComboBox u_repeatComboBox; private System.Windows.Forms.Label u_labelCtrlAlt1; private System.Windows.Forms.Label u_labelCtrlAlt2; private System.Windows.Forms.Label u_lookupLabel; private System.Windows.Forms.ComboBox u_reverseLookupComboBox; private System.Windows.Forms.GroupBox u_shortcutGroup; private System.Windows.Forms.GroupBox u_basicGroup; private System.Windows.Forms.CheckBox u_capslockCheckBox; } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Registrasi_FISList : System.Web.UI.Page { public int NoKe = 0; protected string dsReportSessionName = "dsListRegistrasiFIS"; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["RegistrasiFIS"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } else { btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + "Pasien Baru"; btnAddRJ.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + "Pasien Rawat Jalan"; btnAddRI.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + "Pasien Rawat Inap"; } btnSearch.Text = Resources.GetString("", "Search"); ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif"; ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif"; ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif"; ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif"; txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); UpdateDataView(true); } } #region .Update View Data ////////////////////////////////////////////////////////////////////// // PhysicalDataRead // ------------------------------------------------------------------ /// <summary> /// This function is responsible for loading data from database. /// </summary> /// <returns>DataSet</returns> public DataSet PhysicalDataRead() { // Local variables DataSet oDS = new DataSet(); // Get Data DataTable myData = new DataTable(); SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); if (txtTanggalRegistrasi.Text != "") { myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); } myObj.PoliklinikId = 34 ;//FIS myData = myObj.SelectAllFilter(); oDS.Tables.Add(myData); return oDS; } /// <summary> /// This function is responsible for binding data to Datagrid. /// </summary> /// <param name="dv"></param> private void BindData(DataView dv) { // Sets the sorting order dv.Sort = DataGridList.Attributes["SortField"]; if (DataGridList.Attributes["SortAscending"] == "no") dv.Sort += " DESC"; if (dv.Count > 0) { DataGridList.ShowFooter = false; int intRowCount = dv.Count; int intPageSaze = DataGridList.PageSize; int intPageCount = intRowCount / intPageSaze; if (intRowCount - (intPageCount * intPageSaze) > 0) intPageCount = intPageCount + 1; if (DataGridList.CurrentPageIndex >= intPageCount) DataGridList.CurrentPageIndex = intPageCount - 1; } else { DataGridList.ShowFooter = true; DataGridList.CurrentPageIndex = 0; } // Re-binds the grid NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex; DataGridList.DataSource = dv; DataGridList.DataBind(); int CurrentPage = DataGridList.CurrentPageIndex + 1; lblCurrentPage.Text = CurrentPage.ToString(); lblTotalPage.Text = DataGridList.PageCount.ToString(); lblTotalRecord.Text = dv.Count.ToString(); } /// <summary> /// This function is responsible for loading data from database and store to Session. /// </summary> /// <param name="strDataSessionName"></param> public void DataFromSourceToMemory(String strDataSessionName) { // Gets rows from the data source DataSet oDS = PhysicalDataRead(); // Stores it in the session cache Session[strDataSessionName] = oDS; } /// <summary> /// This function is responsible for update data view from datagrid. /// </summary> /// <param name="requery">true = get data from database, false= get data from session</param> public void UpdateDataView(bool requery) { // Retrieves the data if ((Session[dsReportSessionName] == null) || (requery)) { if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString()); DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } public void UpdateDataView() { // Retrieves the data if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } #endregion #region .Event DataGridList ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // HANDLERs // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageChanged(Object sender, DataGridPageChangedEventArgs e) { DataGridList.CurrentPageIndex = e.NewPageIndex; DataGridList.SelectedIndex = -1; UpdateDataView(); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="nPageIndex"></param> public void GoToPage(Object sender, int nPageIndex) { DataGridPageChangedEventArgs evPage; evPage = new DataGridPageChangedEventArgs(sender, nPageIndex); PageChanged(sender, evPage); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a first page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToFirst(Object sender, ImageClickEventArgs e) { GoToPage(sender, 0); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a previous page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToPrev(Object sender, ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex > 0) { GoToPage(sender, DataGridList.CurrentPageIndex - 1); } else { GoToPage(sender, 0); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a next page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1)) { GoToPage(sender, DataGridList.CurrentPageIndex + 1); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a last page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToLast(Object sender, ImageClickEventArgs e) { GoToPage(sender, DataGridList.PageCount - 1); } /// <summary> /// This function is invoked when you click on a column's header to /// sort by that. It just saves the current sort field name and /// refreshes the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SortByColumn(Object sender, DataGridSortCommandEventArgs e) { String strSortBy = DataGridList.Attributes["SortField"]; String strSortAscending = DataGridList.Attributes["SortAscending"]; // Sets the new sorting field DataGridList.Attributes["SortField"] = e.SortExpression; // Sets the order (defaults to ascending). If you click on the // sorted column, the order reverts. DataGridList.Attributes["SortAscending"] = "yes"; if (e.SortExpression == strSortBy) DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes"); // Refreshes the view OnClearSelection(null, null); UpdateDataView(); } /// <summary> /// The function gets invoked when a new item is being created in /// the datagrid. This applies to pager, header, footer, regular /// and alternating items. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageItemCreated(Object sender, DataGridItemEventArgs e) { // Get the newly created item ListItemType itemType = e.Item.ItemType; ////////////////////////////////////////////////////////// // Is it the HEADER? if (itemType == ListItemType.Header) { for (int i = 0; i < DataGridList.Columns.Count; i++) { // draw to reflect sorting if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression) { ////////////////////////////////////////////// // Should be much easier this way: // ------------------------------------------ // TableCell cell = e.Item.Cells[i]; // Label lblSorted = new Label(); // lblSorted.Font = "webdings"; // lblSorted.Text = strOrder; // cell.Controls.Add(lblSorted); // // but it seems it doesn't work <g> ////////////////////////////////////////////// // Add a non-clickable triangle to mean desc or asc. // The </a> ensures that what follows is non-clickable TableCell cell = e.Item.Cells[i]; LinkButton lb = (LinkButton)cell.Controls[0]; //lb.Text += "</a>&nbsp;<span style=font-family:webdings;>" + GetOrderSymbol() + "</span>"; lb.Text += "</a>&nbsp;<img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >"; } } } ////////////////////////////////////////////////////////// // Is it the PAGER? if (itemType == ListItemType.Pager) { // There's just one control in the list... TableCell pager = (TableCell)e.Item.Controls[0]; // Enumerates all the items in the pager... for (int i = 0; i < pager.Controls.Count; i += 2) { // It can be either a Label or a Link button try { Label l = (Label)pager.Controls[i]; l.Text = "Hal " + l.Text; l.CssClass = "CurrentPage"; } catch { LinkButton h = (LinkButton)pager.Controls[i]; h.Text = "[ " + h.Text + " ]"; h.CssClass = "HotLink"; } } } } /// <summary> /// Verifies whether the current sort is ascending or descending and /// returns an appropriate display text (i.e., a webding) /// </summary> /// <returns></returns> private String GetOrderSymbol() { bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no"); //return (bDescending ? " 6" : " 5"); return (bDescending ? "downbr.gif" : "upbr.gif"); } /// <summary> /// When clicked clears the current selection if any /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnClearSelection(Object sender, EventArgs e) { DataGridList.SelectedIndex = -1; } #endregion #region .Event Button /// <summary> /// When clicked, redirect to form add for inserts a new record to the database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnNewRecord(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("FISAddBaru.aspx?CurrentPage=" + CurrentPage); } public void OnAddRJ(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("FISAddRJ.aspx?CurrentPage=" + CurrentPage); } public void OnAddRI(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("FISAddRI.aspx?CurrentPage=" + CurrentPage); } /// <summary> /// When clicked, filter data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnSearch(Object sender, System.EventArgs e) { if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; DataView dv = ds.Tables[0].DefaultView; if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama") dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRegistrasi") dv.RowFilter = " NoRegistrasi LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRM") dv.RowFilter = " NoRM LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NRP") dv.RowFilter = " NRP LIKE '%" + txtSearch.Text + "%'"; else dv.RowFilter = ""; BindData(dv); } #endregion #region .Update Link Item Butom /// <summary> /// The function is responsible for get link button form. /// </summary> /// <param name="szId"></param> /// <param name="CurrentPage"></param> /// <returns></returns> public string GetLinkButton(string RawatJalanId, string StatusRawatJalan, string Nama, string CurrentPage) { string szResult = ""; if (Session["RegistrasiFIS"] != null) { szResult += "<a class=\"toolbar\" href=\"FISView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + RawatJalanId + "\" "; szResult += ">Detil</a>"; } return szResult; } public bool GetLinkDelete(string StatusRawatJalan) { bool szResult = false; if (Session["RegistrasiFIS"] != null && StatusRawatJalan == "0") { szResult = true; } return szResult; } #endregion protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { UpdateDataView(true); } protected void DataGridList_DeleteCommand(object source, DataGridCommandEventArgs e) { string RawatJalanId = DataGridList.DataKeys[e.Item.ItemIndex].ToString(); SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.RawatJalanId = int.Parse(RawatJalanId); myObj.Delete(); DataGridList.SelectedIndex = -1; UpdateDataView(true); } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections; using System.Diagnostics; using Axiom.Core; using Axiom.MathLib; using Axiom.Collections; using Axiom.Graphics; namespace Axiom.SceneManagers.Multiverse { /// <summary> /// Summary description for HeightField. /// </summary> public class HeightField : SimpleRenderable, IDisposable { // how many meters (units in sample space) per actual sample in this tile. This will be one // near the camera and larger powers of two at lower levels of detail. private int metersPerSample; // when we are changing LOD, this is the LOD we want to change to private int targetMetersPerSample; // actual size of the sample array for the current level of detail. // NOTE - this is the number of samples along one dimension private int numSamples; // location of the height map in world space private Vector3 location; // which tile is this height field attached to private Tile tile; // height samples for this tile private float [] heightMap; private float minHeight; private float maxHeight; private Material normalMaterial; // stuff related to rendering of the tile private RenderOperation renderOp; private StitchRenderable stitchRenderable; private void Init(int metersPerSample) { // set up the material normalMaterial = WorldManager.Instance.DefaultTerrainMaterial; material = normalMaterial; // create the render operation renderOp = new RenderOperation(); renderOp.operationType = OperationType.TriangleList; renderOp.useIndices = true; location = tile.Location; // ask the world manager what LOD we should use this.metersPerSample = metersPerSample; targetMetersPerSample = metersPerSample; // figure out the number of actual samples we need in the tile based on the size // and level of detail numSamples = tile.Size / metersPerSample; // allocate the storage for the height map heightMap = new float[numSamples * numSamples]; return; } public void FogNotify() { WorldManager.Instance.SetFogGPUParams(normalMaterial, "fogSettings", "fogColour"); } private void UpdateBounds() { // set bounding box this.box = new AxisAlignedBox( new Vector3(0, minHeight, 0), new Vector3(Size * WorldManager.oneMeter, maxHeight, Size * WorldManager.oneMeter) ); // set bounding sphere worldBoundingSphere.Center = box.Center; worldBoundingSphere.Radius = box.Maximum.Length; } public HeightField(Tile t):base() { tile = t; Init(WorldManager.Instance.MetersPerSample(tile.Location)); // generate the height map WorldManager.Instance.TerrainGenerator.GenerateHeightField(location, Size, metersPerSample, heightMap, out minHeight, out maxHeight); UpdateBounds(); } /// <summary> /// create a new heightField that has the same LOD as the source, /// and 1/4 the area of the source. Height points are copied from one /// quadrant of the source. /// If the heightField needs to be higher LOD, it will be adjusted /// later and the required points will be generated. /// </summary> /// <param name="t"></param> /// <param name="src"></param> /// <param name="quad"></param> public HeightField(Tile t, HeightField src, Quadrant quad):base() { tile = t; // in this case we will make the new heightField have the same LOD as // the source. The LOD will be adjusted upward later if necessary. Init(src.metersPerSample); Debug.Assert((numSamples * metersPerSample * 2) == ( src.metersPerSample * src.numSamples), "creating heightfield from source that is not next lower LOD"); int xoff = 0; int zoff = 0; switch ( quad ) { case Quadrant.Northeast: xoff = src.numSamples / 2; zoff = 0; break; case Quadrant.Northwest: xoff = 0; zoff = 0; break; case Quadrant.Southeast: xoff = src.numSamples / 2; zoff = src.numSamples / 2; break; case Quadrant.Southwest: xoff = 0; zoff = src.numSamples / 2; break; } // copy from the source heightMap this.CopyHeightFieldScaleUp(src.heightMap, 1, xoff, zoff, src.numSamples); // compute the min and max extents of this heightField, since nobody else is // going to do it. // XXX - do we need to do this? minHeight = float.MaxValue; maxHeight = float.MinValue; foreach ( float h in heightMap ) { if ( h < minHeight ) { minHeight = h; } if ( h > maxHeight ) { maxHeight = h; } } // generate the height points that were not filled in above //WorldManager.Instance.TerrainGenerator.GenerateHeightField(location, Size, metersPerSample, // heightMap, out minHeight, out maxHeight, src.metersPerSample); UpdateBounds(); } /// <summary> /// Create a new heightField that is (equal or) lower LOD than the four sources, /// Height points are copied from the four sources. /// </summary> /// <param name="t"></param> /// <param name="srcNW"></param> /// <param name="srcNE"></param> /// <param name="srcSW"></param> /// <param name="srcSE"></param> public HeightField(Tile t, HeightField srcNW, HeightField srcNE, HeightField srcSW, HeightField srcSE ):base() { tile = t; Init(WorldManager.Instance.MetersPerSample(tile.Location)); // copy from the source heightMap int halfSamples = numSamples/2; CopyHeightFieldScaleDown(srcSW.heightMap, metersPerSample / srcSW.metersPerSample, srcSW.numSamples, 0, halfSamples); CopyHeightFieldScaleDown(srcSE.heightMap, metersPerSample / srcSE.metersPerSample, srcSE.numSamples, halfSamples, halfSamples); CopyHeightFieldScaleDown(srcNW.heightMap, metersPerSample / srcNW.metersPerSample, srcNW.numSamples, 0, 0); CopyHeightFieldScaleDown(srcNE.heightMap, metersPerSample / srcNE.metersPerSample, srcNE.numSamples, halfSamples, 0); // update minHeight and maxHeight by taking the most extreme from the 4 sources. // this could result in a bounding box slightly larger than necessary, but its // not enough of an issue to warrant scanning the entire heightField looking for // the true min and max. minHeight = srcSW.minHeight; if ( srcSE.minHeight < minHeight ) { minHeight = srcSE.minHeight; } if ( srcNW.minHeight < minHeight ) { minHeight = srcNW.minHeight; } if ( srcNE.minHeight < minHeight ) { minHeight = srcNE.minHeight; } maxHeight = srcSW.maxHeight; if ( srcSE.maxHeight > maxHeight ) { maxHeight = srcSE.maxHeight; } if ( srcNW.maxHeight > maxHeight ) { maxHeight = srcNW.maxHeight; } if ( srcNE.maxHeight > maxHeight ) { maxHeight = srcNE.maxHeight; } UpdateBounds(); } private VertexData buildVertexData() { VertexData vertexData = new VertexData(); vertexData.vertexCount = numSamples * numSamples; vertexData.vertexStart = 0; // set up the vertex declaration int vDecOffset = 0; vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float3, VertexElementSemantic.Position); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float3); vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float3, VertexElementSemantic.Normal); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float3); vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float2, VertexElementSemantic.TexCoords); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float2); // create the hardware vertex buffer and set up the buffer binding HardwareVertexBuffer hvBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( vertexData.vertexDeclaration.GetVertexSize(0), vertexData.vertexCount, BufferUsage.StaticWriteOnly, false); vertexData.vertexBufferBinding.SetBinding(0, hvBuffer); // lock the vertex buffer IntPtr ipBuf = hvBuffer.Lock(BufferLocking.Discard); int bufferOff = 0; unsafe { float* buffer = (float *) ipBuf.ToPointer(); int heightMapOffset = 0; for (int zIndex = 0; zIndex < numSamples; zIndex++ ) { float z = ( zIndex * metersPerSample * WorldManager.oneMeter ); for (int xIndex = 0; xIndex < numSamples; xIndex++ ) { float height = heightMap[heightMapOffset++]; // Position float x = ( xIndex * metersPerSample * WorldManager.oneMeter ); buffer[bufferOff++] = x; buffer[bufferOff++] = height; buffer[bufferOff++] = z; // normals // XXX - this can be optimized quite a bit Vector3 norm = tile.GetNormalAt(new Vector3(x + tile.Location.x, height, z + tile.Location.z)); buffer[bufferOff++] = norm.x; buffer[bufferOff++] = norm.y; buffer[bufferOff++] = norm.z; // Texture // XXX - assumes one unit of texture space is one page. // how does the vertex shader deal with texture coords? buffer[bufferOff++] = ( x + location.x - tile.Page.Location.x ) / ( WorldManager.Instance.PageSize * WorldManager.oneMeter ); buffer[bufferOff++] = ( z + location.z - tile.Page.Location.z ) / ( WorldManager.Instance.PageSize * WorldManager.oneMeter ); } } } hvBuffer.Unlock(); return vertexData; } public void AdjustLOD() { Debug.Assert(location == tile.Location, "AdjustLOD: tile and heightField locations don't match"); // ask the world manager what LOD we should use targetMetersPerSample = WorldManager.Instance.MetersPerSample(location); if ( targetMetersPerSample != metersPerSample ) { // figure out the number of actual samples we need in the tile based on the size // and level of detail int oldNumSamples = numSamples; int oldMetersPerSample = metersPerSample; float [] oldHeightMap = heightMap; metersPerSample = targetMetersPerSample; numSamples = tile.Size / metersPerSample; // allocate the storage for the height map heightMap = new float[numSamples * numSamples]; if ( metersPerSample < oldMetersPerSample ) { // go to a higher level of detail int scale = oldMetersPerSample / metersPerSample; CopyHeightFieldScaleUp(oldHeightMap, scale, 0, 0, oldNumSamples); // generate the height map WorldManager.Instance.TerrainGenerator.GenerateHeightField(location, Size, metersPerSample, heightMap, out minHeight, out maxHeight, oldMetersPerSample); } else { // go to a lower level of detail int scale = metersPerSample / oldMetersPerSample; CopyHeightFieldScaleDown(oldHeightMap, scale, oldNumSamples, 0, 0); } // get rid of the old vertex and index buffers DisposeBuffers(); UpdateBounds(); } } /// <summary> /// Used to copy heightMap samples from a lower to higher level of detail. /// Can also be used for equal level of detail. /// Will work when source covers same or larger area than dest. /// /// The entire destination will be filled sparsely with height samples, and will need to be /// filled in with generated points if scale > 1. /// /// </summary> /// <param name="src"></param> /// <param name="scale"></param> /// <param name="srcXStart"></param> /// <param name="srcZStart"></param> protected void CopyHeightFieldScaleUp(float[] src, int scale, int srcXStart, int srcZStart, int srcNumSamples) { Debug.Assert(scale != 0); int srcZ = srcZStart; for ( int z = 0; z < numSamples; z += scale ) { int srcOff = srcZ * srcNumSamples + srcXStart; int destOff = z * numSamples; int srcX = srcXStart; for ( int x = 0; x < numSamples; x += scale ) { heightMap[destOff] = src[srcOff]; srcX++; srcOff++; destOff += scale; } srcZ++; } } /// <summary> /// Used to copy heightMap samples from a higher to lower level of detail. /// Can also be used for equal level of detail. /// Will work when source covers same or smaller area than dest. /// The area of the dest that is filled in will have all the samples filled. /// </summary> /// <param name="src"></param> /// <param name="scale"></param> /// <param name="srcNumSamples"></param> /// <param name="destXStart"></param> /// <param name="destZStart"></param> protected void CopyHeightFieldScaleDown(float[] src, int scale, int srcNumSamples, int destXStart, int destZStart) { int destZ = destZStart; Debug.Assert(scale != 0); for ( int z = 0; z < srcNumSamples; z += scale ) { int destX = destXStart; int destOff = destZ * numSamples + destX; int srcOff = z * srcNumSamples; for ( int x = 0; x < srcNumSamples; x += scale ) { heightMap[destOff] = src[srcOff]; destX++; destOff++; srcOff += scale; } destZ++; } } private static readonly int floatsPerVert = 8; unsafe private void fillVerts(HeightField src, float* buffer, int bufferOff, int numVerts, int xIndex, int zIndex, int xIndexIncr, int zIndexIncr, float xSampOffset, float zSampOffset, Vector3 pageLocation) { // convert from vert offset to float offset in the buffer bufferOff *= floatsPerVert; float unitsPerSample = src.metersPerSample * WorldManager.oneMeter; float xWorldOffset = xSampOffset * WorldManager.oneMeter; float zWorldOffset = zSampOffset * WorldManager.oneMeter; for (int n = 0; n < numVerts; n++ ) { float x = ( xIndex * unitsPerSample ) + xWorldOffset; float z = ( zIndex * unitsPerSample ) + zWorldOffset; float height = src.heightMap[zIndex * src.numSamples + xIndex]; // Position buffer[bufferOff++] = x; buffer[bufferOff++] = height; buffer[bufferOff++] = z; // normals // XXX - need to calculate normal here. Use straight up for now Vector3 norm = WorldManager.Instance.GetNormalAt(new Vector3(x + tile.Location.x, height, z + tile.Location.z)); buffer[bufferOff++] = norm.x; buffer[bufferOff++] = norm.y; buffer[bufferOff++] = norm.z; // Texture // XXX - assumes one unit of texture space is one page. // how does the vertex shader deal with texture coords? buffer[bufferOff++] = ( x + location.x - pageLocation.x ) / ( WorldManager.Instance.PageSize * WorldManager.oneMeter ); buffer[bufferOff++] = ( z + location.z - pageLocation.z ) / ( WorldManager.Instance.PageSize * WorldManager.oneMeter ); xIndex += xIndexIncr; zIndex += zIndexIncr; } } private int neighborSamples(StitchType type) { int ret; switch ( type ) { case StitchType.ToSame: ret = numSamples; break; case StitchType.ToLower: ret = numSamples / 2; break; case StitchType.ToHigher: ret = numSamples * 2; break; case StitchType.None: default: Debug.Assert(false, "stitching:attempted to get samples from non-existent neighbor"); ret = 0; break; } return ret; } /// <summary> /// If the stitchRenderable is not valid, then throw it away. A new one will /// be generated when needed. /// </summary> /// <param name="southMetersPerSample"></param> /// <param name="eastMetersPerSample"></param> public void ValidateStitch(int southMetersPerSample, int eastMetersPerSample) { if ( stitchRenderable != null ) { if ( ! stitchRenderable.IsValid(numSamples, southMetersPerSample, eastMetersPerSample) ) { stitchRenderable.Dispose(); stitchRenderable = null; } } } public void Stitch(HeightField south1, HeightField south2, HeightField east1, HeightField east2, HeightField southEast, bool stitchMiddleSouth, bool stitchMiddleEast) { Debug.Assert( ( south2 == null || south2.metersPerSample == south1.metersPerSample ), "south neighbors have different LOD"); Debug.Assert( ( east2 == null || east2.metersPerSample == east1.metersPerSample ), "east neighbors have different LOD"); // // Determine the stitch types for south and east direction // StitchType southStitchType; StitchType eastStitchType; int southMetersPerSample = 0; if ( south1 == null ) { southStitchType = StitchType.None; } else { southMetersPerSample = south1.metersPerSample; if ( south1.metersPerSample == metersPerSample ) { southStitchType = StitchType.ToSame; } else if ( south1.metersPerSample > metersPerSample ) { Debug.Assert(south1.metersPerSample == ( 2 * metersPerSample ), "stitching:south LOD not half"); southStitchType = StitchType.ToLower; } else { Debug.Assert( ( south1.metersPerSample * 2 ) == metersPerSample, "stitching: south LOD not double"); southStitchType = StitchType.ToHigher; } } int eastMetersPerSample = 0; if ( east1 == null ) { eastStitchType = StitchType.None; } else { eastMetersPerSample = east1.metersPerSample; if ( east1.metersPerSample == metersPerSample ) { eastStitchType = StitchType.ToSame; } else if ( east1.metersPerSample > metersPerSample ) { Debug.Assert(east1.metersPerSample == ( 2 * metersPerSample ), "stitching:east LOD not half"); eastStitchType = StitchType.ToLower; } else { Debug.Assert( ( east1.metersPerSample * 2 ) == metersPerSample, "stitching:east LOD not double"); eastStitchType = StitchType.ToHigher; } } if ( stitchRenderable != null ) { if ( stitchRenderable.IsValid(numSamples, southMetersPerSample, eastMetersPerSample) ) { // existing stitchRenderable is still ok, so just use it return; } else { stitchRenderable.Dispose(); stitchRenderable = null; } } // // The following combinations are acceptable: // 1) both same // 2) one same and one lower // 3) one same and one higher // 4) both lower // Debug.Assert( ( ( southStitchType == StitchType.ToSame ) || ( eastStitchType == StitchType.ToSame ) ) || ( ( southStitchType == StitchType.ToLower ) && ( eastStitchType == StitchType.ToLower ) ) || ( ( southStitchType == StitchType.None ) && ( eastStitchType == StitchType.None ) ), "stitching:invalid stitchType combination"); bool bothSame = false; bool bothLower = false; int vertexCount; if ( southStitchType == eastStitchType ) { if ( southStitchType == StitchType.ToSame ) { bothSame = true; vertexCount = numSamples * 4; } else if ( southStitchType == StitchType.ToLower ) { bothLower = true; vertexCount = numSamples * 3; } else { // both are StitchType.None, which means we are at the NE corner, so we dont need stitching return; } } else { if ( ( southStitchType == StitchType.ToLower ) || ( eastStitchType == StitchType.ToLower ) ) { // one same and one lower vertexCount = numSamples * 3 + ( numSamples / 2 ); } else if ( ( southStitchType == StitchType.ToHigher ) || ( eastStitchType == StitchType.ToHigher ) ) { // one same and one higher vertexCount = numSamples * 5; } else { // one same and one none vertexCount = numSamples * 2; } } VertexData vertexData = new VertexData(); vertexData.vertexCount = vertexCount; vertexData.vertexStart = 0; // set up the vertex declaration int vDecOffset = 0; vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float3, VertexElementSemantic.Position); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float3); vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float3, VertexElementSemantic.Normal); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float3); vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float2, VertexElementSemantic.TexCoords); vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float2); // create the hardware vertex buffer and set up the buffer binding HardwareVertexBuffer hvBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( vertexData.vertexDeclaration.GetVertexSize(0), vertexData.vertexCount, BufferUsage.StaticWriteOnly, false); vertexData.vertexBufferBinding.SetBinding(0, hvBuffer); // lock the vertex buffer IntPtr ipBuf = hvBuffer.Lock(BufferLocking.Discard); int bufferOff = 0; int southSamples = 0; int eastSamples = 0; int vertOff = 0; unsafe { float* buffer = (float *) ipBuf.ToPointer(); if ( southStitchType != StitchType.None ) { // // First the south edge of this tile // fillVerts(this, buffer, vertOff, numSamples, 0, numSamples - 1, 1, 0, 0, 0, tile.Page.Location); vertOff += numSamples; } if ( eastStitchType != StitchType.None ) { int adjust = 0; if ( southStitchType == StitchType.None ) { // include the inner corner because it wasnt done with the south edge adjust = 1; } // // Now the east edge of the tile // fillVerts(this, buffer, vertOff, numSamples - 1 + adjust, numSamples - 1, numSamples - 2 + adjust, 0, -1, 0, 0, tile.Page.Location); vertOff += ( numSamples - 1 + adjust ); } if ( southStitchType != StitchType.None ) { // // fill the verts from the south neighbor // southSamples = neighborSamples(southStitchType); if ( south2 == null ) { // only one southern neighbor int xStart = 0; int xSampOff = 0; if ( stitchMiddleSouth ) { // go from bottom to middle of east tile, rather than middle to top xStart = southSamples; xSampOff = -tile.Size; } fillVerts(south1, buffer, vertOff, southSamples, xStart, 0, 1, 0, xSampOff, tile.Size, tile.Page.Location); vertOff += southSamples; } else { // two southern neighbors int halfSamples = southSamples / 2; fillVerts(south1, buffer, vertOff, halfSamples, 0, 0, 1, 0, 0, tile.Size, tile.Page.Location); vertOff += halfSamples; fillVerts(south2, buffer, vertOff, halfSamples, 0, 0, 1, 0, south1.tile.Size, tile.Size, tile.Page.Location); vertOff += halfSamples; } } if ( ( southStitchType != StitchType.None ) && ( eastStitchType != StitchType.None ) ) { // // fill the single sample from the SE neighbor // if ( southEast == east1 ) { fillVerts(southEast, buffer, vertOff, 1, 0, neighborSamples(eastStitchType), 0, 0, tile.Size, 0, tile.Page.Location); } else if ( southEast == south1 ) { fillVerts(southEast, buffer, vertOff, 1, neighborSamples(southStitchType), 0, 0, 0, 0, tile.Size, tile.Page.Location); } else { fillVerts(southEast, buffer, vertOff, 1, 0, 0, 0, 0, tile.Size, tile.Size, tile.Page.Location); } vertOff++; } if ( eastStitchType != StitchType.None ) { // // fill the verts from the east neighbor // eastSamples = neighborSamples(eastStitchType); if ( east2 == null ) { // only one eastern neighbor int zStart = eastSamples - 1; int zSampOff = 0; if ( stitchMiddleEast ) { // go from bottom to middle of east tile, rather than middle to top zStart = ( eastSamples * 2 ) - 1; zSampOff = -tile.Size; } fillVerts(east1, buffer, vertOff, eastSamples, 0, zStart, 0, -1, tile.Size, zSampOff, tile.Page.Location); vertOff += eastSamples; } else { // two eastern neighbors int halfSamples = eastSamples / 2; fillVerts(east2, buffer, vertOff, halfSamples, 0, halfSamples - 1, 0, -1, tile.Size, east1.tile.Size, tile.Page.Location); vertOff += halfSamples; fillVerts(east1, buffer, vertOff, halfSamples, 0, halfSamples - 1, 0, -1, tile.Size, 0, tile.Page.Location); vertOff += halfSamples; } } Debug.Assert(vertexCount == vertOff, "stitching: generated incorrect number of vertices"); } hvBuffer.Unlock(); IndexData indexData = IndexBufferManager.Instance.GetStitchIndexBuffer(numSamples, southSamples, eastSamples); stitchRenderable = new StitchRenderable(this, vertexData, indexData, numSamples, southMetersPerSample, eastMetersPerSample); } public override void GetRenderOperation(RenderOperation op) { Debug.Assert(renderOp.vertexData != null, "attempting to render heightField with no vertexData"); Debug.Assert(renderOp.indexData != null, "attempting to render heightField with no indexData"); op.useIndices = this.renderOp.useIndices; op.operationType = this.renderOp.operationType; op.vertexData = this.renderOp.vertexData; op.indexData = this.renderOp.indexData; } public override void NotifyCurrentCamera( Axiom.Core.Camera cam ) { if (((Camera)(cam)).IsObjectVisible(this.worldAABB)) { isVisible = true; } else { isVisible = false; return; } } public override void UpdateRenderQueue(RenderQueue queue) { if ( isVisible ) { if (tile.Hilight) { material = tile.HilightMaterial; } else { material = normalMaterial; } if ( renderOp.vertexData == null ) { // the object is visible so we had better make sure it has vertex and index buffers renderOp.vertexData = buildVertexData(); renderOp.indexData = IndexBufferManager.Instance.GetTileIndexBuffer(numSamples); } if ( WorldManager.Instance.DrawTiles ) { queue.AddRenderable( this ); } if ( stitchRenderable == null ) { tile.Stitch(); } if ( WorldManager.Instance.DrawStitches && ( stitchRenderable != null ) ) { queue.AddRenderable( stitchRenderable ); } } } public override float GetSquaredViewDepth( Axiom.Core.Camera cam) { // Use squared length to avoid square root return (this.ParentNode.DerivedPosition - cam.DerivedPosition).LengthSquared; } public override float BoundingRadius { get { return 0f; } } public Tile Tile { get { return tile; } set { tile = value; } } public int MetersPerSample { get { return metersPerSample; } } public int NumSamples { get { return numSamples; } } public float this[int x,int z] { get { return heightMap[z * numSamples + x]; } } public int Size { get { return metersPerSample * numSamples; } } #region IDisposable Members private void DisposeBuffers() { renderOp.indexData = null; if ( renderOp.vertexData != null ) { renderOp.vertexData.vertexBufferBinding.GetBuffer(0).Dispose(); renderOp.vertexData.vertexBufferBinding.SetBinding(0, null); renderOp.vertexData = null; } if ( stitchRenderable != null ) { stitchRenderable.Dispose(); stitchRenderable = null; } } public void Dispose() { WorldManager.Instance.FogNotify -= new FogNotifyEventHandler(FogNotify); DisposeBuffers(); } #endregion } public enum StitchType { None, ToLower, ToSame, ToHigher } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Globalization; using System.IO; using CertEnrollInterop; using WebsitePanel.Providers.Common; using WebsitePanel.Server.Utils; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using Microsoft.Web.Administration; namespace WebsitePanel.Providers.Web.Iis { public class SSLModuleService80 : SSLModuleService { private const string CertificateStoreName = "WebHosting"; public bool UseSNI { get; private set; } public bool UseCCS { get; private set; } public string CCSUncPath { get; private set; } public string CCSCommonPassword { get; private set; } public SSLModuleService80(SslFlags sslFlags, string ccsUncPath, string ccsCommonPassword) { UseSNI = sslFlags.HasFlag(SslFlags.Sni); UseCCS = sslFlags.HasFlag(SslFlags.CentralCertStore); CCSUncPath = ccsUncPath; CCSCommonPassword = ccsCommonPassword; } public new SSLCertificate InstallCertificate(SSLCertificate cert, WebSite website) { try { var response = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; if (response == null) { throw new Exception("Cannot create instance of X509Enrollment.CX509Enrollment"); } response.Initialize(X509CertificateEnrollmentContext.ContextMachine); response.InstallResponse( InstallResponseRestrictionFlags.AllowUntrustedRoot, cert.Certificate, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, null ); // At this point, certificate has been installed into "Personal" store // We need to move it into "WebHosting" store // Get certificate var servercert = GetServerCertificates(StoreName.My.ToString()).Single(c => c.FriendlyName == cert.FriendlyName); // Get certificate data - the one we just added to "Personal" store var storeMy = new X509Store(StoreName.My, StoreLocation.LocalMachine); storeMy.Open(OpenFlags.MaxAllowed); X509CertificateCollection existCerts2 = storeMy.Certificates.Find(X509FindType.FindBySerialNumber, servercert.SerialNumber, false); var certData = existCerts2[0].Export(X509ContentType.Pfx); storeMy.Close(); var x509Cert = new X509Certificate2(certData, string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); if (UseCCS) { // Revert to InstallPfx to install new certificate - this also adds binding InstallPfx(certData, string.Empty, website); } else { // Add new certificate to "WebHosting" store var store = new X509Store(CertificateStoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(x509Cert); store.Close(); } // Remove certificate from "Personal" store storeMy.Open(OpenFlags.MaxAllowed); X509CertificateCollection existCerts = storeMy.Certificates.Find(X509FindType.FindBySerialNumber, servercert.SerialNumber, false); storeMy.Remove((X509Certificate2)existCerts[0]); storeMy.Close(); // Fill object with certificate data cert.SerialNumber = servercert.SerialNumber; cert.ValidFrom = servercert.ValidFrom; cert.ExpiryDate = servercert.ExpiryDate; cert.Hash = servercert.Hash; cert.DistinguishedName = servercert.DistinguishedName; if (!UseCCS) { if (CheckCertificate(website)) { DeleteCertificate(GetCurrentSiteCertificate(website), website); } AddBinding(x509Cert, website); } } catch (Exception ex) { Log.WriteError("Error adding SSL certificate", ex); cert.Success = false; } return cert; } public new List<SSLCertificate> GetServerCertificates() { // Get certificates from both WebHosting and My (Personal) store var certificates = GetServerCertificates(CertificateStoreName); certificates.AddRange(GetServerCertificates(StoreName.My.ToString())); return certificates; } public new SSLCertificate ImportCertificate(WebSite website) { SSLCertificate certificate; try { certificate = GetCurrentSiteCertificate(website); } catch (Exception ex) { certificate = new SSLCertificate { Success = false, Certificate = ex.ToString() }; } return certificate ?? (new SSLCertificate {Success = false, Certificate = "No certificate in binding on server, please remove or edit binding"}); } public new SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website) { SSLCertificate newcert = null, oldcert = null; // Ensure we perform operations safely and preserve the original state during all manipulations, save the oldcert if one is used if (CheckCertificate(website)) { oldcert = GetCurrentSiteCertificate(website); } X509Certificate2 x509Cert; var store = new X509Store(CertificateStoreName, StoreLocation.LocalMachine); if (UseCCS) { // We need to use this constructor or we won't be able to export this certificate x509Cert = new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); var certData = x509Cert.Export(X509ContentType.Pfx); var convertedCert = new X509Certificate2(certData, string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Attempts to move certificate to CCS UNC path try { // Create a stream out of that new certificate certData = convertedCert.Export(X509ContentType.Pfx, CCSCommonPassword); // Open UNC path and set path to certificate subject var filename = (CCSUncPath.EndsWith("/") ? CCSUncPath: CCSUncPath + "/") + x509Cert.GetNameInfo(X509NameType.SimpleName, false) + ".pfx"; var writer = new BinaryWriter(File.Open(filename, FileMode.Create)); writer.Write(certData); writer.Flush(); writer.Close(); // Certificate saved } catch (Exception ex) { // Log error Log.WriteError("SSLModuleService could not save certificate to Centralized Certificate Store", ex); // Re-throw throw; } } else { x509Cert = new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Step 1: Register X.509 certificate in the store // Trying to keep X.509 store open as less as possible try { store.Open(OpenFlags.ReadWrite); store.Add(x509Cert); } catch (Exception ex) { Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex); // Re-throw error throw; } finally { store.Close(); } } // Step 2: Instantiate a copy of new X.509 certificate try { newcert = GetSSLCertificateFromX509Certificate2(x509Cert); } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, null, website, "SSLModuleService could not instantiate a copy of new X.509 certificate.", ex); } // Step 3: Remove old certificate from the web site if any try { // Check if certificate already exists, remove it. if (oldcert != null) { DeleteCertificate(oldcert, website); } } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, null, website, string.Format("SSLModuleService could not remove existing certificate from '{0}' web site.", website.Name), ex); } // Step 4: Register new certificate with HTTPS binding on the web site try { AddBinding(x509Cert, website); } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, oldcert, website, String.Format("SSLModuleService could not add new X.509 certificate to '{0}' web site.", website.Name), ex); } return newcert; } public new byte[] ExportPfx(string serialNumber, string password) { if (UseCCS) { // This is not a good way to do it // Find cert by somehow perhaps first looking in the database? There vi kan lookup the serialnumber and find the hostname needed to create the path to the cert in CCS and then we can load the certdata into a cert and do a export with new password. // Another solution would be to look through all SSL-bindings on all sites until we found the site with the binding that has this serialNumber. But serialNumber is not good enough, we need hash that is unique and present in bindingInfo // A third solution is to iterate over all files in CCS, load them into memory and find the one with the correct serialNumber, but that cannot be good if there are thousands of files... foreach (var file in Directory.GetFiles(CCSUncPath)) { var fileStream = File.OpenRead(file); // Read certificate data from file var certData = new byte[fileStream.Length]; fileStream.Read(certData, 0, (int) fileStream.Length); var convertedCert = new X509Certificate2(certData, CCSCommonPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); fileStream.Close(); if (convertedCert.SerialNumber == serialNumber) { return convertedCert.Export(X509ContentType.Pfx, password); } } } var store = new X509Store(CertificateStoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var cert = store.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, false)[0]; var exported = cert.Export(X509ContentType.Pfx, password); return exported; } public void AddBinding(X509Certificate2 certificate, WebSite website) { using (var srvman = GetServerManager()) { // Look for dedicated ip var dedicatedIp = SiteHasBindingWithDedicatedIp(srvman, website); // Look for all the hostnames this certificate is valid for if we are using SNI var hostNames = new List<string>(); if (!dedicatedIp) { hostNames.AddRange(certificate.Extensions.Cast<X509Extension>() .Where(e => e.Oid.Value == "2.5.29.17") // Subject Alternative Names .SelectMany(e => e.Format(true).Split(new[] {"\r\n", "\n", "\n"}, StringSplitOptions.RemoveEmptyEntries).Where(s => s.Contains("=")).Select(s => s.Split('=')[1])).Where(s => !s.Contains(" "))); } var simpleName = certificate.GetNameInfo(X509NameType.SimpleName, false); if (hostNames.All(h => h != simpleName)) { hostNames.Add(simpleName); } var wildcardHostName = hostNames.SingleOrDefault(h => h.StartsWith("*.")); // If a wildcard certificate is used if (wildcardHostName != null) { if (!dedicatedIp) { // If using a wildcard ssl and not a dedicated IP, we take all the matching bindings on the site and use it to bind to SSL also. hostNames.Remove(wildcardHostName); hostNames.AddRange(website.Bindings.Where(b => !string.IsNullOrEmpty(b.Host) && b.Host.EndsWith(wildcardHostName.Substring(2))).Select(b => b.Host)); } } // For every hostname foreach (var hostName in hostNames) { var bindingIpAddress = string.IsNullOrEmpty(website.SiteInternalIPAddress) ? website.SiteIPAddress : website.SiteInternalIPAddress; var bindingInformation = string.Format("{0}:443:{1}", bindingIpAddress ?? "*", dedicatedIp ? "" : hostName); Binding siteBinding = UseCCS ? srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, "https") : srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, certificate.GetCertHash(), CertificateStoreName); if (UseSNI && !dedicatedIp) { siteBinding.SslFlags |= SslFlags.Sni; } if (UseCCS) { siteBinding.SslFlags |= SslFlags.CentralCertStore; } } srvman.CommitChanges(); } } public new ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website) { // This method removes all https bindings and all certificates associated with them. // Old implementation (IIS70) removed a single binding (there could not be more than one) and the first certificate that matched via serial number var result = new ResultObject { IsSuccess = true }; if (certificate == null) { return result; } try { var certificatesAndStoreNames = new List<Tuple<string, byte[]>>(); // User servermanager to get aLL SSL-bindings on this website and try to remove the certificates used using (var srvman = GetServerManager()) { var site = srvman.Sites[website.Name]; var bindings = site.Bindings.Where(b => b.Protocol == "https"); foreach (Binding binding in bindings.ToList()) { if (binding.SslFlags.HasFlag(SslFlags.CentralCertStore)) { if (!string.IsNullOrWhiteSpace(CCSUncPath) && Directory.Exists(CCSUncPath)) { // This is where it will be if CCS is used var path = GetCCSPath(certificate.Hostname); if (File.Exists(path)) { File.Delete(path); } // If binding with hostname, also try to delete with the hostname in the binding // This is because if SNI is used, several bindings are created for every valid name in the cerificate, but only one name exists in the SSLCertificate if (!string.IsNullOrEmpty(binding.Host)) { path = GetCCSPath(binding.Host); if (File.Exists(path)) { File.Delete(path); } } } } else { var certificateAndStoreName = new Tuple<string, byte[]>(binding.CertificateStoreName, binding.CertificateHash); if (!string.IsNullOrEmpty(binding.CertificateStoreName) && !certificatesAndStoreNames.Contains(certificateAndStoreName)) { certificatesAndStoreNames.Add(certificateAndStoreName); } } // Remove binding from site site.Bindings.Remove(binding); } srvman.CommitChanges(); foreach (var certificateAndStoreName in certificatesAndStoreNames) { // Delete all certs with the same serialnumber in Store var store = new X509Store(certificateAndStoreName.Item1, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, BitConverter.ToString(certificateAndStoreName.Item2).Replace("-", ""), false); foreach (var cert in certs) { store.Remove(cert); } store.Close(); } } } catch (Exception ex) { Log.WriteError(String.Format("Unable to delete certificate for website {0}", website.Name), ex); result.IsSuccess = false; result.AddError("", ex); } return result; } public new SSLCertificate GetCurrentSiteCertificate(WebSite website) { using (var srvman = GetServerManager()) { var site = srvman.Sites[website.SiteId]; var sslBinding = site.Bindings.First(b => b.Protocol == "https"); // If the certificate is in the central store if (((SslFlags)Enum.Parse(typeof(SslFlags), sslBinding["sslFlags"].ToString())).HasFlag(SslFlags.CentralCertStore)) { // Let's try to match binding host and certificate filename var path = GetCCSPath(sslBinding.Host); if (File.Exists(path)) { var fileStream = File.OpenRead(path); // Read certificate data from file var certData = new byte[fileStream.Length]; fileStream.Read(certData, 0, (int) fileStream.Length); var cert = new X509Certificate2(certData, CCSCommonPassword); fileStream.Close(); return GetSSLCertificateFromX509Certificate2(cert); } } else { var currentHash = Convert.ToBase64String(sslBinding.CertificateHash); return GetServerCertificates().FirstOrDefault(c => Convert.ToBase64String(c.Hash) == currentHash); } } return null; } private static List<SSLCertificate> GetServerCertificates(string certificateStoreName) { var store = new X509Store(certificateStoreName, StoreLocation.LocalMachine); List<SSLCertificate> certificates; try { store.Open(OpenFlags.ReadOnly); certificates = store.Certificates.Cast<X509Certificate2>().Select(GetSSLCertificateFromX509Certificate2).ToList(); } catch (Exception ex) { Log.WriteError( String.Format("SSLModuleService is unable to get certificates from X509Store('{0}', '{1}') and complete GetServerCertificates call", store.Name, store.Location), ex); // Re-throw exception throw; } finally { store.Close(); } return certificates; } private string GetCCSPath(string bindingName) { return (CCSUncPath.EndsWith("/") ? CCSUncPath : CCSUncPath + "/") + bindingName + ".pfx"; } private static SSLCertificate GetSSLCertificateFromX509Certificate2(X509Certificate2 cert) { var certificate = new SSLCertificate { Hostname = cert.GetNameInfo(X509NameType.SimpleName, false), FriendlyName = cert.FriendlyName, CSRLength = Convert.ToInt32(cert.PublicKey.Key.KeySize.ToString(CultureInfo.InvariantCulture)), Installed = true, DistinguishedName = cert.Subject, Hash = cert.GetCertHash(), SerialNumber = cert.SerialNumber, ExpiryDate = DateTime.Parse(cert.GetExpirationDateString()), ValidFrom = DateTime.Parse(cert.GetEffectiveDateString()), Success = true }; return certificate; } private static bool SiteHasBindingWithDedicatedIp(ServerManager srvman, WebSite website) { try { var bindings = srvman.Sites[website.SiteId].Bindings; return bindings.Any(b => string.IsNullOrEmpty(b.Host) && b.BindingInformation.Split(':')[1] != "*"); } catch { return false; } } private void HandleExceptionAndRollbackCertificate(X509Store store, X509Certificate2 x509Cert, SSLCertificate oldCert, WebSite webSite, string errorMessage, Exception ex) { if (!UseCCS) { try { // Rollback X.509 store changes store.Open(OpenFlags.ReadWrite); store.Remove(x509Cert); store.Close(); } catch (Exception) { Log.WriteError("SSLModuleService could not rollback and remove certificate from store", ex); } // Install old certificate back if any if (oldCert != null) InstallCertificate(oldCert, webSite); } // Log the error Log.WriteError(errorMessage + " All changes have been rolled back.", ex); // Re-throw throw ex; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading; namespace OpenSim.Region.CoreModules.Scripting.ScriptModuleComms { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ScriptModuleCommsModule")] public class ScriptModuleCommsModule : INonSharedRegionModule, IScriptModuleComms { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[MODULE COMMS]"; private ThreadedClasses.RwLockedDictionary<string, object> m_constants = new ThreadedClasses.RwLockedDictionary<string, object>(); #region ScriptInvocation protected class ScriptInvocationData { public Delegate ScriptInvocationDelegate { get; private set; } public string FunctionName { get; private set; } public Type[] TypeSignature { get; private set; } public Type ReturnType { get; private set; } public ScriptInvocationData(string fname, Delegate fn, Type[] callsig, Type returnsig) { FunctionName = fname; ScriptInvocationDelegate = fn; TypeSignature = callsig; ReturnType = returnsig; } } private ThreadedClasses.RwLockedDictionary<string, ScriptInvocationData> m_scriptInvocation = new ThreadedClasses.RwLockedDictionary<string, ScriptInvocationData>(); #endregion private IScriptModule m_scriptModule = null; public event ScriptCommand OnScriptCommand; #region RegionModuleInterface public void Initialise(IConfigSource config) { } public void AddRegion(Scene scene) { scene.RegisterModuleInterface<IScriptModuleComms>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { m_scriptModule = scene.RequestModuleInterface<IScriptModule>(); if (m_scriptModule != null) m_log.Info("[MODULE COMMANDS]: Script engine found, module active"); } public string Name { get { return "ScriptModuleCommsModule"; } } public Type ReplaceableInterface { get { return null; } } public void Close() { } #endregion #region ScriptModuleComms public void RaiseEvent(UUID script, string id, string module, string command, string k) { ScriptCommand c = OnScriptCommand; if (c == null) return; c(script, id, module, command, k); } public void DispatchReply(UUID script, int code, string text, string k) { if (m_scriptModule == null) return; Object[] args = new Object[] {-1, code, text, k}; m_scriptModule.PostScriptEvent(script, "link_message", args); } private static MethodInfo GetMethodInfoFromType(Type target, string meth, bool searchInstanceMethods) { BindingFlags getMethodFlags = BindingFlags.NonPublic | BindingFlags.Public; if (searchInstanceMethods) getMethodFlags |= BindingFlags.Instance; else getMethodFlags |= BindingFlags.Static; return target.GetMethod(meth, getMethodFlags); } public void RegisterScriptInvocation(object target, string meth) { MethodInfo mi = GetMethodInfoFromType(target.GetType(), meth, true); if (mi == null) { m_log.WarnFormat("{0} Failed to register method {1}", LogHeader, meth); return; } RegisterScriptInvocation(target, mi); } public void RegisterScriptInvocation(object target, string[] meth) { foreach (string m in meth) RegisterScriptInvocation(target, m); } public void RegisterScriptInvocation(object target, MethodInfo mi) { // m_log.DebugFormat("[MODULE COMMANDS] Register method {0} from type {1}", mi.Name, (target is Type) ? ((Type)target).Name : target.GetType().Name); Type delegateType = typeof(void); List<Type> typeArgs = mi.GetParameters() .Select(p => p.ParameterType) .ToList(); if (mi.ReturnType == typeof(void)) { delegateType = Expression.GetActionType(typeArgs.ToArray()); } else { try { typeArgs.Add(mi.ReturnType); delegateType = Expression.GetFuncType(typeArgs.ToArray()); } catch (Exception e) { m_log.ErrorFormat("{0} Failed to create function signature. Most likely more than 5 parameters. Method={1}. Error={2}", LogHeader, mi.Name, e); } } Delegate fcall; if (!(target is Type)) fcall = Delegate.CreateDelegate(delegateType, target, mi); else fcall = Delegate.CreateDelegate(delegateType, (Type)target, mi.Name); ParameterInfo[] parameters = fcall.Method.GetParameters(); if (parameters.Length < 2) // Must have two UUID params return; // Hide the first two parameters Type[] parmTypes = new Type[parameters.Length - 2]; for (int i = 2; i < parameters.Length; i++) parmTypes[i - 2] = parameters[i].ParameterType; m_scriptInvocation[fcall.Method.Name] = new ScriptInvocationData(fcall.Method.Name, fcall, parmTypes, fcall.Method.ReturnType); } public void RegisterScriptInvocation(Type target, string[] methods) { foreach (string method in methods) { MethodInfo mi = GetMethodInfoFromType(target, method, false); if (mi == null) m_log.WarnFormat("[MODULE COMMANDS] Failed to register method {0}", method); else RegisterScriptInvocation(target, mi); } } public void RegisterScriptInvocations(IRegionModuleBase target) { foreach(MethodInfo method in target.GetType().GetMethods( BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if(method.GetCustomAttributes( typeof(ScriptInvocationAttribute), true).Any()) { if(method.IsStatic) RegisterScriptInvocation(target.GetType(), method); else RegisterScriptInvocation(target, method); } } } public Delegate[] GetScriptInvocationList() { List<Delegate> ret = new List<Delegate>(); m_scriptInvocation.ForEach(delegate(ScriptInvocationData d) { ret.Add(d.ScriptInvocationDelegate); }); return ret.ToArray(); } public string LookupModInvocation(string fname) { ScriptInvocationData sid; if (m_scriptInvocation.TryGetValue(fname,out sid)) { if (sid.ReturnType == typeof(string)) return "modInvokeS"; else if (sid.ReturnType == typeof(int)) return "modInvokeI"; else if (sid.ReturnType == typeof(float)) return "modInvokeF"; else if (sid.ReturnType == typeof(UUID)) return "modInvokeK"; else if (sid.ReturnType == typeof(OpenMetaverse.Vector3)) return "modInvokeV"; else if (sid.ReturnType == typeof(OpenMetaverse.Quaternion)) return "modInvokeR"; else if (sid.ReturnType == typeof(object[])) return "modInvokeL"; m_log.WarnFormat("[MODULE COMMANDS] failed to find match for {0} with return type {1}",fname,sid.ReturnType.Name); } return null; } public Delegate LookupScriptInvocation(string fname) { ScriptInvocationData sid; if (m_scriptInvocation.TryGetValue(fname,out sid)) return sid.ScriptInvocationDelegate; return null; } public Type[] LookupTypeSignature(string fname) { ScriptInvocationData sid; if (m_scriptInvocation.TryGetValue(fname,out sid)) return sid.TypeSignature; return null; } public Type LookupReturnType(string fname) { ScriptInvocationData sid; if (m_scriptInvocation.TryGetValue(fname,out sid)) return sid.ReturnType; return null; } public object InvokeOperation(UUID hostid, UUID scriptid, string fname, params object[] parms) { List<object> olist = new List<object>(); olist.Add(hostid); olist.Add(scriptid); foreach (object o in parms) olist.Add(o); Delegate fn = LookupScriptInvocation(fname); return fn.DynamicInvoke(olist.ToArray()); } /// <summary> /// Operation to for a region module to register a constant to be used /// by the script engine /// </summary> public void RegisterConstant(string cname, object value) { // m_log.DebugFormat("[MODULE COMMANDS] register constant <{0}> with value {1}",cname,value.ToString()); m_constants.Add(cname,value); } public void RegisterConstants(IRegionModuleBase target) { foreach (FieldInfo field in target.GetType().GetFields( BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) { if (field.GetCustomAttributes( typeof(ScriptConstantAttribute), true).Any()) { RegisterConstant(field.Name, field.GetValue(target)); } } } /// <summary> /// Operation to check for a registered constant /// </summary> public object LookupModConstant(string cname) { // m_log.DebugFormat("[MODULE COMMANDS] lookup constant <{0}>",cname); object value = null; if (m_constants.TryGetValue(cname,out value)) return value; return null; } /// <summary> /// Get all registered constants /// </summary> public Dictionary<string, object> GetConstants() { return new Dictionary<string,object>(m_constants); } #endregion } }
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(); } } // Use a static instance of the windows hook to prevent stack overflows in the windows kernel. [ThreadStatic] private static LocalWindowsHook sm_localWindowsHook; private LocalWindowsHook.HookEventHandler m_hookEventHandler; public FocusManagerImpl(DockPanel dockPanel) { m_dockPanel = dockPanel; if (Win32Helper.IsRunningOnMono) return; m_hookEventHandler = new LocalWindowsHook.HookEventHandler(HookEventHandler); // Ensure the windows hook has been created for this thread if (sm_localWindowsHook == null) { sm_localWindowsHook = new LocalWindowsHook(Win32.HookType.WH_CALLWNDPROCRET); sm_localWindowsHook.Install(); } sm_localWindowsHook.HookInvoked += m_hookEventHandler; } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } private bool m_disposed = false; protected override void Dispose(bool disposing) { if (!m_disposed && disposing) { if (!Win32Helper.IsRunningOnMono) { sm_localWindowsHook.HookInvoked -= m_hookEventHandler; } 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; } if (content == null) return; DockContentHandler handler = content.DockHandler; if (handler.Form.IsDisposed) return; // Should not reach here, but better than throwing an exception if (ContentContains(content, handler.ActiveWindowHandle)) { if (!Win32Helper.IsRunningOnMono) { NativeMethods.SetFocus(handler.ActiveWindowHandle); } } if (handler.Form.ContainsFocus) return; if (handler.Form.SelectNextControl(handler.Form.ActiveControl, true, true, true, true)) return; if (Win32Helper.IsRunningOnMono) return; // 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) Activate(prev); else if (ListContent.Count > 0) Activate(ListContent[ListContent.Count - 1]); } else if (LastActiveContent != null) Activate(LastActiveContent); else if (ListContent.Count > 0) Activate(ListContent[ListContent.Count - 1]); } 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++; if (!Win32Helper.IsRunningOnMono) sm_localWindowsHook.HookInvoked -= m_hookEventHandler; } public void ResumeFocusTracking() { if (m_countSuspendFocusTracking > 0) m_countSuspendFocusTracking--; if (m_countSuspendFocusTracking == 0) { if (ContentActivating != null) { Activate(ContentActivating); ContentActivating = null; } if (!Win32Helper.IsRunningOnMono) sm_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 || msg == Win32.Msgs.WM_MDIACTIVATE) 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 = Win32Helper.IsRunningOnMono ? null : 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 && DockPanel.DockWindows != 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); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace TerribleWebApi.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); } } } }