context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This regression algorithm tests In The Money (ITM) future option expiry for puts. /// We expect 3 orders from the algorithm, which are: /// /// * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1) /// * Option exercise, receiving short ES future contracts (sell, qty -1) /// * Future contract liquidation, due to impending expiry (buy qty 1) /// /// Additionally, we test delistings for future options and assert that our /// portfolio holdings reflect the orders the algorithm has submitted. /// </summary> public class FutureOptionPutITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _es19m20; private Symbol _esOption; private Symbol _expectedContract; public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 6, 30); _es19m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; // Select a future option expiring ITM, and adds it to the algorithm. _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time) .Where(x => x.ID.StrikePrice >= 3300m && x.ID.OptionRight == OptionRight.Put) .OrderBy(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute).Symbol; _expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3300m, new DateTime(2020, 6, 19)); if (_esOption != _expectedContract) { throw new Exception($"Contract {_expectedContract} was not found in the chain"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () => { MarketOrder(_esOption, 1); }); } public override void OnData(Slice data) { // Assert delistings, so that we can make sure that we receive the delisting warnings at // the expected time. These assertions detect bug #4872 foreach (var delisting in data.Delistings.Values) { if (delisting.Type == DelistingType.Warning) { if (delisting.Time != new DateTime(2020, 6, 19)) { throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}"); } } if (delisting.Type == DelistingType.Delisted) { if (delisting.Time != new DateTime(2020, 6, 20)) { throw new Exception($"Delisting happened at unexpected date: {delisting.Time}"); } } } } public override void OnOrderEvent(OrderEvent orderEvent) { if (orderEvent.Status != OrderStatus.Filled) { // There's lots of noise with OnOrderEvent, but we're only interested in fills. return; } if (!Securities.ContainsKey(orderEvent.Symbol)) { throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}"); } var security = Securities[orderEvent.Symbol]; if (security.Symbol == _es19m20) { AssertFutureOptionOrderExercise(orderEvent, security, Securities[_expectedContract]); } else if (security.Symbol == _expectedContract) { AssertFutureOptionContractOrder(orderEvent, security); } else { throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}"); } Log($"{Time:yyyy-MM-dd HH:mm:ss} -- {orderEvent.Symbol} :: Price: {Securities[orderEvent.Symbol].Holdings.Price} Qty: {Securities[orderEvent.Symbol].Holdings.Quantity} Direction: {orderEvent.Direction} Msg: {orderEvent.Message}"); } private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract) { var expectedLiquidationTimeUtc = new DateTime(2020, 6, 20, 4, 0, 0); if (orderEvent.Direction == OrderDirection.Buy && future.Holdings.Quantity != 0) { // We expect the contract to have been liquidated immediately throw new Exception($"Did not liquidate existing holdings for Symbol {future.Symbol}"); } if (orderEvent.Direction == OrderDirection.Buy && orderEvent.UtcTime != expectedLiquidationTimeUtc) { throw new Exception($"Liquidated future contract, but not at the expected time. Expected: {expectedLiquidationTimeUtc:yyyy-MM-dd HH:mm:ss} - found {orderEvent.UtcTime:yyyy-MM-dd HH:mm:ss}"); } // No way to detect option exercise orders or any other kind of special orders // other than matching strings, for now. if (orderEvent.Message.Contains("Option Exercise")) { if (orderEvent.FillPrice != 3300m) { throw new Exception("Option did not exercise at expected strike price (3300)"); } if (future.Holdings.Quantity != -1) { // Here, we expect to have some holdings in the underlying, but not in the future option anymore. throw new Exception($"Exercised option contract, but we have no holdings for Future {future.Symbol}"); } if (optionContract.Holdings.Quantity != 0) { throw new Exception($"Exercised option contract, but we have holdings for Option contract {optionContract.Symbol}"); } } } private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option) { if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1) { throw new Exception($"No holdings were created for option contract {option.Symbol}"); } if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0) { throw new Exception($"Holdings were found after a filled option exercise"); } if (orderEvent.Message.Contains("Exercise") && option.Holdings.Quantity != 0) { throw new Exception($"Holdings were found after exercising option contract {option.Symbol}"); } } /// <summary> /// Ran at the end of the algorithm to ensure the algorithm has no holdings /// </summary> /// <exception cref="Exception">The algorithm has holdings</exception> public override void OnEndOfAlgorithm() { if (Portfolio.Invested) { throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "3"}, {"Average Win", "4.18%"}, {"Average Loss", "-8.26%"}, {"Compounding Annual Return", "-8.884%"}, {"Drawdown", "4.400%"}, {"Expectancy", "-0.247"}, {"Net Profit", "-4.427%"}, {"Sharpe Ratio", "-1.283"}, {"Probabilistic Sharpe Ratio", "0.001%"}, {"Loss Rate", "50%"}, {"Win Rate", "50%"}, {"Profit-Loss Ratio", "0.51"}, {"Alpha", "-0.061"}, {"Beta", "0.002"}, {"Annual Standard Deviation", "0.048"}, {"Annual Variance", "0.002"}, {"Information Ratio", "-0.221"}, {"Tracking Error", "0.376"}, {"Treynor Ratio", "-24.544"}, {"Total Fees", "$1.85"}, {"Estimated Strategy Capacity", "$330000000.00"}, {"Lowest Capacity Asset", "ES 31EL5FAOOQON8|ES XFH59UK0MYO1"}, {"Fitness Score", "0.008"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-0.225"}, {"Return Over Maximum Drawdown", "-2.009"}, {"Portfolio Turnover", "0.023"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "99f96f433bc76c31cb25bcd9117a6bf1"} }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_CTYPES #pragma warning disable SYSLIB0004 // The Constrained Execution Region (CER) feature is not supported in .NET 5.0. using System; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Text; using System.Threading; using IronPython.Runtime; namespace IronPython.Modules { /// <summary> /// A wrapper around allocated memory to ensure it gets released and isn't accessed /// when it could be finalized. /// </summary> internal sealed class MemoryHolder : CriticalFinalizerObject { private readonly IntPtr _data; private readonly bool _ownsData; private readonly int _size; private PythonDictionary _objects; #pragma warning disable 414 // TODO: unused field? private readonly MemoryHolder _parent; #pragma warning restore 414 /// <summary> /// Creates a new MemoryHolder and allocates a buffer of the specified size. /// </summary> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public MemoryHolder(int size) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { _size = size; _data = NativeFunctions.Calloc(new IntPtr(size)); if (_data == IntPtr.Zero) { GC.SuppressFinalize(this); throw new OutOfMemoryException(); } _ownsData = true; } } /// <summary> /// Creates a new MemoryHolder at the specified address which is not tracked /// by us and we will never free. /// </summary> public MemoryHolder(IntPtr data, int size) { GC.SuppressFinalize(this); _data = data; _size = size; } /// <summary> /// Creates a new MemoryHolder at the specified address which will keep alive the /// parent memory holder. /// </summary> public MemoryHolder(IntPtr data, int size, MemoryHolder parent) { GC.SuppressFinalize(this); _data = data; _parent = parent; _objects = parent._objects; _size = size; } /// <summary> /// Gets the address of the held memory. The caller should ensure the MemoryHolder /// is always alive as long as the address will continue to be accessed. /// </summary> public IntPtr UnsafeAddress { get { return _data; } } public int Size { get { return _size; } } /// <summary> /// Gets a list of objects which need to be kept alive for this MemoryHolder to be /// remain valid. /// </summary> public PythonDictionary Objects { get { return _objects; } set { _objects = value; } } internal PythonDictionary EnsureObjects() { if (_objects == null) { Interlocked.CompareExchange(ref _objects, new PythonDictionary(), null); } return _objects; } /// <summary> /// Used to track the lifetime of objects when one memory region depends upon /// another memory region. For example if you have an array of objects that /// each have an element which has it's own lifetime the array needs to keep /// the individual elements alive. /// /// The keys used here match CPython's keys as tested by CPython's test_ctypes. /// Typically they are a string which is the array index, "ffffffff" when /// from_buffer is used, or when it's a simple type there's just a string /// instead of the full dictionary - we store that under the key "str". /// </summary> internal void AddObject(object key, object value) { EnsureObjects()[key] = value; } private short Swap(short val) { return (short)((((ushort)val & 0xFF00) >> 8) | (((ushort)val & 0x00FF) << 8)); } private int Swap(int val) { // swap adjacent 16-bit blocks val = (int)(((uint)val >> 16) | ((uint)val << 16)); // swap adjacent 8-bit blocks return (int)((((uint)val & 0xFF00FF00) >> 8) | (((uint)val & 0x00FF00FF) << 8)); } private long Swap(long val) { // swap adjacent 32-bit blocks val = (long)(((ulong)val >> 32) | ((ulong)val << 32)); // swap adjacent 16-bit blocks val = (long)((((ulong)val & 0xFFFF0000FFFF0000) >> 16) | (((ulong)val & 0x0000FFFF0000FFFF) << 16)); // swap adjacent 8-bit blocks return (long)((((ulong)val & 0xFF00FF00FF00FF00) >> 8) | (((ulong)val & 0x00FF00FF00FF00FF) << 8)); } public byte ReadByte(int offset) { byte res = Marshal.ReadByte(_data, offset); GC.KeepAlive(this); return res; } public short ReadInt16(int offset, bool swap=false) { short res = Marshal.ReadInt16(_data, offset); GC.KeepAlive(this); if(swap) res = Swap(res); return res; } public int ReadInt32(int offset, bool swap=false) { int res = Marshal.ReadInt32(_data, offset); GC.KeepAlive(this); if(swap) res = Swap(res); return res; } public long ReadInt64(int offset, bool swap=false) { long res = Marshal.ReadInt64(_data, offset); GC.KeepAlive(this); if(swap) res = Swap(res); return res; } public IntPtr ReadIntPtr(int offset) { IntPtr res = Marshal.ReadIntPtr(_data, offset); GC.KeepAlive(this); return res; } public MemoryHolder ReadMemoryHolder(int offset) { IntPtr res = Marshal.ReadIntPtr(_data, offset); return new MemoryHolder(res, IntPtr.Size, this); } internal Bytes ReadBytes(int offset) { try { return ReadBytes(_data, offset); } finally { GC.KeepAlive(this); } } internal string ReadUnicodeString(int offset) { try { return Marshal.PtrToStringUni(_data.Add(offset)); } finally { GC.KeepAlive(this); } } internal Bytes ReadBytes(int offset, int length) { try { return ReadBytes(_data, offset, length); } finally { GC.KeepAlive(this); } } internal static Bytes ReadBytes(IntPtr addr, int offset, int length) { // instead of Marshal.PtrToStringAnsi we do this because // ptrToStringAnsi gives special treatment to values >= 128. var buffer = new byte[length]; if (checked(offset + length) < int.MaxValue) { for (int i = 0; i < length; i++) { buffer[i] = Marshal.ReadByte(addr, offset + i); } } return Bytes.Make(buffer); } internal static Bytes ReadBytes(IntPtr addr, int offset) { // instead of Marshal.PtrToStringAnsi we do this because // ptrToStringAnsi gives special treatment to values >= 128. MemoryStream res = new MemoryStream(); byte b; while((b = Marshal.ReadByte(addr, offset++)) != 0) { res.WriteByte(b); } return Bytes.Make(res.ToArray()); } internal string ReadUnicodeString(int offset, int length) { try { return Marshal.PtrToStringUni(_data.Add(offset), length); } finally { GC.KeepAlive(this); } } public void WriteByte(int offset, byte value) { Marshal.WriteByte(_data, offset, value); GC.KeepAlive(this); } public void WriteInt16(int offset, short value, bool swap=false) { Marshal.WriteInt16(_data, offset, swap ? Swap(value) : value); GC.KeepAlive(this); } public void WriteInt32(int offset, int value, bool swap=false) { Marshal.WriteInt32(_data, offset, swap ? Swap(value) : value); GC.KeepAlive(this); } public void WriteInt64(int offset, long value, bool swap=false) { Marshal.WriteInt64(_data, offset, swap ? Swap(value) : value); GC.KeepAlive(this); } public void WriteIntPtr(int offset, IntPtr value) { Marshal.WriteIntPtr(_data, offset, value); GC.KeepAlive(this); } public void WriteIntPtr(int offset, MemoryHolder address) { Marshal.WriteIntPtr(_data, offset, address.UnsafeAddress); GC.KeepAlive(this); GC.KeepAlive(address); } /// <summary> /// Copies the data in data into this MemoryHolder. /// </summary> public void CopyFrom(IntPtr source, IntPtr size) { NativeFunctions.MemCopy(_data, source, size); GC.KeepAlive(this); } internal void WriteUnicodeString(int offset, string value) { // TODO: There's gotta be a better way to do this for (int i = 0; i < value.Length; i++) { WriteInt16(checked(offset + i * 2), (short)value[i]); } } internal void WriteSpan(int offset, ReadOnlySpan<byte> value) { for (int i = 0; i < value.Length; i++) { WriteByte(checked(offset + i), value[i]); } } public MemoryHolder GetSubBlock(int offset) { // No GC.KeepAlive here because the new MemoryHolder holds onto the previous one. return new MemoryHolder(_data.Add(offset), _size - offset, this); } /// <summary> /// Copies memory from one location to another keeping the associated memory holders alive during the /// operation. /// </summary> public void CopyTo(MemoryHolder/*!*/ destAddress, int writeOffset, int size) { NativeFunctions.MemCopy(destAddress._data.Add(writeOffset), _data, new IntPtr(size)); GC.KeepAlive(destAddress); GC.KeepAlive(this); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] ~MemoryHolder() { if (_ownsData) { Marshal.FreeHGlobal(_data); } } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Xml; using VersionOne.Parsers; using VersionOne.ServiceHost.Core.Utility; using VersionOne.ServiceHost.Core.Logging; using TDAPIOLELib; using IList = System.Collections.IList; namespace VersionOne.ServiceHost.QualityCenterServices { // TODO refactor and extract bunch of classes /// <summary> /// This class encapsulates the QualityCenter COM library. No other classes should directly use the COM library /// It does *not* know about the EventManager, or any event objects specific to ServiceHost /// The only knowledge it has of ServiceHost is use of a couple utility classes in ServiceHost.Core.Utility /// </summary> public class QualityCenterClient : IQualityCenterClient { private readonly ILogger log; private string url; private string userName; private string password; private readonly QCProject project; private TDConnection server; private TestFactory testFactory; private BugFactory bugFactory; private readonly IDictionary<string, string> defectFilters = new Dictionary<string, string>(); private string qcCreateStatusValue; private string qcCloseStatusValue; public QualityCenterClient(QCProject project, XmlNode config, ILogger log) { this.project = project; this.log = log; SetConfiguration(config); } public bool IsLoggedIn { get { return Server.LoggedIn; } } public bool IsConnected { get { return Server.Connected; } } public bool IsProjectConnected { get { return Server.ProjectConnected; } } public QCProject ProjectInfo { get { return project; } } private TDConnection Server { get { if (server == null) { server = new TDConnection(); } if (!server.Connected) { server.InitConnectionEx(url); } return server; } } private TestFactory TestFoundry { // This name is used so we don't confuse our TestFactory w/ QC TestFactory get { if (testFactory == null) { var treeManager = Server.TreeManager as TreeManager; if (treeManager == null) { throw new Exception("Quality Center did not return a TreeManager"); } var rootNode = treeManager["Subject"] as SubjectNode; if(rootNode == null) { throw new Exception("Quality Center does not contain a root folder called \"Subject\""); } SubjectNode versionOneNode; try { versionOneNode = (rootNode.FindChildNode(project.TestFolder) ?? rootNode.AddNode(project.TestFolder)) as SubjectNode; } catch (COMException ex) { log.Log(LogMessage.SeverityType.Debug, string.Format("Node Not Found"), ex); versionOneNode = rootNode.AddNode(project.TestFolder) as SubjectNode; } if (versionOneNode == null) { throw new Exception( string.Format( "Failed to create folder with the name {0}. It must be created manually for project {1}", project.TestFolder, project.Project)); } testFactory = versionOneNode.TestFactory as TestFactory; } return testFactory; } } private BugFactory BugFoundry { // This name is used so we don't confuse our BugFactory w/ QC BugFactory get { return bugFactory ?? (bugFactory = (BugFactory) Server.BugFactory); } } public static bool HasLastRun(object testObj) { var test = (Test) testObj; return test.LastRun != null; var x = test.LastRun != null; } public static string TestID(object testObj) { var test = (Test) testObj; return test.ID.ToString(); } public static DateTime TimeStamp(object testObj) { var test = (Test) testObj; return DateTime.Parse(test["TS_VTS"].ToString()); } public static string LastRunStatus(object testObj) { var test = (Test) testObj; return ((Run) test.LastRun).Status; } public static string DefectID(object bugObj) { var bug = (Bug) bugObj; return bug.ID.ToString(); } public static string DefectSummary(object bugObj) { var bug = (Bug) bugObj; return bug.Summary; } public static string DefectDescription(object bugObj) { var bug = (Bug) bugObj; return (string) bug["BG_DESCRIPTION"]; } public static string DefectPriority(object bugObj) { var bug = (Bug) bugObj; return bug.Priority; } public void Dispose() { Server.Disconnect(); Server.ReleaseConnection(); server = null; } public void Login() { if (!IsLoggedIn) { Server.Login(userName, password); } } public void ConnectToProject() { Login(); if (IsProjectConnected) { return; } try { Server.Connect(project.Domain, project.Project); } catch (COMException) { log.Log(LogMessage.SeverityType.Error, string.Format("*** Exception connecting to Domain=\"{0}\" Project=\"{1}\"", project.Domain, project.Project)); throw; } if (!IsConnected) { throw new ConfigurationException( string.Format("*** Failed to connect. Domain=\"{0}\" Project=\"{1}\"", project.Domain, project.Project)); } } public void Logout() { Server.Logout(); } public string CreateQCTest(string title, string description, string externalId) { ConnectToProject(); var test = TestFoundry.AddItem(DBNull.Value) as Test; test.Name = title; test["TS_DESCRIPTION"] = "<html><body>" + description + "</body></html>"; test["TS_STATUS"] = project.TestStatus; test[project.V1IdField] = externalId; test.Post(); return GetFullyQualifiedQCId(test.ID.ToString()); } // TODO use generic collections public IList GetLatestTestRuns(DateTime lastCheck) { IList testRuns = new ArrayList(); ConnectToProject(); var filterString = GetLastCheckFilterString(lastCheck); var filter = (TDFilter) TestFoundry.Filter; filter["TS_VTS"] = filterString; filter[project.V1IdField] = "AT*"; // This needs to be a global test factory so users can move test to other folders var factory = Server.TestFactory as TestFactory; if (factory == null) { throw new Exception("Quality Center failed to return a Test Factory"); } var tdTestList = factory.NewList(filter.Text); foreach (var testRun in tdTestList) { testRuns.Add(testRun); } return testRuns; } // TODO use generic collections public IList GetLatestDefects(DateTime lastCheck) { IList bugList = new ArrayList(); ConnectToProject(); var filter = (TDFilter) BugFoundry.Filter; foreach (var entry in defectFilters) { filter[entry.Key] = entry.Value; } foreach (var bug in BugFoundry.NewList(filter.Text)) { bugList.Add(bug); } return bugList; } public void OnDefectCreated(string id, ICollection comments, string link) { ConnectToProject(); var bug = UpdateDefectStatus(id, qcCreateStatusValue, comments); var attachmentFactory = (AttachmentFactory) bug.Attachments; var attachment = (Attachment) attachmentFactory.AddItem(link); attachment.Post(); } public bool OnDefectStateChange(string id, ICollection comments) { ConnectToProject(); return UpdateDefectStatus(id, qcCloseStatusValue, comments) != null; } public Bug GetQCDefect(string externalId) { var bugId = GetLocalQCId(externalId); return (Bug) BugFoundry[bugId]; } #region Methods that Only Exist for Testing public int GetTestCount() { Login(); ConnectToProject(); return TestFoundry.NewList("").Count; } public Bug CreateQCDefect() { ConnectToProject(); string summary = "A Test Defect " + Guid.NewGuid(); Bug bug = (Bug) BugFoundry.AddItem(summary); bug.Summary = summary; bug.Status = "New"; bug.AssignedTo = "VersionOne"; bug["BG_DESCRIPTION"] = "DESCRIPTION"; bug.Post(); return bug; } #endregion public string GetFullyQualifiedQCId(string localId) { return string.Format("{0}.{1}.{2}", project.Domain, project.Project, localId); } public string GetLocalQCId(string fullyQualifiedId) { return fullyQualifiedId.Substring(fullyQualifiedId.LastIndexOf(".") + 1); } #region Private Methods private void SetConfiguration(XmlNode config) { XmlNode connection = config["Connection"]; url = connection["ApplicationUrl"].InnerText; userName = connection["Username"].InnerText; password = connection["Password"].InnerText; foreach (XmlNode node in config["DefectFilters"].SelectNodes("DefectFilter")) { defectFilters.Add(node["FieldName"].InnerText, node["FieldValue"].InnerText); } qcCreateStatusValue = config["CreateStatusValue"].InnerText; qcCloseStatusValue = config["CloseStatusValue"].InnerText; } private Bug UpdateDefectStatus(string externalId, string newStatus, IEnumerable comments) { var bug = GetQCDefect(externalId); bug.Status = newStatus; var existingComments = (string) bug["BG_DEV_COMMENTS"]; bug["BG_DEV_COMMENTS"] = existingComments + BuildComments(comments, existingComments); bug.Post(); return bug; } private static string GetLastCheckFilterString(DateTime lastCheck) { return ">=\"" + lastCheck.ToString("yyyy-MM-dd HH:mm:00") + "\""; } private static string BuildComments(IEnumerable messages, string existingComments) { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine(); stringBuilder.Append("<html><body>"); if (!string.IsNullOrEmpty(existingComments)) { stringBuilder.Append("<br><font color=\"#000080\"><b>________________________________________</b></font><br>"); } stringBuilder.AppendFormat("<font color=\"#000080\"><b>VersionOne, {0}: </b></font><br/>", DateTime.Now); foreach (string comment in messages) { stringBuilder.Append(comment); stringBuilder.AppendLine("<br/>"); } stringBuilder.AppendLine("</body></html>"); return stringBuilder.ToString(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if FEATURE_ENCODINGNLS namespace System.Text { using System; using System.Diagnostics.Contracts; using System.Collections; using System.Runtime.Remoting; using System.Globalization; using System.Threading; using Win32Native = Microsoft.Win32.Win32Native; // This class overrides Encoding with the things we need for our NLS Encodings // // All of the GetBytes/Chars GetByte/CharCount methods are just wrappers for the pointer // plus decoder/encoder method that is our real workhorse. Note that this is an internal // class, so our public classes cannot derive from this class. Because of this, all of the // GetBytes/Chars GetByte/CharCount wrapper methods are duplicated in all of our public // encodings, which currently include: // // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, & UnicodeEncoding // // So if you change the wrappers in this class, you must change the wrappers in the other classes // as well because they should have the same behavior. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] internal abstract class EncodingNLS : Encoding { protected EncodingNLS(int codePage) : base(codePage) { } // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (chars.Length == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetByteCount(String s) { // Validate input if (s==null) throw new ArgumentNullException("s"); Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", Environment.GetResourceString("ArgumentOutOfRange_IndexCount")); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed ( byte* pBytes = bytes) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (chars.Length == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = bytes) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (bytes.Length == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (bytes.Length == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = chars) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (bytes.Length == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } } #endif // FEATURE_ENCODINGNLS
using Xunit; using System; using System.IO; using System.Diagnostics; using System.Management.Automation; namespace PSTests { [Collection("AssemblyLoadContext")] public static class PlatformTests { [Fact] public static void TestIsCoreCLR() { Assert.True(Platform.IsCoreCLR); } [Fact] public static void TestGetUserName() { var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "whoami", RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { // Get output of call to whoami without trailing newline string username = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); // The process should return an exit code of 0 on success Assert.Equal(0, process.ExitCode); // It should be the same as what our platform code returns Assert.Equal(username, Platform.Unix.UserName()); } } [Fact(Skip="Bad arguments for OS X")] public static void TestGetMachineName() { var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "hostname", RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { // Get output of call to hostname without trailing newline string hostname = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); // The process should return an exit code of 0 on success Assert.Equal(0, process.ExitCode); // It should be the same as what our platform code returns Assert.Equal(hostname, System.Management.Automation.Environment.MachineName); } } [Fact(Skip="Bad arguments for OS X")] public static void TestGetFQDN() { var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "hostname --fqdn", RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { // Get output of call to hostname without trailing newline string hostname = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); // The process should return an exit code of 0 on success Assert.Equal(0, process.ExitCode); // It should be the same as what our platform code returns Assert.Equal(hostname, Platform.NonWindowsGetHostName()); } } [Fact(Skip="Bad arguments for OS X")] public static void TestGetDomainName() { var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "dnsdomainname", RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { // Get output of call to hostname without trailing newline string domainName = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); // The process should return an exit code of 0 on success Assert.Equal(0, process.ExitCode); // It should be the same as what our platform code returns Assert.Equal(domainName, Platform.NonWindowsGetDomainName()); } } [Fact] public static void TestIsExecutable() { Assert.True(Platform.NonWindowsIsExecutable("/bin/ls")); } [Fact] public static void TestIsNotExecutable() { Assert.False(Platform.NonWindowsIsExecutable("/etc/hosts")); } [Fact] public static void TestDirectoryIsNotExecutable() { Assert.False(Platform.NonWindowsIsExecutable("/etc")); } [Fact] public static void TestFileIsNotHardLink() { string path = @"/tmp/nothardlink"; if (File.Exists(path)) { File.Delete(path); } File.Create(path); FileSystemInfo fd = new FileInfo(path); // Since this is the only reference to the file, it is not considered a // hardlink by our API (though all files are hardlinks on Linux) Assert.False(Platform.NonWindowsIsHardLink(fd)); File.Delete(path); } [Fact] public static void TestFileIsHardLink() { string path = @"/tmp/originallink"; if (File.Exists(path)) { File.Delete(path); } File.Create(path); string link = "/tmp/newlink"; if (File.Exists(link)) { File.Delete(link); } var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "ln " + path + " " + link, RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); Assert.Equal(0, process.ExitCode); } // Since there are now two references to the file, both are considered // hardlinks by our API (though all files are hardlinks on Linux) FileSystemInfo fd = new FileInfo(path); Assert.True(Platform.NonWindowsIsHardLink(fd)); fd = new FileInfo(link); Assert.True(Platform.NonWindowsIsHardLink(fd)); File.Delete(path); File.Delete(link); } [Fact] public static void TestDirectoryIsNotHardLink() { string path = @"/tmp"; FileSystemInfo fd = new FileInfo(path); Assert.False(Platform.NonWindowsIsHardLink(fd)); } [Fact] public static void TestNonExistantIsHardLink() { // A file that should *never* exist on a test machine: string path = @"/tmp/ThisFileShouldNotExistOnTestMachines"; // If the file exists, then there's a larger issue that needs to be looked at Assert.False(File.Exists(path)); // Convert `path` string to FileSystemInfo data type. And now, it should return true FileSystemInfo fd = new FileInfo(path); Assert.False(Platform.NonWindowsIsHardLink(fd)); } [Fact] public static void TestFileIsSymLink() { string path = @"/tmp/originallink"; if (File.Exists(path)) { File.Delete(path); } File.Create(path); string link = "/tmp/newlink"; if (File.Exists(link)) { File.Delete(link); } var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "ln -s " + path + " " + link, RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); Assert.Equal(0, process.ExitCode); } FileSystemInfo fd = new FileInfo(path); Assert.False(Platform.NonWindowsIsSymLink(fd)); fd = new FileInfo(link); Assert.True(Platform.NonWindowsIsSymLink(fd)); File.Delete(path); File.Delete(link); } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using GameLibrary.Dependencies.Physics.Common; using Microsoft.Xna.Framework; using System; using System.Diagnostics; namespace GameLibrary.Dependencies.Physics.Dynamics.Joints { // Linear constraint (point-to-line) // d = p2 - p1 = x2 + r2 - x1 - r1 // C = dot(perp, d) // Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) // = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) // J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] // // Angular constraint // C = a2 - a1 + a_initial // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // // K = J * invM * JT // // J = [-a -s1 a s2] // [0 -1 0 1] // a = perp // s1 = cross(d + r1, a) = cross(p2 - x1, a) // s2 = cross(r2, a) = cross(p2 - x2, a) // Motor/Limit linear constraint // C = dot(ax1, d) // Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) // J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] // Block Solver // We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even // when the mass has poor distribution (leading to large torques about the joint anchor points). // // The Jacobian has 3 rows: // J = [-uT -s1 uT s2] // linear // [0 -1 0 1] // angular // [-vT -a1 vT a2] // limit // // u = perp // v = axis // s1 = cross(d + r1, u), s2 = cross(r2, u) // a1 = cross(d + r1, v), a2 = cross(r2, v) // M * (v2 - v1) = JT * df // J * v2 = bias // // v2 = v1 + invM * JT * df // J * (v1 + invM * JT * df) = bias // K * df = bias - J * v1 = -Cdot // K = J * invM * JT // Cdot = J * v1 - bias // // Now solve for f2. // df = f2 - f1 // K * (f2 - f1) = -Cdot // f2 = invK * (-Cdot) + f1 // // Clamp accumulated limit impulse. // lower: f2(3) = max(f2(3), 0) // upper: f2(3) = min(f2(3), 0) // // Solve for correct f2(1:2) // K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1 // = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3) // K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2) // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) // // Now compute impulse to be applied: // df = f2 - f1 /// <summary> /// A prismatic joint. This joint provides one degree of freedom: translation /// along an axis fixed in body1. Relative rotation is prevented. You can /// use a joint limit to restrict the range of motion and a joint motor to /// drive the motion or to model joint friction. /// </summary> public class PrismaticJoint : PhysicsJoint { public Vector2 LocalAnchorA; public Vector2 LocalAnchorB; private Mat33 _K; private float _a1, _a2; private Vector2 _axis; private bool _enableLimit; private bool _enableMotor; private Vector3 _impulse; private LimitState _limitState; private Vector2 _localXAxis1; private Vector2 _localYAxis1; private float _lowerTranslation; private float _maxMotorForce; private float _motorImpulse; private float _motorMass; // effective mass for motor/limit translational constraint. private float _motorSpeed; private Vector2 _perp; private float _refAngle; private float _s1, _s2; private float _upperTranslation; internal PrismaticJoint() { JointType = JointType.Prismatic; } /// <summary> /// This requires defining a line of /// motion using an axis and an anchor point. The definition uses local /// anchor points and a local axis so that the initial configuration /// can violate the constraint slightly. The joint translation is zero /// when the local anchor points coincide in world space. Using local /// anchors and a local axis helps when saving and loading a game. /// </summary> /// <param name="bodyA">The first body.</param> /// <param name="bodyB">The second body.</param> /// <param name="localAnchorA">The first body anchor.</param> /// <param name="localAnchorB">The second body anchor.</param> /// <param name="axis">The axis.</param> public PrismaticJoint(PhysicsBody bodyA, PhysicsBody bodyB, Vector2 localAnchorA, Vector2 localAnchorB, Vector2 axis) : base(bodyA, bodyB) { JointType = JointType.Prismatic; LocalAnchorA = localAnchorA; LocalAnchorB = localAnchorB; _localXAxis1 = BodyA.GetLocalVector(axis); _localYAxis1 = MathUtils.Cross(1.0f, _localXAxis1); _refAngle = BodyB.Rotation - BodyA.Rotation; _limitState = LimitState.Inactive; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } /// <summary> /// Get the current joint translation, usually in meters. /// </summary> /// <value></value> public float JointTranslation { get { Vector2 d = BodyB.GetWorldPoint(LocalAnchorB) - BodyA.GetWorldPoint(LocalAnchorA); Vector2 axis = BodyA.GetWorldVector(ref _localXAxis1); return Vector2.Dot(d, axis); } } /// <summary> /// Get the current joint translation speed, usually in meters per second. /// </summary> /// <value></value> public float JointSpeed { get { Transform xf1, xf2; BodyA.GetTransform(out xf1); BodyB.GetTransform(out xf2); Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - BodyA.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - BodyB.LocalCenter); Vector2 p1 = BodyA.Sweep.C + r1; Vector2 p2 = BodyB.Sweep.C + r2; Vector2 d = p2 - p1; Vector2 axis = BodyA.GetWorldVector(ref _localXAxis1); Vector2 v1 = BodyA.LinearVelocityInternal; Vector2 v2 = BodyB.LinearVelocityInternal; float w1 = BodyA.AngularVelocityInternal; float w2 = BodyB.AngularVelocityInternal; float speed = Vector2.Dot(d, MathUtils.Cross(w1, axis)) + Vector2.Dot(axis, v2 + MathUtils.Cross(w2, r2) - v1 - MathUtils.Cross(w1, r1)); return speed; } } /// <summary> /// Is the joint limit enabled? /// </summary> /// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value> public bool LimitEnabled { get { return _enableLimit; } set { Debug.Assert(BodyA.FixedRotation == false || BodyB.FixedRotation == false, "Warning: limits does currently not work with fixed rotation"); WakeBodies(); _enableLimit = value; } } /// <summary> /// Get the lower joint limit, usually in meters. /// </summary> /// <value></value> public float LowerLimit { get { return _lowerTranslation; } set { WakeBodies(); _lowerTranslation = value; } } /// <summary> /// Get the upper joint limit, usually in meters. /// </summary> /// <value></value> public float UpperLimit { get { return _upperTranslation; } set { WakeBodies(); _upperTranslation = value; } } /// <summary> /// Is the joint motor enabled? /// </summary> /// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value> public bool MotorEnabled { get { return _enableMotor; } set { WakeBodies(); _enableMotor = value; } } /// <summary> /// Set the motor speed, usually in meters per second. /// </summary> /// <value>The speed.</value> public float MotorSpeed { set { WakeBodies(); _motorSpeed = value; } get { return _motorSpeed; } } /// <summary> /// Set the maximum motor force, usually in N. /// </summary> /// <value>The force.</value> public float MaxMotorForce { get { return _maxMotorForce; } set { WakeBodies(); _maxMotorForce = value; } } /// <summary> /// Get the current motor force, usually in N. /// </summary> /// <value></value> public float MotorForce { get { return _motorImpulse; } set { _motorImpulse = value; } } public Vector2 LocalXAxis1 { get { return _localXAxis1; } set { _localXAxis1 = BodyA.GetLocalVector(value); _localYAxis1 = MathUtils.Cross(1.0f, _localXAxis1); } } public float ReferenceAngle { get { return _refAngle; } set { _refAngle = value; } } public override Vector2 GetReactionForce(float inv_dt) { return inv_dt * (_impulse.X * _perp + (_motorImpulse + _impulse.Z) * _axis); } public override float GetReactionTorque(float inv_dt) { return inv_dt * _impulse.Y; } internal override void InitVelocityConstraints(ref TimeStep step) { PhysicsBody b1 = BodyA; PhysicsBody b2 = BodyB; LocalCenterA = b1.LocalCenter; LocalCenterB = b2.LocalCenter; Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2); // Compute the effective masses. Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - LocalCenterA); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - LocalCenterB); Vector2 d = b2.Sweep.C + r2 - b1.Sweep.C - r1; InvMassA = b1.InvMass; InvIA = b1.InvI; InvMassB = b2.InvMass; InvIB = b2.InvI; // Compute motor Jacobian and effective mass. { _axis = MathUtils.Multiply(ref xf1.R, _localXAxis1); _a1 = MathUtils.Cross(d + r1, _axis); _a2 = MathUtils.Cross(r2, _axis); _motorMass = InvMassA + InvMassB + InvIA * _a1 * _a1 + InvIB * _a2 * _a2; if (_motorMass > Settings.Epsilon) { _motorMass = 1.0f / _motorMass; } } // Prismatic constraint. { _perp = MathUtils.Multiply(ref xf1.R, _localYAxis1); _s1 = MathUtils.Cross(d + r1, _perp); _s2 = MathUtils.Cross(r2, _perp); float m1 = InvMassA, m2 = InvMassB; float i1 = InvIA, i2 = InvIB; float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2; float k12 = i1 * _s1 + i2 * _s2; float k13 = i1 * _s1 * _a1 + i2 * _s2 * _a2; float k22 = i1 + i2; float k23 = i1 * _a1 + i2 * _a2; float k33 = m1 + m2 + i1 * _a1 * _a1 + i2 * _a2 * _a2; _K.Col1 = new Vector3(k11, k12, k13); _K.Col2 = new Vector3(k12, k22, k23); _K.Col3 = new Vector3(k13, k23, k33); } // Compute motor and limit terms. if (_enableLimit) { float jointTranslation = Vector2.Dot(_axis, d); if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop) { _limitState = LimitState.Equal; } else if (jointTranslation <= _lowerTranslation) { if (_limitState != LimitState.AtLower) { _limitState = LimitState.AtLower; _impulse.Z = 0.0f; } } else if (jointTranslation >= _upperTranslation) { if (_limitState != LimitState.AtUpper) { _limitState = LimitState.AtUpper; _impulse.Z = 0.0f; } } else { _limitState = LimitState.Inactive; _impulse.Z = 0.0f; } } else { _limitState = LimitState.Inactive; } if (_enableMotor == false) { _motorImpulse = 0.0f; } if (Settings.EnableWarmstarting) { // Account for variable time step. _impulse *= step.dtRatio; _motorImpulse *= step.dtRatio; Vector2 P = _impulse.X * _perp + (_motorImpulse + _impulse.Z) * _axis; float L1 = _impulse.X * _s1 + _impulse.Y + (_motorImpulse + _impulse.Z) * _a1; float L2 = _impulse.X * _s2 + _impulse.Y + (_motorImpulse + _impulse.Z) * _a2; b1.LinearVelocityInternal -= InvMassA * P; b1.AngularVelocityInternal -= InvIA * L1; b2.LinearVelocityInternal += InvMassB * P; b2.AngularVelocityInternal += InvIB * L2; } else { _impulse = Vector3.Zero; _motorImpulse = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { PhysicsBody b1 = BodyA; PhysicsBody b2 = BodyB; Vector2 v1 = b1.LinearVelocityInternal; float w1 = b1.AngularVelocityInternal; Vector2 v2 = b2.LinearVelocityInternal; float w2 = b2.AngularVelocityInternal; // Solve linear motor constraint. if (_enableMotor && _limitState != LimitState.Equal) { float Cdot = Vector2.Dot(_axis, v2 - v1) + _a2 * w2 - _a1 * w1; float impulse = _motorMass * (_motorSpeed - Cdot); float oldImpulse = _motorImpulse; float maxImpulse = step.dt * _maxMotorForce; _motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = _motorImpulse - oldImpulse; Vector2 P = impulse * _axis; float L1 = impulse * _a1; float L2 = impulse * _a2; v1 -= InvMassA * P; w1 -= InvIA * L1; v2 += InvMassB * P; w2 += InvIB * L2; } Vector2 Cdot1 = new Vector2(Vector2.Dot(_perp, v2 - v1) + _s2 * w2 - _s1 * w1, w2 - w1); if (_enableLimit && _limitState != LimitState.Inactive) { // Solve prismatic and limit constraint in block form. float Cdot2 = Vector2.Dot(_axis, v2 - v1) + _a2 * w2 - _a1 * w1; Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2); Vector3 f1 = _impulse; Vector3 df = _K.Solve33(-Cdot); _impulse += df; if (_limitState == LimitState.AtLower) { _impulse.Z = Math.Max(_impulse.Z, 0.0f); } else if (_limitState == LimitState.AtUpper) { _impulse.Z = Math.Min(_impulse.Z, 0.0f); } // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) Vector2 b = -Cdot1 - (_impulse.Z - f1.Z) * new Vector2(_K.Col3.X, _K.Col3.Y); Vector2 f2r = _K.Solve22(b) + new Vector2(f1.X, f1.Y); _impulse.X = f2r.X; _impulse.Y = f2r.Y; df = _impulse - f1; Vector2 P = df.X * _perp + df.Z * _axis; float L1 = df.X * _s1 + df.Y + df.Z * _a1; float L2 = df.X * _s2 + df.Y + df.Z * _a2; v1 -= InvMassA * P; w1 -= InvIA * L1; v2 += InvMassB * P; w2 += InvIB * L2; } else { // Limit is inactive, just solve the prismatic constraint in block form. Vector2 df = _K.Solve22(-Cdot1); _impulse.X += df.X; _impulse.Y += df.Y; Vector2 P = df.X * _perp; float L1 = df.X * _s1 + df.Y; float L2 = df.X * _s2 + df.Y; v1 -= InvMassA * P; w1 -= InvIA * L1; v2 += InvMassB * P; w2 += InvIB * L2; } b1.LinearVelocityInternal = v1; b1.AngularVelocityInternal = w1; b2.LinearVelocityInternal = v2; b2.AngularVelocityInternal = w2; } internal override bool SolvePositionConstraints() { PhysicsBody b1 = BodyA; PhysicsBody b2 = BodyB; Vector2 c1 = b1.Sweep.C; float a1 = b1.Sweep.A; Vector2 c2 = b2.Sweep.C; float a2 = b2.Sweep.A; // Solve linear limit constraint. float linearError = 0.0f; bool active = false; float C2 = 0.0f; Mat22 R1 = new Mat22(a1); Mat22 R2 = new Mat22(a2); Vector2 r1 = MathUtils.Multiply(ref R1, LocalAnchorA - LocalCenterA); Vector2 r2 = MathUtils.Multiply(ref R2, LocalAnchorB - LocalCenterB); Vector2 d = c2 + r2 - c1 - r1; if (_enableLimit) { _axis = MathUtils.Multiply(ref R1, _localXAxis1); _a1 = MathUtils.Cross(d + r1, _axis); _a2 = MathUtils.Cross(r2, _axis); float translation = Vector2.Dot(_axis, d); if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop) { // Prevent large angular corrections C2 = MathUtils.Clamp(translation, -Settings.MaxLinearCorrection, Settings.MaxLinearCorrection); linearError = Math.Abs(translation); active = true; } else if (translation <= _lowerTranslation) { // Prevent large linear corrections and allow some slop. C2 = MathUtils.Clamp(translation - _lowerTranslation + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f); linearError = _lowerTranslation - translation; active = true; } else if (translation >= _upperTranslation) { // Prevent large linear corrections and allow some slop. C2 = MathUtils.Clamp(translation - _upperTranslation - Settings.LinearSlop, 0.0f, Settings.MaxLinearCorrection); linearError = translation - _upperTranslation; active = true; } } _perp = MathUtils.Multiply(ref R1, _localYAxis1); _s1 = MathUtils.Cross(d + r1, _perp); _s2 = MathUtils.Cross(r2, _perp); Vector3 impulse; Vector2 C1 = new Vector2(Vector2.Dot(_perp, d), a2 - a1 - ReferenceAngle); linearError = Math.Max(linearError, Math.Abs(C1.X)); float angularError = Math.Abs(C1.Y); if (active) { float m1 = InvMassA, m2 = InvMassB; float i1 = InvIA, i2 = InvIB; float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2; float k12 = i1 * _s1 + i2 * _s2; float k13 = i1 * _s1 * _a1 + i2 * _s2 * _a2; float k22 = i1 + i2; float k23 = i1 * _a1 + i2 * _a2; float k33 = m1 + m2 + i1 * _a1 * _a1 + i2 * _a2 * _a2; _K.Col1 = new Vector3(k11, k12, k13); _K.Col2 = new Vector3(k12, k22, k23); _K.Col3 = new Vector3(k13, k23, k33); Vector3 C = new Vector3(-C1.X, -C1.Y, -C2); impulse = _K.Solve33(C); // negated above } else { float m1 = InvMassA, m2 = InvMassB; float i1 = InvIA, i2 = InvIB; float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2; float k12 = i1 * _s1 + i2 * _s2; float k22 = i1 + i2; _K.Col1 = new Vector3(k11, k12, 0.0f); _K.Col2 = new Vector3(k12, k22, 0.0f); Vector2 impulse1 = _K.Solve22(-C1); impulse.X = impulse1.X; impulse.Y = impulse1.Y; impulse.Z = 0.0f; } Vector2 P = impulse.X * _perp + impulse.Z * _axis; float L1 = impulse.X * _s1 + impulse.Y + impulse.Z * _a1; float L2 = impulse.X * _s2 + impulse.Y + impulse.Z * _a2; c1 -= InvMassA * P; a1 -= InvIA * L1; c2 += InvMassB * P; a2 += InvIB * L2; // TODO_ERIN remove need for this. b1.Sweep.C = c1; b1.Sweep.A = a1; b2.Sweep.C = c2; b2.Sweep.A = a2; b1.SynchronizeTransform(); b2.SynchronizeTransform(); return linearError <= Settings.LinearSlop && angularError <= Settings.AngularSlop; } } }
using System; using System.Collections.Generic; using System.Threading; using Castle.MicroKernel.Registration; using Castle.Windsor; using Castle.Windsor.Configuration.Interpreters; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Sagas; using Rhino.ServiceBus.Sagas.Persisters; using Xunit; namespace Rhino.ServiceBus.Tests { public class SagaTests : MsmqBehaviorTests { private static Guid sagaId; private static ManualResetEvent wait; private readonly IWindsorContainer container; public SagaTests() { OrderProcessor.LastState = null; wait = new ManualResetEvent(false); container = new WindsorContainer(new XmlInterpreter()); container.Kernel.AddFacility("rhino.esb", new RhinoServiceBusFacility()); container.Register( Component.For(typeof(ISagaPersister<>)) .ImplementedBy(typeof(InMemorySagaPersister<>)), Component.For<OrderProcessor>() ); } [Fact] public void when_sending_non_initiating_message_saga_will_not_be_invoked() { using (var bus = container.Resolve<IStartableServiceBus>()) { var transport = container.Resolve<ITransport>(); bus.Start(); transport.MessageProcessingCompleted += (i,e) => wait.Set(); bus.Send(bus.Endpoint, new AddLineItemMessage()); wait.WaitOne(); Assert.Null(OrderProcessor.LastState); } } [Fact] public void When_saga_with_same_correlation_id_exists_and_get_initiating_message_will_usage_same_saga() { using (var bus = container.Resolve<IStartableServiceBus>()) { bus.Start(); var guid = Guid.NewGuid(); bus.Send(bus.Endpoint, new NewOrderMessage { CorrelationId = guid }); wait.WaitOne(); wait.Reset(); bus.Send(bus.Endpoint, new NewOrderMessage { CorrelationId = guid }); wait.WaitOne(); Assert.Equal(2, OrderProcessor.LastState.Count); } } [Fact] public void Can_create_saga_entity() { using (var bus = container.Resolve<IStartableServiceBus>()) { bus.Start(); bus.Send(bus.Endpoint, new NewOrderMessage()); wait.WaitOne(); var persister = container.Resolve<ISagaPersister<OrderProcessor>>(); OrderProcessor processor = null; while (processor == null) { Thread.Sleep(500); processor = persister.Get(sagaId); } Assert.Equal(1, processor.State.Count); } } [Fact] public void When_creating_saga_entity_will_set_saga_id() { using (var bus = container.Resolve<IStartableServiceBus>()) { bus.Start(); bus.Send(bus.Endpoint, new NewOrderMessage2()); wait.WaitOne(); var persister = container.Resolve<ISagaPersister<OrderProcessor>>(); OrderProcessor processor = null; while (processor == null) { Thread.Sleep(500); processor = persister.Get(sagaId); } Assert.NotEqual(Guid.Empty, sagaId); } } [Fact] public void Can_send_several_messaged_to_same_instance_of_saga_entity() { using (var bus = container.Resolve<IStartableServiceBus>()) { bus.Start(); bus.Send(bus.Endpoint, new NewOrderMessage()); wait.WaitOne(); wait.Reset(); Assert.Equal(1, OrderProcessor.LastState.Count); bus.Send(bus.Endpoint, new AddLineItemMessage { CorrelationId = sagaId }); wait.WaitOne(); Assert.Equal(2, OrderProcessor.LastState.Count); } } [Fact] public void Completing_saga_will_get_it_out_of_the_in_memory_persister() { using (var bus = container.Resolve<IStartableServiceBus>()) { bus.Start(); bus.Send(bus.Endpoint, new NewOrderMessage()); wait.WaitOne(); wait.Reset(); var persister = container.Resolve<ISagaPersister<OrderProcessor>>(); OrderProcessor processor = null; while (processor == null) { Thread.Sleep(500); processor = persister.Get(sagaId); } bus.Send(bus.Endpoint, new SubmitOrderMessage { CorrelationId = sagaId }); wait.WaitOne(); while (processor != null) { Thread.Sleep(500); processor = persister.Get(sagaId); } Assert.Null(processor); } } #region Nested type: AddLineItemMessage public class AddLineItemMessage : ISagaMessage { #region ISagaMessage Members public Guid CorrelationId { get; set; } #endregion } #endregion #region Nested type: NewOrderMessage public class NewOrderMessage : ISagaMessage { public Guid CorrelationId { get; set; } } #endregion #region Nested type: OrderProcessor public class OrderProcessor : ISaga<List<object>>, InitiatedBy<NewOrderMessage2>, InitiatedBy<NewOrderMessage>, Orchestrates<AddLineItemMessage>, Orchestrates<SubmitOrderMessage> { public static List<object> LastState; public OrderProcessor() { State = new List<object>(); } #region InitiatedBy<NewOrderMessage> Members public void Consume(NewOrderMessage pong) { State.Add(pong); sagaId = Id; LastState = State; wait.Set(); } public Guid Id { get; set; } public bool IsCompleted { get; set; } #endregion #region Orchestrates<AddLineItemMessage> Members public void Consume(AddLineItemMessage pong) { State.Add(pong); sagaId = Id; LastState = State; wait.Set(); } #endregion public void Consume(SubmitOrderMessage message) { IsCompleted = true; LastState = State; wait.Set(); } public List<object> State { get; set; } public void Consume(NewOrderMessage2 message) { LastState = State; sagaId = Id; wait.Set(); } } #endregion #region Nested type: SubmitOrderMessage public class SubmitOrderMessage : ISagaMessage { #region ISagaMessage Members public Guid CorrelationId { get; set; } #endregion } #endregion } public class NewOrderMessage2 { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using Microsoft.CSharp.RuntimeBinder.Semantics; namespace Microsoft.CSharp.RuntimeBinder { internal sealed class ExpressionTreeCallRewriter : ExprVisitorBase { ///////////////////////////////////////////////////////////////////////////////// // Members private sealed class ExpressionExpr : Expr { public readonly Expression Expression; public ExpressionExpr(Expression e) : base(0) { Expression = e; } } private readonly Dictionary<ExprCall, Expression> _DictionaryOfParameters; private readonly Expression[] _ListOfParameters; private readonly TypeManager _typeManager; // Counts how many EXPRSAVEs we've encountered so we know which index into the // parameter list we should be taking. private int _currentParameterIndex; ///////////////////////////////////////////////////////////////////////////////// private ExpressionTreeCallRewriter(TypeManager typeManager, Expression[] listOfParameters) { _typeManager = typeManager; _DictionaryOfParameters = new Dictionary<ExprCall, Expression>(); _ListOfParameters = listOfParameters; } ///////////////////////////////////////////////////////////////////////////////// public static Expression Rewrite(TypeManager typeManager, Expr pExpr, Expression[] listOfParameters) { ExpressionTreeCallRewriter rewriter = new ExpressionTreeCallRewriter(typeManager, listOfParameters); // We should have a EXPRBINOP thats an EK_SEQUENCE. The RHS of our sequence // should be a call to PM_EXPRESSION_LAMBDA. The LHS of our sequence is the // set of declarations for the parameters that we'll need. // Assert all of these first, and then unwrap them. Debug.Assert(pExpr != null); Debug.Assert(pExpr.Kind == ExpressionKind.Sequence); ExprBinOp binOp = (ExprBinOp)pExpr; Debug.Assert(binOp != null); Debug.Assert(binOp.OptionalRightChild is ExprCall); Debug.Assert(((ExprCall)binOp.OptionalRightChild).PredefinedMethod == PREDEFMETH.PM_EXPRESSION_LAMBDA); Debug.Assert(binOp.OptionalLeftChild != null); // Visit the left to generate the parameter construction. rewriter.Visit(binOp.OptionalLeftChild); ExprCall call = (ExprCall)binOp.OptionalRightChild; ExpressionExpr e = rewriter.Visit(call) as ExpressionExpr; return e.Expression; } ///////////////////////////////////////////////////////////////////////////////// protected override Expr VisitSAVE(ExprBinOp pExpr) { // Saves should have a LHS that is a CALL to PM_EXPRESSION_PARAMETER // and a RHS that is a WRAP of that call. ExprCall call = (ExprCall)pExpr.OptionalLeftChild; Debug.Assert(call?.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_PARAMETER); Debug.Assert(pExpr.OptionalRightChild is ExprWrap); Expression parameter = _ListOfParameters[_currentParameterIndex++]; _DictionaryOfParameters.Add(call, parameter); return null; } ///////////////////////////////////////////////////////////////////////////////// protected override Expr VisitCALL(ExprCall pExpr) { if (pExpr.PredefinedMethod == PREDEFMETH.PM_COUNT) { return pExpr; } Expression exp; switch (pExpr.PredefinedMethod) { case PREDEFMETH.PM_EXPRESSION_LAMBDA: return GenerateLambda(pExpr); case PREDEFMETH.PM_EXPRESSION_CALL: exp = GenerateCall(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX: case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2: exp = GenerateArrayIndex(pExpr); break; case PREDEFMETH.PM_EXPRESSION_CONVERT: case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED: exp = GenerateConvert(pExpr); break; case PREDEFMETH.PM_EXPRESSION_PROPERTY: exp = GenerateProperty(pExpr); break; case PREDEFMETH.PM_EXPRESSION_FIELD: exp = GenerateField(pExpr); break; case PREDEFMETH.PM_EXPRESSION_INVOKE: exp = GenerateInvoke(pExpr); break; case PREDEFMETH.PM_EXPRESSION_NEW: exp = GenerateNew(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ADD: case PREDEFMETH.PM_EXPRESSION_AND: case PREDEFMETH.PM_EXPRESSION_DIVIDE: case PREDEFMETH.PM_EXPRESSION_EQUAL: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT: case PREDEFMETH.PM_EXPRESSION_LESSTHAN: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_MODULO: case PREDEFMETH.PM_EXPRESSION_MULTIPLY: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL: case PREDEFMETH.PM_EXPRESSION_OR: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT: case PREDEFMETH.PM_EXPRESSION_SUBTRACT: case PREDEFMETH.PM_EXPRESSION_ORELSE: case PREDEFMETH.PM_EXPRESSION_ANDALSO: // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED: exp = GenerateBinaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED: // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED: exp = GenerateUserDefinedBinaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_NEGATE: case PREDEFMETH.PM_EXPRESSION_NOT: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED: exp = GenerateUnaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED: exp = GenerateUserDefinedUnaryOperator(pExpr); break; case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE: exp = GenerateConstantType(pExpr); break; case PREDEFMETH.PM_EXPRESSION_ASSIGN: exp = GenerateAssignment(pExpr); break; default: Debug.Assert(false, "Invalid Predefined Method in VisitCALL"); throw Error.InternalCompilerError(); } return new ExpressionExpr(exp); } #region Generators ///////////////////////////////////////////////////////////////////////////////// private Expr GenerateLambda(ExprCall pExpr) { // We always call Lambda(body, arrayinit) where the arrayinit // is the initialization of the parameters. return Visit(((ExprList)pExpr.OptionalArguments).OptionalElement); /* * // Do we need to do this? Expression e = (body as ExpressionExpr).Expression; if (e.Type.IsValueType) { // If we have a value type, convert it to object so that boxing // can happen. e = Expression.Convert(body.Expression, typeof(object)); } * */ } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateCall(ExprCall pExpr) { // Our arguments are: object, methodinfo, parameters. // The object is either an EXPRWRAP of a CALL, or a CALL that is a PM_CONVERT, whose // argument is the WRAP of a CALL. Deal with that first. ExprMethodInfo methinfo; ExprArrayInit arrinit; ExprList list = (ExprList)pExpr.OptionalArguments; if (list.OptionalNextListNode is ExprList next) { methinfo = (ExprMethodInfo)next.OptionalElement; arrinit = (ExprArrayInit)next.OptionalNextListNode; } else { methinfo = (ExprMethodInfo)list.OptionalNextListNode; arrinit = null; } Expression obj = null; MethodInfo m = GetMethodInfoFromExpr(methinfo); Expression[] arguments = GetArgumentsFromArrayInit(arrinit); if (m == null) { Debug.Assert(false, "How did we get a call that doesn't have a methodinfo?"); throw Error.InternalCompilerError(); } // The DLR is expecting the instance for a static invocation to be null. If we have // an instance method, fetch the object. if (!m.IsStatic) { obj = GetExpression(((ExprList)pExpr.OptionalArguments).OptionalElement); } return Expression.Call(obj, m, arguments); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateArrayIndex(ExprCall pExpr) { // We have two possibilities here - we're either a single index array, in which // case we'll be PM_EXPRESSION_ARRAYINDEX, or we have multiple dimensions, // in which case we are PM_EXPRESSION_ARRAYINDEX2. // // Our arguments then, are: object, index or object, indices. ExprList list = (ExprList)pExpr.OptionalArguments; Debug.Assert(list != null); Expression obj = GetExpression(list.OptionalElement); Expression[] indices; if (pExpr.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX) { indices = new[] { GetExpression(list.OptionalNextListNode) }; } else { Debug.Assert(pExpr.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2); indices = GetArgumentsFromArrayInit((ExprArrayInit)list.OptionalNextListNode); } return Expression.ArrayAccess(obj, indices); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateConvert(ExprCall pExpr) { PREDEFMETH pm = pExpr.PredefinedMethod; Expression e; Type t; if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED) { // If we have a user defined conversion, then we'll have the object // as the first element, and another list as a second element. This list // contains a TYPEOF as the first element, and the METHODINFO for the call // as the second. ExprList list = (ExprList)pExpr.OptionalArguments; ExprList list2 = (ExprList)list.OptionalNextListNode; e = GetExpression(list.OptionalElement); t = ((ExprTypeOf)list2.OptionalElement).SourceType.Type.AssociatedSystemType; if (e.Type.MakeByRefType() == t) { // We're trying to convert from a type to its by ref type. Don't do that. return e; } Debug.Assert((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) == 0); MethodInfo m = GetMethodInfoFromExpr((ExprMethodInfo)list2.OptionalNextListNode); if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED) { return Expression.Convert(e, t, m); } return Expression.ConvertChecked(e, t, m); } else { Debug.Assert(pm == PREDEFMETH.PM_EXPRESSION_CONVERT || pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED); // If we have a standard conversion, then we'll have some object as // the first list element (ie a WRAP or a CALL), and then a TYPEOF // as the second list element. ExprList list = (ExprList)pExpr.OptionalArguments; e = GetExpression(list.OptionalElement); t = ((ExprTypeOf)list.OptionalNextListNode).SourceType.Type.AssociatedSystemType; if (e.Type.MakeByRefType() == t) { // We're trying to convert from a type to its by ref type. Don't do that. return e; } if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0) { // If we want to unbox this thing, return that instead of the convert. return Expression.Unbox(e, t); } if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT) { return Expression.Convert(e, t); } return Expression.ConvertChecked(e, t); } } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateProperty(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; Expr instance = list.OptionalElement; Expr nextNode = list.OptionalNextListNode; ExprPropertyInfo propinfo; ExprArrayInit arguments; if (nextNode is ExprList nextList) { propinfo = nextList.OptionalElement as ExprPropertyInfo; arguments = nextList.OptionalNextListNode as ExprArrayInit; } else { propinfo = nextNode as ExprPropertyInfo; arguments = null; } PropertyInfo p = GetPropertyInfoFromExpr(propinfo); if (p == null) { Debug.Assert(false, "How did we get a prop that doesn't have a propinfo?"); throw Error.InternalCompilerError(); } if (arguments == null) { return Expression.Property(GetExpression(instance), p); } return Expression.Property(GetExpression(instance), p, GetArgumentsFromArrayInit(arguments)); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateField(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; ExprFieldInfo fieldInfo = (ExprFieldInfo)list.OptionalNextListNode; Debug.Assert(fieldInfo != null); Type t = fieldInfo.FieldType.AssociatedSystemType; FieldInfo f = fieldInfo.Field.AssociatedFieldInfo; // This is to ensure that for embedded nopia types, we have the // appropriate local type from the member itself; this is possible // because nopia types are not generic or nested. if (!t.IsGenericType && !t.IsNested) { t = f.DeclaringType; } // Now find the generic'ed one if we're generic. if (t.IsGenericType) { f = t.GetField(f.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); } return Expression.Field(GetExpression(list.OptionalElement), f); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateInvoke(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; return Expression.Invoke( GetExpression(list.OptionalElement), GetArgumentsFromArrayInit(list.OptionalNextListNode as ExprArrayInit)); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateNew(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; var constructor = GetConstructorInfoFromExpr(list.OptionalElement as ExprMethodInfo); var arguments = GetArgumentsFromArrayInit(list.OptionalNextListNode as ExprArrayInit); return Expression.New(constructor, arguments); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateConstantType(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; return Expression.Constant( GetObject(list.OptionalElement), ((ExprTypeOf)list.OptionalNextListNode).SourceType.Type.AssociatedSystemType); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateAssignment(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; return Expression.Assign( GetExpression(list.OptionalElement), GetExpression(list.OptionalNextListNode)); } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateBinaryOperator(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; Debug.Assert(list != null); Expression arg1 = GetExpression(list.OptionalElement); Expression arg2 = GetExpression(list.OptionalNextListNode); switch (pExpr.PredefinedMethod) { case PREDEFMETH.PM_EXPRESSION_ADD: return Expression.Add(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_AND: return Expression.And(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_DIVIDE: return Expression.Divide(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_EQUAL: return Expression.Equal(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR: return Expression.ExclusiveOr(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_GREATERTHAN: return Expression.GreaterThan(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL: return Expression.GreaterThanOrEqual(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT: return Expression.LeftShift(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_LESSTHAN: return Expression.LessThan(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL: return Expression.LessThanOrEqual(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_MODULO: return Expression.Modulo(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_MULTIPLY: return Expression.Multiply(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_NOTEQUAL: return Expression.NotEqual(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_OR: return Expression.Or(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT: return Expression.RightShift(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_SUBTRACT: return Expression.Subtract(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_ORELSE: return Expression.OrElse(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_ANDALSO: return Expression.AndAlso(arg1, arg2); // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED: return Expression.AddChecked(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED: return Expression.MultiplyChecked(arg1, arg2); case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED: return Expression.SubtractChecked(arg1, arg2); default: Debug.Assert(false, "Invalid Predefined Method in GenerateBinaryOperator"); throw Error.InternalCompilerError(); } } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateUserDefinedBinaryOperator(ExprCall pExpr) { ExprList list = (ExprList)pExpr.OptionalArguments; Expression arg1 = GetExpression(list.OptionalElement); Expression arg2 = GetExpression(((ExprList)list.OptionalNextListNode).OptionalElement); list = (ExprList)list.OptionalNextListNode; MethodInfo methodInfo; bool bIsLifted = false; if (list.OptionalNextListNode is ExprList next) { ExprConstant isLifted = (ExprConstant)next.OptionalElement; Debug.Assert(isLifted != null); bIsLifted = isLifted.Val.Int32Val == 1; methodInfo = GetMethodInfoFromExpr((ExprMethodInfo)next.OptionalNextListNode); } else { methodInfo = GetMethodInfoFromExpr((ExprMethodInfo)list.OptionalNextListNode); } switch (pExpr.PredefinedMethod) { case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED: return Expression.Add(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED: return Expression.And(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED: return Expression.Divide(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED: return Expression.Equal(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED: return Expression.ExclusiveOr(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED: return Expression.GreaterThan(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED: return Expression.GreaterThanOrEqual(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED: return Expression.LeftShift(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED: return Expression.LessThan(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED: return Expression.LessThanOrEqual(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED: return Expression.Modulo(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED: return Expression.Multiply(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED: return Expression.NotEqual(arg1, arg2, bIsLifted, methodInfo); case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED: return Expression.Or(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED: return Expression.RightShift(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED: return Expression.Subtract(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED: return Expression.OrElse(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED: return Expression.AndAlso(arg1, arg2, methodInfo); // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED: return Expression.AddChecked(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED: return Expression.MultiplyChecked(arg1, arg2, methodInfo); case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED: return Expression.SubtractChecked(arg1, arg2, methodInfo); default: Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedBinaryOperator"); throw Error.InternalCompilerError(); } } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateUnaryOperator(ExprCall pExpr) { PREDEFMETH pm = pExpr.PredefinedMethod; Expression arg = GetExpression(pExpr.OptionalArguments); switch (pm) { case PREDEFMETH.PM_EXPRESSION_NOT: return Expression.Not(arg); case PREDEFMETH.PM_EXPRESSION_NEGATE: return Expression.Negate(arg); case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED: return Expression.NegateChecked(arg); default: Debug.Assert(false, "Invalid Predefined Method in GenerateUnaryOperator"); throw Error.InternalCompilerError(); } } ///////////////////////////////////////////////////////////////////////////////// private Expression GenerateUserDefinedUnaryOperator(ExprCall pExpr) { PREDEFMETH pm = pExpr.PredefinedMethod; ExprList list = (ExprList)pExpr.OptionalArguments; Expression arg = GetExpression(list.OptionalElement); MethodInfo methodInfo = GetMethodInfoFromExpr((ExprMethodInfo)list.OptionalNextListNode); switch (pm) { case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED: return Expression.Not(arg, methodInfo); case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED: return Expression.Negate(arg, methodInfo); case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED: return Expression.UnaryPlus(arg, methodInfo); case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED: return Expression.NegateChecked(arg, methodInfo); default: Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedUnaryOperator"); throw Error.InternalCompilerError(); } } #endregion #region Helpers ///////////////////////////////////////////////////////////////////////////////// private Expression GetExpression(Expr pExpr) { if (pExpr is ExprWrap wrap) { return _DictionaryOfParameters[(ExprCall)wrap.OptionalExpression]; } else if (pExpr is ExprConstant) { Debug.Assert(pExpr.Type is NullType); return null; } else { // We can have a convert node or a call of a user defined conversion. ExprCall call = (ExprCall)pExpr; Debug.Assert(call != null); PREDEFMETH pm = call.PredefinedMethod; Debug.Assert(pm == PREDEFMETH.PM_EXPRESSION_CONVERT || pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT || pm == PREDEFMETH.PM_EXPRESSION_CALL || pm == PREDEFMETH.PM_EXPRESSION_PROPERTY || pm == PREDEFMETH.PM_EXPRESSION_FIELD || pm == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX || pm == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2 || pm == PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE || pm == PREDEFMETH.PM_EXPRESSION_NEW || // Binary operators. pm == PREDEFMETH.PM_EXPRESSION_ASSIGN || pm == PREDEFMETH.PM_EXPRESSION_ADD || pm == PREDEFMETH.PM_EXPRESSION_AND || pm == PREDEFMETH.PM_EXPRESSION_DIVIDE || pm == PREDEFMETH.PM_EXPRESSION_EQUAL || pm == PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR || pm == PREDEFMETH.PM_EXPRESSION_GREATERTHAN || pm == PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL || pm == PREDEFMETH.PM_EXPRESSION_LEFTSHIFT || pm == PREDEFMETH.PM_EXPRESSION_LESSTHAN || pm == PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL || pm == PREDEFMETH.PM_EXPRESSION_MODULO || pm == PREDEFMETH.PM_EXPRESSION_MULTIPLY || pm == PREDEFMETH.PM_EXPRESSION_NOTEQUAL || pm == PREDEFMETH.PM_EXPRESSION_OR || pm == PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT || pm == PREDEFMETH.PM_EXPRESSION_SUBTRACT || pm == PREDEFMETH.PM_EXPRESSION_ORELSE || pm == PREDEFMETH.PM_EXPRESSION_ANDALSO || pm == PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED || // Checked binary pm == PREDEFMETH.PM_EXPRESSION_ADDCHECKED || pm == PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED || pm == PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED || pm == PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED || // Unary operators. pm == PREDEFMETH.PM_EXPRESSION_NOT || pm == PREDEFMETH.PM_EXPRESSION_NEGATE || pm == PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED || // Checked unary pm == PREDEFMETH.PM_EXPRESSION_NEGATECHECKED || pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED || pm == PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED || pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED ); switch (pm) { case PREDEFMETH.PM_EXPRESSION_CALL: return GenerateCall(call); case PREDEFMETH.PM_EXPRESSION_CONVERT: case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED: case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED: return GenerateConvert(call); case PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT: { ExprList list = (ExprList)call.OptionalArguments; return Expression.NewArrayInit( ((ExprTypeOf)list.OptionalElement).SourceType.Type.AssociatedSystemType, GetArgumentsFromArrayInit((ExprArrayInit)list.OptionalNextListNode)); } case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX: case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2: return GenerateArrayIndex(call); case PREDEFMETH.PM_EXPRESSION_NEW: return GenerateNew(call); case PREDEFMETH.PM_EXPRESSION_PROPERTY: return GenerateProperty(call); case PREDEFMETH.PM_EXPRESSION_FIELD: return GenerateField(call); case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE: return GenerateConstantType(call); case PREDEFMETH.PM_EXPRESSION_ASSIGN: return GenerateAssignment(call); case PREDEFMETH.PM_EXPRESSION_ADD: case PREDEFMETH.PM_EXPRESSION_AND: case PREDEFMETH.PM_EXPRESSION_DIVIDE: case PREDEFMETH.PM_EXPRESSION_EQUAL: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT: case PREDEFMETH.PM_EXPRESSION_LESSTHAN: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL: case PREDEFMETH.PM_EXPRESSION_MODULO: case PREDEFMETH.PM_EXPRESSION_MULTIPLY: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL: case PREDEFMETH.PM_EXPRESSION_OR: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT: case PREDEFMETH.PM_EXPRESSION_SUBTRACT: case PREDEFMETH.PM_EXPRESSION_ORELSE: case PREDEFMETH.PM_EXPRESSION_ANDALSO: // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED: return GenerateBinaryOperator(call); case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED: // Checked case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED: return GenerateUserDefinedBinaryOperator(call); case PREDEFMETH.PM_EXPRESSION_NOT: case PREDEFMETH.PM_EXPRESSION_NEGATE: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED: return GenerateUnaryOperator(call); case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED: case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED: return GenerateUserDefinedUnaryOperator(call); default: Debug.Assert(false, "Invalid Predefined Method in GetExpression"); throw Error.InternalCompilerError(); } } } ///////////////////////////////////////////////////////////////////////////////// private object GetObject(Expr pExpr) { for (;;) { if (pExpr is ExprCast cast) { pExpr = cast.Argument; } else if (pExpr is ExprTypeOf typeOf) { return typeOf.SourceType.Type.AssociatedSystemType; } else if (pExpr is ExprMethodInfo methodInfo) { return GetMethodInfoFromExpr(methodInfo); } else if (pExpr is ExprConstant constant) { ConstVal val = constant.Val; CType underlyingType = pExpr.Type; object objval; if (pExpr.Type is NullType) { return null; } if (pExpr.Type.isEnumType()) { underlyingType = underlyingType.getAggregate().GetUnderlyingType(); } switch (Type.GetTypeCode(underlyingType.AssociatedSystemType)) { case TypeCode.Boolean: objval = val.BooleanVal; break; case TypeCode.SByte: objval = val.SByteVal; break; case TypeCode.Byte: objval = val.ByteVal; break; case TypeCode.Int16: objval = val.Int16Val; break; case TypeCode.UInt16: objval = val.UInt16Val; break; case TypeCode.Int32: objval = val.Int32Val; break; case TypeCode.UInt32: objval = val.UInt32Val; break; case TypeCode.Int64: objval = val.Int64Val; break; case TypeCode.UInt64: objval = val.UInt64Val; break; case TypeCode.Single: objval = val.SingleVal; break; case TypeCode.Double: objval = val.DoubleVal; break; case TypeCode.Decimal: objval = val.DecimalVal; break; case TypeCode.Char: objval = val.CharVal; break; case TypeCode.String: objval = val.StringVal; break; default: objval = val.ObjectVal; break; } return pExpr.Type.isEnumType() ? Enum.ToObject(pExpr.Type.AssociatedSystemType, objval) : objval; } else if (pExpr is ExprZeroInit zeroInit) { return Activator.CreateInstance(zeroInit.Type.AssociatedSystemType); } else { Debug.Assert(false, "Invalid Expr in GetObject"); throw Error.InternalCompilerError(); } } } ///////////////////////////////////////////////////////////////////////////////// private Expression[] GetArgumentsFromArrayInit(ExprArrayInit arrinit) { List<Expression> expressions = new List<Expression>(); if (arrinit != null) { Expr list = arrinit.OptionalArguments; while (list != null) { Expr p; if (list is ExprList pList) { p = pList.OptionalElement; list = pList.OptionalNextListNode; } else { p = list; list = null; } expressions.Add(GetExpression(p)); } Debug.Assert(expressions.Count == arrinit.DimensionSizes[0]); } return expressions.ToArray(); } ///////////////////////////////////////////////////////////////////////////////// private MethodInfo GetMethodInfoFromExpr(ExprMethodInfo methinfo) { // To do this, we need to construct a type array of the parameter types, // get the parent constructed type, and get the method from it. AggregateType aggType = methinfo.Method.Ats; MethodSymbol methSym = methinfo.Method.Meth(); TypeArray genericParams = _typeManager.SubstTypeArray(methSym.Params, aggType, methSym.typeVars); CType genericReturn = _typeManager.SubstType(methSym.RetType, aggType, methSym.typeVars); Type type = aggType.AssociatedSystemType; MethodInfo methodInfo = methSym.AssociatedMemberInfo as MethodInfo; // This is to ensure that for embedded nopia types, we have the // appropriate local type from the member itself; this is possible // because nopia types are not generic or nested. if (!type.IsGenericType && !type.IsNested) { type = methodInfo.DeclaringType; } // We need to find the associated methodinfo on the instantiated type. foreach (MethodInfo m in type.GetRuntimeMethods()) { #if UNSUPPORTEDAPI if ((m.MetadataToken != methodInfo.MetadataToken) || (m.Module != methodInfo.Module)) #else if (!m.HasSameMetadataDefinitionAs(methodInfo)) #endif { continue; } Debug.Assert((m.Name == methodInfo.Name) && (m.GetParameters().Length == genericParams.Count) && (TypesAreEqual(m.ReturnType, genericReturn.AssociatedSystemType))); bool bMatch = true; ParameterInfo[] parameters = m.GetParameters(); for (int i = 0; i < genericParams.Count; i++) { if (!TypesAreEqual(parameters[i].ParameterType, genericParams[i].AssociatedSystemType)) { bMatch = false; break; } } if (bMatch) { if (m.IsGenericMethod) { int size = methinfo.Method.TypeArgs?.Count ?? 0; Type[] typeArgs = new Type[size]; if (size > 0) { for (int i = 0; i < methinfo.Method.TypeArgs.Count; i++) { typeArgs[i] = methinfo.Method.TypeArgs[i].AssociatedSystemType; } } return m.MakeGenericMethod(typeArgs); } return m; } } Debug.Assert(false, "Could not find matching method"); throw Error.InternalCompilerError(); } ///////////////////////////////////////////////////////////////////////////////// private ConstructorInfo GetConstructorInfoFromExpr(ExprMethodInfo methinfo) { // To do this, we need to construct a type array of the parameter types, // get the parent constructed type, and get the method from it. AggregateType aggType = methinfo.Method.Ats; MethodSymbol methSym = methinfo.Method.Meth(); TypeArray genericInstanceParams = _typeManager.SubstTypeArray(methSym.Params, aggType); Type type = aggType.AssociatedSystemType; ConstructorInfo ctorInfo = (ConstructorInfo)methSym.AssociatedMemberInfo; // This is to ensure that for embedded nopia types, we have the // appropriate local type from the member itself; this is possible // because nopia types are not generic or nested. if (!type.IsGenericType && !type.IsNested) { type = ctorInfo.DeclaringType; } foreach (ConstructorInfo c in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) { #if UNSUPPORTEDAPI if ((c.MetadataToken != ctorInfo.MetadataToken) || (c.Module != ctorInfo.Module)) #else if (!c.HasSameMetadataDefinitionAs(ctorInfo)) #endif { continue; } Debug.Assert(c.GetParameters() == null || c.GetParameters().Length == genericInstanceParams.Count); bool bMatch = true; ParameterInfo[] parameters = c.GetParameters(); for (int i = 0; i < genericInstanceParams.Count; i++) { if (!TypesAreEqual(parameters[i].ParameterType, genericInstanceParams[i].AssociatedSystemType)) { bMatch = false; break; } } if (bMatch) { return c; } } Debug.Assert(false, "Could not find matching constructor"); throw Error.InternalCompilerError(); } ///////////////////////////////////////////////////////////////////////////////// private PropertyInfo GetPropertyInfoFromExpr(ExprPropertyInfo propinfo) { // To do this, we need to construct a type array of the parameter types, // get the parent constructed type, and get the property from it. AggregateType aggType = propinfo.Property.Ats; PropertySymbol propSym = propinfo.Property.Prop(); TypeArray genericInstanceParams = _typeManager.SubstTypeArray(propSym.Params, aggType, null); CType genericInstanceReturn = _typeManager.SubstType(propSym.RetType, aggType, null); Type type = aggType.AssociatedSystemType; PropertyInfo propertyInfo = propSym.AssociatedPropertyInfo; // This is to ensure that for embedded nopia types, we have the // appropriate local type from the member itself; this is possible // because nopia types are not generic or nested. if (!type.IsGenericType && !type.IsNested) { type = propertyInfo.DeclaringType; } foreach (PropertyInfo p in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) { #if UNSUPPORTEDAPI if ((p.MetadataToken != propertyInfo.MetadataToken) || (p.Module != propertyInfo.Module)) #else if (!p.HasSameMetadataDefinitionAs(propertyInfo)) { #endif continue; } Debug.Assert((p.Name == propertyInfo.Name) && (p.GetIndexParameters() == null || p.GetIndexParameters().Length == genericInstanceParams.Count)); bool bMatch = true; ParameterInfo[] parameters = p.GetSetMethod(true) != null ? p.GetSetMethod(true).GetParameters() : p.GetGetMethod(true).GetParameters(); for (int i = 0; i < genericInstanceParams.Count; i++) { if (!TypesAreEqual(parameters[i].ParameterType, genericInstanceParams[i].AssociatedSystemType)) { bMatch = false; break; } } if (bMatch) { return p; } } Debug.Assert(false, "Could not find matching property"); throw Error.InternalCompilerError(); } ///////////////////////////////////////////////////////////////////////////////// private bool TypesAreEqual(Type t1, Type t2) { if (t1 == t2) { return true; } return t1.IsEquivalentTo(t2); } #endregion } }
/* * * (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.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Core.Common.Configuration; using ASC.Core.Tenants; using ASC.VoipService.Twilio; namespace ASC.VoipService.Dao { public class VoipDao : AbstractDao { public VoipDao(int tenantID) : base(tenantID) { } public virtual VoipPhone SaveOrUpdateNumber(VoipPhone phone) { if (!string.IsNullOrEmpty(phone.Number)) { phone.Number = phone.Number.TrimStart('+'); } using (var db = GetDb()) { var insert = Insert("crm_voip_number") .InColumnValue("id", phone.Id) .InColumnValue("number", phone.Number) .InColumnValue("alias", phone.Alias); if (phone.Settings != null) { insert.InColumnValue("settings", phone.Settings.ToString()); } db.ExecuteNonQuery(insert); } return phone; } public virtual void DeleteNumber(string phoneId = "") { using (var db = GetDb()) { var query = Delete("crm_voip_number"); if (!string.IsNullOrEmpty(phoneId)) { query.Where("id", phoneId); } db.ExecuteNonQuery(query); } } public virtual IEnumerable<VoipPhone> GetNumbers(params object[] ids) { using (var db = GetDb()) { var query = Query("crm_voip_number") .Select("id", "number", "alias", "settings"); if (ids.Any()) { query.Where(Exp.In("number", ids) | Exp.In("id", ids)); } return db.ExecuteList(query).ConvertAll(ToPhone); } } public VoipPhone GetNumber(string id) { return GetNumbers(id.TrimStart('+')).FirstOrDefault(); } public virtual VoipPhone GetCurrentNumber() { return GetNumbers().FirstOrDefault(r => r.Caller != null); } public VoipCall SaveOrUpdateCall(VoipCall call) { using (var db = GetDb()) { var query = Insert("crm_voip_calls") .InColumnValue("id", call.Id) .InColumnValue("number_from", call.From) .InColumnValue("number_to", call.To) .InColumnValue("contact_id", call.ContactId); if (!string.IsNullOrEmpty(call.ParentID)) { query.InColumnValue("parent_call_id", call.ParentID); } if (call.Status.HasValue) { query.InColumnValue("status", call.Status.Value); } if (!call.AnsweredBy.Equals(Guid.Empty)) { query.InColumnValue("answered_by", call.AnsweredBy); } if (call.DialDate == DateTime.MinValue) { call.DialDate = DateTime.UtcNow; } query.InColumnValue("dial_date", TenantUtil.DateTimeToUtc(call.DialDate)); if (call.DialDuration > 0) { query.InColumnValue("dial_duration", call.DialDuration); } if (call.Price > Decimal.Zero) { query.InColumnValue("price", call.Price); } if (call.VoipRecord != null) { if (!string.IsNullOrEmpty(call.VoipRecord.Id)) { query.InColumnValue("record_sid", call.VoipRecord.Id); } if (!string.IsNullOrEmpty(call.VoipRecord.Uri)) { query.InColumnValue("record_url", call.VoipRecord.Uri); } if (call.VoipRecord.Duration != 0) { query.InColumnValue("record_duration", call.VoipRecord.Duration); } if (call.VoipRecord.Price != default(decimal)) { query.InColumnValue("record_price", call.VoipRecord.Price); } } db.ExecuteNonQuery(query); } return call; } public IEnumerable<VoipCall> GetCalls(VoipCallFilter filter) { using (var db = GetDb()) { var query = GetCallsQuery(filter); if (filter.SortByColumn != null) { query.OrderBy(filter.SortByColumn, filter.SortOrder); } query.SetFirstResult((int)filter.Offset); query.SetMaxResults((int)filter.Max * 3); var calls = db.ExecuteList(query).ConvertAll(ToCall); calls = calls.GroupJoin(calls, call => call.Id, h => h.ParentID, (call, h) => { call.ChildCalls.AddRange(h); return call; }).Where(r => string.IsNullOrEmpty(r.ParentID)).ToList(); return calls; } } public VoipCall GetCall(string id) { return GetCalls(new VoipCallFilter { Id = id }).FirstOrDefault(); } public int GetCallsCount(VoipCallFilter filter) { using (var db = GetDb()) { var query = GetCallsQuery(filter).Where("ca.parent_call_id", ""); var queryCount = new SqlQuery().SelectCount().From(query, "t1"); return db.ExecuteScalar<int>(queryCount); } } public IEnumerable<VoipCall> GetMissedCalls(Guid agent, long count = 0, DateTime? from = null) { using (var db = GetDb()) { var query = GetCallsQuery(new VoipCallFilter { Agent = agent, SortBy = "date", SortOrder = true, Type = "missed" }); var subQuery = new SqlQuery("crm_voip_calls tmp") .SelectMax("tmp.dial_date") .Where(Exp.EqColumns("ca.tenant_id", "tmp.tenant_id")) .Where(Exp.EqColumns("ca.number_from", "tmp.number_from") | Exp.EqColumns("ca.number_from", "tmp.number_to")) .Where(Exp.Lt("tmp.status", VoipCallStatus.Missed)); if (from.HasValue) { query.Where(Exp.Ge("ca.dial_date", TenantUtil.DateTimeFromUtc(from.Value))); } if (count != 0) { query.SetMaxResults((int)count); } query.Select(subQuery, "tmp_date"); query.Having(Exp.Sql("ca.dial_date >= tmp_date") | Exp.Eq("tmp_date", null)); return db.ExecuteList(query).ConvertAll(ToCall); } } private SqlQuery GetCallsQuery(VoipCallFilter filter) { var query = Query("crm_voip_calls ca") .Select("ca.id", "ca.parent_call_id", "ca.number_from", "ca.number_to", "ca.answered_by", "ca.dial_date", "ca.dial_duration", "ca.price", "ca.status") .Select("ca.record_sid", "ca.record_url", "ca.record_duration", "ca.record_price") .Select("ca.contact_id", "co.is_company", "co.company_name", "co.first_name", "co.last_name") .LeftOuterJoin("crm_contact co", Exp.EqColumns("ca.contact_id", "co.id")) .GroupBy("ca.id"); if (!string.IsNullOrEmpty(filter.Id)) { query.Where(Exp.Eq("ca.id", filter.Id) | Exp.Eq("ca.parent_call_id", filter.Id)); } if (filter.ContactID.HasValue) { query.Where(Exp.Eq("ca.contact_id", filter.ContactID.Value)); } if (!string.IsNullOrWhiteSpace(filter.SearchText)) { query.Where(Exp.Like("ca.id", filter.SearchText, SqlLike.StartWith)); } if (filter.TypeStatus.HasValue) { query.Where("ca.status", filter.TypeStatus.Value); } if (filter.FromDate.HasValue) { query.Where(Exp.Ge("ca.dial_date", filter.FromDate.Value)); } if (filter.ToDate.HasValue) { query.Where(Exp.Le("ca.dial_date", filter.ToDate.Value)); } if (filter.Agent.HasValue) { query.Where("ca.answered_by", filter.Agent.Value); } return query; } #region Converters private static VoipPhone ToPhone(object[] r) { return GetProvider().GetPhone(r); } private static VoipCall ToCall(object[] r) { var call = new VoipCall { Id = (string)r[0], ParentID = (string)r[1], From = (string)r[2], To = (string)r[3], AnsweredBy = new Guid((string)r[4]), DialDate = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[5])), DialDuration = Convert.ToInt32(r[6] ?? "0"), Price = Convert.ToDecimal(r[7]), Status = (VoipCallStatus)Convert.ToInt32(r[8]), VoipRecord = new VoipRecord { Id = (string)r[9], Uri = (string)r[10], Duration = Convert.ToInt32(r[11] ?? "0"), Price = Convert.ToDecimal(r[12]) }, ContactId = Convert.ToInt32(r[13]), ContactIsCompany = Convert.ToBoolean(r[14]) }; if (call.ContactId != 0) { call.ContactTitle = call.ContactIsCompany ? r[15] == null ? null : Convert.ToString(r[15]) : r[16] == null || r[17] == null ? null : string.Format("{0} {1}", Convert.ToString(r[16]), Convert.ToString(r[17])); } return call; } public static Consumer Consumer { get { return ConsumerFactory.GetByName("twilio"); } } public static TwilioProvider GetProvider() { return new TwilioProvider(Consumer["twilioAccountSid"], Consumer["twilioAuthToken"]); } public static bool ConfigSettingsExist { get { return !string.IsNullOrEmpty(Consumer["twilioAccountSid"]) && !string.IsNullOrEmpty(Consumer["twilioAuthToken"]); } } #endregion } }
//--------------------------------------------------------------------------------------- // Copyright 2014 North Carolina State University // // Center for Educational Informatics // http://www.cei.ncsu.edu/ // // 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. // // 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.Text.RegularExpressions; namespace IntelliMedia.Utilities { /// <summary> /// This class parses the useragent string provided by web Browsers to attempt to determine /// the Browser type and version. /// </summary> public class WebBrowserInfo { public enum BrowserType { Opera, WindowsPhone, IE, Chrome, Sailfish, SeaMonkey, Firefox, Silk, Android, PhantomJS, BlackBerry, WebOS, Bada, Tizen, Safari, iPhone, iPad, iPod, Unknown } public bool Success { get { return Browser != BrowserType.Unknown; }} public BrowserType Browser { get; private set; } public string DisplayName { get; private set; } public string DisplayVersion { get; private set; } public bool IsiOS { get; private set; } public bool IsAndroid { get; private set; } public bool IsTablet { get; private set; } public bool IsMobile { get; private set; } public WebBrowserInfo(string userAgent) { DisplayName = "unknown"; Browser = BrowserType.Unknown; DisplayVersion = ""; if (!string.IsNullOrEmpty(userAgent)) { Parse(userAgent); } } public bool MeetsMinimum(BrowserType browser, string minVersion) { return (Browser == browser && (ParseVersion(DisplayVersion) >= ParseVersion(minVersion))); } // Parse the browser's useragent string to detect browser type and version // Based on: // Bowser - a browser detector // https://github.com/ded/bowser // MIT License | (c) Dustin Diaz 2014 private void Parse(string userAgent) { string iosdevice = getFirstMatch(userAgent, @"(ipod|iphone|ipad)"); if (iosdevice != null) { iosdevice = iosdevice.ToLower(); IsiOS = true; } bool likeAndroid = contains(userAgent, @"like android"); IsAndroid = !likeAndroid && contains(userAgent, @"android"); string versionIdentifier = getNamedGroup(userAgent, "version", @"version\/(?<version>\d+(\.\d+)?)"); IsTablet = contains(userAgent, @"tablet"); IsMobile = !IsTablet && contains(userAgent, @"[^-]mobi"); if (contains(userAgent, @"opera|opr")) { DisplayName = "Opera"; Browser = BrowserType.Opera; DisplayVersion = (versionIdentifier != null ? versionIdentifier : getFirstMatch(userAgent, @"(?:opera|opr)[\s\/](\d+(\.\d+)?)")); } else if (contains(userAgent, @"windows phone")) { DisplayName = "Windows Phone"; Browser = BrowserType.WindowsPhone; DisplayVersion = getFirstMatch(userAgent, @"iemobile\/(\d+(\.\d+)?)"); } else if (contains(userAgent, @"msie|trident")) { DisplayName = "Internet Explorer"; Browser = BrowserType.IE; DisplayVersion = getNamedGroup(userAgent, "version", @"(?:msie |rv\:)(?<version>\d+(\.\d+)?)"); } else if (contains(userAgent, @"chrome|crios|crmo")) { DisplayName = "Chrome"; Browser = BrowserType.Chrome; DisplayVersion = getNamedGroup(userAgent, "version", @"(?:chrome|crios|crmo)\/(?<version>\d+(\.\d+)?)"); } else if (iosdevice != null) { if (iosdevice == "iphone") { DisplayName = "iPhone"; Browser = BrowserType.iPhone; } else if (iosdevice == "ipad") { DisplayName = "iPad"; Browser = BrowserType.iPad; } else { DisplayName = "iPod"; Browser = BrowserType.iPod; } DisplayVersion = versionIdentifier; } else if (contains(userAgent, @"sailfish")) { DisplayName = "Sailfish"; Browser = BrowserType.Sailfish; DisplayVersion = getFirstMatch(userAgent, @"sailfish\s?Browser\/(\d+(\.\d+)?)"); } else if (contains(userAgent, @"seamonkey\/")) { DisplayName = "SeaMonkey"; Browser = BrowserType.SeaMonkey; DisplayVersion = getFirstMatch(userAgent, @"seamonkey\/(\d+(\.\d+)?)"); } else if (contains(userAgent, @"firefox|iceweasel")) { DisplayName = "Firefox"; Browser = BrowserType.Firefox; DisplayVersion = getNamedGroup(userAgent, "version", @"(?:firefox|iceweasel)[ \/](?<version>\d+(\.\d+)?)"); } else if (contains(userAgent, @"silk")) { DisplayName = "Amazon Silk"; Browser = BrowserType.Silk; DisplayVersion = getFirstMatch(userAgent, @"silk\/(\d+(\.\d+)?)"); } else if (IsAndroid) { DisplayName = "Android"; Browser = BrowserType.Android; DisplayVersion = versionIdentifier; } else if (contains(userAgent, @"phantom")) { DisplayName = "PhantomJS"; Browser = BrowserType.PhantomJS; DisplayVersion = getFirstMatch(userAgent, @"phantomjs\/(\d+(\.\d+)?)"); } else if (contains(userAgent, @"blackberry|\bbb\d+") || contains(userAgent, @"rim\stablet")) { DisplayName = "BlackBerry"; Browser = BrowserType.BlackBerry; DisplayVersion = (versionIdentifier != null ? versionIdentifier : getFirstMatch(userAgent, @"blackberry[\d]+\/(\d+(\.\d+)?)")); } else if (contains(userAgent, @"(web|hpw)os")) { DisplayName = "WebOS"; Browser = BrowserType.WebOS; DisplayVersion = (versionIdentifier != null ? versionIdentifier : getNamedGroup(userAgent, "version", @"w(?:eb)?osBrowser\/(?<version>\d+(\.\d+)?)")); } else if (contains(userAgent, @"bada")) { DisplayName = "Bada"; Browser = BrowserType.Bada; DisplayVersion = getFirstMatch(userAgent, @"dolfin\/(\d+(\.\d+)?)"); } else if (contains(userAgent, @"tizen")) { DisplayName = "Tizen"; Browser = BrowserType.Tizen; DisplayVersion = getNamedGroup(userAgent, "version", @"(?:tizen\s?)?Browser\/(?<version>\d+(\.\d+)?)"); if (DisplayVersion == null) { DisplayVersion = versionIdentifier; } } else if (contains(userAgent, @"safari")) { DisplayName = "Safari"; Browser = BrowserType.Safari; DisplayVersion = versionIdentifier; } } private static Version ParseVersion(string version) { int major = 0; int minor = 0; int build = 0; int revision = 0; string[] versionParts = version.Split('.'); if (versionParts.Length > 3) { int.TryParse(versionParts[3], out revision); } if (versionParts.Length > 2) { int.TryParse(versionParts[2], out build); } if (versionParts.Length > 1) { int.TryParse(versionParts[1], out minor); } if (versionParts.Length > 0) { int.TryParse(versionParts[0], out major); } return new Version(major, minor, build, revision); } private static string getFirstMatch(string source, string pattern) { Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); Match match = regex.Match(source); if (match.Success) { return match.Value; } return null; } private static string getNamedGroup(string source, string name, string pattern) { Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); MatchCollection matches = regex.Matches(source); if (matches.Count > 0) { return matches[0].Groups[name].Value; } return null; } private static string getMatch(int matchIndex, string source, string pattern) { Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); MatchCollection matches = regex.Matches(source); if (matches.Count > matchIndex) { return matches[matchIndex].Value; } return null; } private static bool contains(string source, string pattern) { return getFirstMatch(source, pattern) != null; } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // 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.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.3.6.7. response to an action request PDU /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(FixedDatum))] [XmlInclude(typeof(VariableDatum))] public partial class ActionResponsePdu : SimulationManagementPdu, IEquatable<ActionResponsePdu> { /// <summary> /// Request ID that is unique /// </summary> private uint _requestID; /// <summary> /// Status of response /// </summary> private uint _requestStatus; /// <summary> /// Number of fixed datum records /// </summary> private uint _fixedDatumRecordCount; /// <summary> /// Number of variable datum records /// </summary> private uint _variableDatumRecordCount; /// <summary> /// variable length list of fixed datums /// </summary> private List<FixedDatum> _fixedDatums = new List<FixedDatum>(); /// <summary> /// variable length list of variable length datums /// </summary> private List<VariableDatum> _variableDatums = new List<VariableDatum>(); /// <summary> /// Initializes a new instance of the <see cref="ActionResponsePdu"/> class. /// </summary> public ActionResponsePdu() { PduType = (byte)17; } /// <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 !=(ActionResponsePdu left, ActionResponsePdu 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 both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(ActionResponsePdu left, ActionResponsePdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += 4; // this._requestID marshalSize += 4; // this._requestStatus marshalSize += 4; // this._fixedDatumRecordCount marshalSize += 4; // this._variableDatumRecordCount for (int idx = 0; idx < this._fixedDatums.Count; idx++) { FixedDatum listElement = (FixedDatum)this._fixedDatums[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { VariableDatum listElement = (VariableDatum)this._variableDatums[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the Request ID that is unique /// </summary> [XmlElement(Type = typeof(uint), ElementName = "requestID")] public uint RequestID { get { return this._requestID; } set { this._requestID = value; } } /// <summary> /// Gets or sets the Status of response /// </summary> [XmlElement(Type = typeof(uint), ElementName = "requestStatus")] public uint RequestStatus { get { return this._requestStatus; } set { this._requestStatus = value; } } /// <summary> /// Gets or sets the Number of fixed datum records /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getfixedDatumRecordCount method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "fixedDatumRecordCount")] public uint FixedDatumRecordCount { get { return this._fixedDatumRecordCount; } set { this._fixedDatumRecordCount = value; } } /// <summary> /// Gets or sets the Number of variable datum records /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getvariableDatumRecordCount method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "variableDatumRecordCount")] public uint VariableDatumRecordCount { get { return this._variableDatumRecordCount; } set { this._variableDatumRecordCount = value; } } /// <summary> /// Gets the variable length list of fixed datums /// </summary> [XmlElement(ElementName = "fixedDatumsList", Type = typeof(List<FixedDatum>))] public List<FixedDatum> FixedDatums { get { return this._fixedDatums; } } /// <summary> /// Gets the variable length list of variable length datums /// </summary> [XmlElement(ElementName = "variableDatumsList", Type = typeof(List<VariableDatum>))] public List<VariableDatum> VariableDatums { get { return this._variableDatums; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { dos.WriteUnsignedInt((uint)this._requestID); dos.WriteUnsignedInt((uint)this._requestStatus); dos.WriteUnsignedInt((uint)this._fixedDatums.Count); dos.WriteUnsignedInt((uint)this._variableDatums.Count); for (int idx = 0; idx < this._fixedDatums.Count; idx++) { FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx]; aFixedDatum.Marshal(dos); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx]; aVariableDatum.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._requestID = dis.ReadUnsignedInt(); this._requestStatus = dis.ReadUnsignedInt(); this._fixedDatumRecordCount = dis.ReadUnsignedInt(); this._variableDatumRecordCount = dis.ReadUnsignedInt(); for (int idx = 0; idx < this.FixedDatumRecordCount; idx++) { FixedDatum anX = new FixedDatum(); anX.Unmarshal(dis); this._fixedDatums.Add(anX); } for (int idx = 0; idx < this.VariableDatumRecordCount; idx++) { VariableDatum anX = new VariableDatum(); anX.Unmarshal(dis); this._variableDatums.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<ActionResponsePdu>"); base.Reflection(sb); try { sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>"); sb.AppendLine("<requestStatus type=\"uint\">" + this._requestStatus.ToString(CultureInfo.InvariantCulture) + "</requestStatus>"); sb.AppendLine("<fixedDatums type=\"uint\">" + this._fixedDatums.Count.ToString(CultureInfo.InvariantCulture) + "</fixedDatums>"); sb.AppendLine("<variableDatums type=\"uint\">" + this._variableDatums.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatums>"); for (int idx = 0; idx < this._fixedDatums.Count; idx++) { sb.AppendLine("<fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"FixedDatum\">"); FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx]; aFixedDatum.Reflection(sb); sb.AppendLine("</fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { sb.AppendLine("<variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">"); VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx]; aVariableDatum.Reflection(sb); sb.AppendLine("</variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</ActionResponsePdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <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) { return this == obj as ActionResponsePdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(ActionResponsePdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (this._requestID != obj._requestID) { ivarsEqual = false; } if (this._requestStatus != obj._requestStatus) { ivarsEqual = false; } if (this._fixedDatumRecordCount != obj._fixedDatumRecordCount) { ivarsEqual = false; } if (this._variableDatumRecordCount != obj._variableDatumRecordCount) { ivarsEqual = false; } if (this._fixedDatums.Count != obj._fixedDatums.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._fixedDatums.Count; idx++) { if (!this._fixedDatums[idx].Equals(obj._fixedDatums[idx])) { ivarsEqual = false; } } } if (this._variableDatums.Count != obj._variableDatums.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._variableDatums.Count; idx++) { if (!this._variableDatums[idx].Equals(obj._variableDatums[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._requestID.GetHashCode(); result = GenerateHash(result) ^ this._requestStatus.GetHashCode(); result = GenerateHash(result) ^ this._fixedDatumRecordCount.GetHashCode(); result = GenerateHash(result) ^ this._variableDatumRecordCount.GetHashCode(); if (this._fixedDatums.Count > 0) { for (int idx = 0; idx < this._fixedDatums.Count; idx++) { result = GenerateHash(result) ^ this._fixedDatums[idx].GetHashCode(); } } if (this._variableDatums.Count > 0) { for (int idx = 0; idx < this._variableDatums.Count; idx++) { result = GenerateHash(result) ^ this._variableDatums[idx].GetHashCode(); } } return result; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Edge.Mount.FileSystem; using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Edge.Settings { public class Scanner { public Scanner(IEngineEnvironmentSettings environmentSettings) { _environmentSettings = environmentSettings; _paths = new Paths(environmentSettings); } private readonly IEngineEnvironmentSettings _environmentSettings; private readonly Paths _paths; public ScanResult Scan(string baseDir) { return Scan(baseDir, false); } public ScanResult Scan(string baseDir, bool allowDevInstall) { IReadOnlyList<string> directoriesToScan = DetermineDirectoriesToScan(baseDir); IReadOnlyList<MountPointScanSource> sourceList = SetupMountPointScanInfoForInstallSourceList(directoriesToScan); ScanResult scanResult = new ScanResult(); ScanSourcesForComponents(sourceList, allowDevInstall); ScanSourcesForTemplatesAndLangPacks(sourceList, scanResult); // Cleanup. // The source mount points are done being used, release them. The caller will delete the source files if needed. foreach (MountPointScanSource source in sourceList) { _environmentSettings.SettingsLoader.ReleaseMountPoint(source.MountPoint); } return scanResult; } private IReadOnlyList<string> DetermineDirectoriesToScan(string baseDir) { List<string> directoriesToScan = new List<string>(); if (baseDir[baseDir.Length - 1] == '/' || baseDir[baseDir.Length - 1] == '\\') { baseDir = baseDir.Substring(0, baseDir.Length - 1); } string searchTarget = Path.Combine(_environmentSettings.Host.FileSystem.GetCurrentDirectory(), baseDir.Trim()); List<string> matches = _environmentSettings.Host.FileSystem.EnumerateFileSystemEntries(Path.GetDirectoryName(searchTarget), Path.GetFileName(searchTarget), SearchOption.TopDirectoryOnly) .Where(x => !x.EndsWith("symbols.nupkg", StringComparison.OrdinalIgnoreCase)).ToList(); if (matches.Count == 1) { directoriesToScan.Add(matches[0]); } else { foreach (string match in matches) { IReadOnlyList<string> subDirMatches = DetermineDirectoriesToScan(match); directoriesToScan.AddRange(subDirMatches); } } return directoriesToScan; } private IReadOnlyList<MountPointScanSource> SetupMountPointScanInfoForInstallSourceList(IReadOnlyList<string> directoriesToScan) { List<MountPointScanSource> locationList = new List<MountPointScanSource>(); foreach (string directory in directoriesToScan) { MountPointScanSource locationInfo = GetOrCreateMountPointScanInfoForInstallSource(directory); if (locationInfo != null) { locationList.Add(locationInfo); } } return locationList; } private MountPointScanSource GetOrCreateMountPointScanInfoForInstallSource(string sourceLocation) { if (_environmentSettings.SettingsLoader.TryGetMountPointFromPlace(sourceLocation, out IMountPoint existingMountPoint)) { return new MountPointScanSource() { Location = sourceLocation, MountPoint = existingMountPoint, FoundTemplates = false, FoundComponents = false, ShouldStayInOriginalLocation = true, }; } else { foreach (IMountPointFactory factory in _environmentSettings.SettingsLoader.Components.OfType<IMountPointFactory>().ToList()) { if (factory.TryMount(_environmentSettings, null, sourceLocation, out IMountPoint mountPoint)) { // file-based and not originating in the scratch dir. bool isLocalFlatFileSource = mountPoint.Info.MountPointFactoryId == FileSystemMountPointFactory.FactoryId && !sourceLocation.StartsWith(_paths.User.ScratchDir); return new MountPointScanSource() { Location = sourceLocation, MountPoint = mountPoint, ShouldStayInOriginalLocation = isLocalFlatFileSource, FoundTemplates = false, FoundComponents = false, }; } } } return null; } // Iterate over the sourceList, scanning for components. // Track the sources that didn't find any components. // If any source found components, re-try the remaining sources that didn't find any components. // Repeat until all sources have found components, or none of the remaining sources find anything. // This is to avoid problems with the load order - an assembly that depends on another assembly can't be loaded until the dependent assembly has been loaded. private void ScanSourcesForComponents(IReadOnlyList<MountPointScanSource> sourceList, bool allowDevInstall) { List<MountPointScanSource> workingSet = new List<MountPointScanSource>(sourceList); bool anythingFoundThisRound; do { anythingFoundThisRound = false; List<MountPointScanSource> unhandledSources = new List<MountPointScanSource>(); foreach (MountPointScanSource source in workingSet) { ScanForComponents(source, allowDevInstall); anythingFoundThisRound |= source.FoundComponents; if (!source.FoundComponents) { unhandledSources.Add(source); } } workingSet = unhandledSources; } while (anythingFoundThisRound && workingSet.Count > 0); } private void ScanForComponents(MountPointScanSource source, bool allowDevInstall) { bool isCopiedIntoContentDirectory; if (!source.MountPoint.Root.EnumerateFiles("*.dll", SearchOption.AllDirectories).Any()) { return; } string actualScanPath; if (!source.ShouldStayInOriginalLocation) { if (!TryCopyForNonFileSystemBasedMountPoints(source.MountPoint, source.Location, _paths.User.Content, true, out actualScanPath)) { return; } isCopiedIntoContentDirectory = true; } else { if (!allowDevInstall) { // TODO: localize this message _environmentSettings.Host.LogDiagnosticMessage("Installing local .dll files is not a standard supported scenario. Either package it in a .zip or .nupkg, or install it using '--dev:install'.", "Install"); // dont allow .dlls to be installed from a file unless the debugging flag is set. return; } actualScanPath = source.Location; isCopiedIntoContentDirectory = false; } foreach (KeyValuePair<string, Assembly> asm in AssemblyLoader.LoadAllFromPath(_paths, out IEnumerable<string> failures, actualScanPath)) { try { IReadOnlyList<Type> typeList = asm.Value.GetTypes(); if (typeList.Count > 0) { // TODO: figure out what to do with probing path registration when components are not found. // They need to be registered for dependent assemblies, not just when an assembly can be loaded. // We'll need to figure out how to know when that is. _environmentSettings.SettingsLoader.Components.RegisterMany(typeList); _environmentSettings.SettingsLoader.AddProbingPath(Path.GetDirectoryName(asm.Key)); source.FoundComponents = true; } } catch { // exceptions here are ok, due to dependency errors, etc. } } if (!source.FoundComponents && isCopiedIntoContentDirectory) { try { // The source was copied to content and then scanned for components. // Nothing was found, and this is a copy that now has no use, so delete it. // Note: no mount point was created for this copy, so no need to release it. _environmentSettings.Host.FileSystem.DirectoryDelete(actualScanPath, true); } catch (Exception ex) { _environmentSettings.Host.LogDiagnosticMessage($"During ScanForComponents() cleanup, couldn't delete source copied into the content dir: {actualScanPath}", "Install"); _environmentSettings.Host.LogDiagnosticMessage($"\tError: {ex.Message}", "Install"); } } } private bool TryCopyForNonFileSystemBasedMountPoints(IMountPoint mountPoint, string sourceLocation, string targetBasePath, bool expandIfArchive, out string diskPath) { string targetPath = Path.Combine(targetBasePath, Path.GetFileName(sourceLocation)); try { if (expandIfArchive) { mountPoint.Root.CopyTo(targetPath); } else { _paths.CreateDirectory(targetBasePath); // creates Packages/ or Content/ if needed _paths.Copy(sourceLocation, targetPath); } } catch (IOException) { _environmentSettings.Host.LogDiagnosticMessage($"Error copying scanLocation: {sourceLocation} into the target dir: {targetPath}", "Install"); diskPath = null; return false; } diskPath = targetPath; return true; } private void ScanSourcesForTemplatesAndLangPacks(IReadOnlyList<MountPointScanSource> sourceList, ScanResult scanResult) { // only scan for templates & langpacks if no components were found. foreach (MountPointScanSource source in sourceList.Where(x => !x.AnythingFound)) { ScanMountPointForTemplatesAndLangpacks(source, scanResult); } } private void ScanMountPointForTemplatesAndLangpacks(MountPointScanSource source, ScanResult scanResult) { bool isCopiedIntoPackagesDirectory; string actualScanPath; IMountPoint scanMountPoint = null; if (!source.ShouldStayInOriginalLocation) { if (!TryCopyForNonFileSystemBasedMountPoints(source.MountPoint, source.Location, _paths.User.Packages, false, out actualScanPath)) { return; } // Try get an existing mount point for the scan location if (!_environmentSettings.SettingsLoader.TryGetMountPointFromPlace(actualScanPath, out scanMountPoint)) { // The mount point didn't exist, try creating a new one foreach (IMountPointFactory factory in _environmentSettings.SettingsLoader.Components.OfType<IMountPointFactory>()) { if (factory.TryMount(_environmentSettings, null, actualScanPath, out scanMountPoint)) { break; } } } if (scanMountPoint == null) { _environmentSettings.Host.FileSystem.FileDelete(actualScanPath); return; } isCopiedIntoPackagesDirectory = true; } else { actualScanPath = source.Location; scanMountPoint = source.MountPoint; isCopiedIntoPackagesDirectory = false; } // look for things to install foreach (IGenerator generator in _environmentSettings.SettingsLoader.Components.OfType<IGenerator>()) { IList<ITemplate> templateList = generator.GetTemplatesAndLangpacksFromDir(scanMountPoint, out IList<ILocalizationLocator> localizationInfo); foreach (ILocalizationLocator locator in localizationInfo) { scanResult.AddLocalization(locator); } foreach (ITemplate template in templateList) { scanResult.AddTemplate(template); } source.FoundTemplates |= templateList.Count > 0 || localizationInfo.Count > 0; } // finalize the result if (source.FoundTemplates) { // add the MP _environmentSettings.SettingsLoader.AddMountPoint(scanMountPoint); // add the MP to the scan result scanResult.AddInstalledMountPointId(scanMountPoint.Info.MountPointId); } else { // delete the copy if (!source.FoundTemplates && isCopiedIntoPackagesDirectory) { try { // The source was copied to packages and then scanned for templates. // Nothing was found, and this is a copy that now has no use, so delete it. _environmentSettings.SettingsLoader.ReleaseMountPoint(scanMountPoint); // It's always copied as an archive, so it's a file delete, not a directory delete _environmentSettings.Host.FileSystem.FileDelete(actualScanPath); } catch (Exception ex) { _environmentSettings.Host.LogDiagnosticMessage($"During ScanMountPointForTemplatesAndLangpacks() cleanup, couldn't delete source copied into the packages dir: {actualScanPath}", "Install"); _environmentSettings.Host.LogDiagnosticMessage($"\tError: {ex.Message}", "Install"); } } } } private class MountPointScanSource { public string Location { get; set; } public IMountPoint MountPoint { get; set; } public bool ShouldStayInOriginalLocation { get; set; } public bool FoundComponents { get; set; } public bool FoundTemplates { get; set; } public bool AnythingFound { get { return FoundTemplates || FoundComponents; } } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCustomerExtensionSettingServiceClientTest { [Category("Autogenerated")][Test] public void GetCustomerExtensionSettingRequestObject() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting response = client.GetCustomerExtensionSetting(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerExtensionSettingRequestObjectAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting responseCallSettings = await client.GetCustomerExtensionSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerExtensionSetting responseCancellationToken = await client.GetCustomerExtensionSettingAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerExtensionSetting() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting response = client.GetCustomerExtensionSetting(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerExtensionSettingAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting responseCallSettings = await client.GetCustomerExtensionSettingAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerExtensionSetting responseCancellationToken = await client.GetCustomerExtensionSettingAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerExtensionSettingResourceNames() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting response = client.GetCustomerExtensionSetting(request.ResourceNameAsCustomerExtensionSettingName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerExtensionSettingResourceNamesAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCustomerExtensionSettingRequest request = new GetCustomerExtensionSettingRequest { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), }; gagvr::CustomerExtensionSetting expectedResponse = new gagvr::CustomerExtensionSetting { ResourceNameAsCustomerExtensionSettingName = gagvr::CustomerExtensionSettingName.FromCustomerExtensionType("[CUSTOMER_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCustomerExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerExtensionSetting responseCallSettings = await client.GetCustomerExtensionSettingAsync(request.ResourceNameAsCustomerExtensionSettingName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerExtensionSetting responseCancellationToken = await client.GetCustomerExtensionSettingAsync(request.ResourceNameAsCustomerExtensionSettingName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerExtensionSettingsRequestObject() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCustomerExtensionSettingsRequest request = new MutateCustomerExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerExtensionSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCustomerExtensionSettingsResponse expectedResponse = new MutateCustomerExtensionSettingsResponse { Results = { new MutateCustomerExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerExtensionSettingsResponse response = client.MutateCustomerExtensionSettings(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerExtensionSettingsRequestObjectAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCustomerExtensionSettingsRequest request = new MutateCustomerExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerExtensionSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCustomerExtensionSettingsResponse expectedResponse = new MutateCustomerExtensionSettingsResponse { Results = { new MutateCustomerExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerExtensionSettingsResponse responseCallSettings = await client.MutateCustomerExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerExtensionSettingsResponse responseCancellationToken = await client.MutateCustomerExtensionSettingsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerExtensionSettings() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCustomerExtensionSettingsRequest request = new MutateCustomerExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerExtensionSettingOperation(), }, }; MutateCustomerExtensionSettingsResponse expectedResponse = new MutateCustomerExtensionSettingsResponse { Results = { new MutateCustomerExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerExtensionSettingsResponse response = client.MutateCustomerExtensionSettings(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerExtensionSettingsAsync() { moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CustomerExtensionSettingService.CustomerExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCustomerExtensionSettingsRequest request = new MutateCustomerExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerExtensionSettingOperation(), }, }; MutateCustomerExtensionSettingsResponse expectedResponse = new MutateCustomerExtensionSettingsResponse { Results = { new MutateCustomerExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerExtensionSettingServiceClient client = new CustomerExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerExtensionSettingsResponse responseCallSettings = await client.MutateCustomerExtensionSettingsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerExtensionSettingsResponse responseCancellationToken = await client.MutateCustomerExtensionSettingsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * 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 OpenMetaverse; using System.Collections.Generic; namespace OpenSim.Data.Null { public class NullPresenceData : IPresenceData { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static NullPresenceData Instance; Dictionary<UUID, PresenceData> m_presenceData = new Dictionary<UUID, PresenceData>(); public NullPresenceData(string connectionString, string realm) { if (Instance == null) { Instance = this; //Console.WriteLine("[XXX] NullRegionData constructor"); } } public bool Store(PresenceData data) { if (Instance != this) return Instance.Store(data); // m_log.DebugFormat("[NULL PRESENCE DATA]: Storing presence {0}", data.UserID); // Console.WriteLine("HOME for " + data.UserID + " is " + (data.Data.ContainsKey("HomeRegionID") ? data.Data["HomeRegionID"] : "Not found")); m_presenceData[data.SessionID] = data; return true; } public PresenceData Get(UUID sessionID) { if (Instance != this) return Instance.Get(sessionID); if (m_presenceData.ContainsKey(sessionID)) { return m_presenceData[sessionID]; } return null; } public void LogoutRegionAgents(UUID regionID) { if (Instance != this) { Instance.LogoutRegionAgents(regionID); return; } List<UUID> toBeDeleted = new List<UUID>(); foreach (KeyValuePair<UUID, PresenceData> kvp in m_presenceData) if (kvp.Value.RegionID == regionID) toBeDeleted.Add(kvp.Key); foreach (UUID u in toBeDeleted) m_presenceData.Remove(u); } public bool ReportAgent(UUID sessionID, UUID regionID) { if (Instance != this) return Instance.ReportAgent(sessionID, regionID); if (m_presenceData.ContainsKey(sessionID)) { m_presenceData[sessionID].RegionID = regionID; return true; } return false; } public PresenceData[] Get(string field, string data) { if (Instance != this) return Instance.Get(field, data); // m_log.DebugFormat( // "[NULL PRESENCE DATA]: Getting presence data for field {0} with parameter {1}", field, data); List<PresenceData> presences = new List<PresenceData>(); if (field == "UserID") { foreach (PresenceData p in m_presenceData.Values) { if (p.UserID == data) { presences.Add(p); // Console.WriteLine("HOME for " + p.UserID + " is " + (p.Data.ContainsKey("HomeRegionID") ? p.Data["HomeRegionID"] : "Not found")); } } return presences.ToArray(); } else if (field == "SessionID") { UUID session = UUID.Zero; if (!UUID.TryParse(data, out session)) return presences.ToArray(); if (m_presenceData.ContainsKey(session)) { presences.Add(m_presenceData[session]); return presences.ToArray(); } } else if (field == "RegionID") { UUID region = UUID.Zero; if (!UUID.TryParse(data, out region)) return presences.ToArray(); foreach (PresenceData p in m_presenceData.Values) if (p.RegionID == region) presences.Add(p); return presences.ToArray(); } else { foreach (PresenceData p in m_presenceData.Values) { if (p.Data.ContainsKey(field) && p.Data[field] == data) presences.Add(p); } return presences.ToArray(); } return presences.ToArray(); } public bool Delete(string field, string data) { // m_log.DebugFormat( // "[NULL PRESENCE DATA]: Deleting presence data for field {0} with parameter {1}", field, data); if (Instance != this) return Instance.Delete(field, data); List<UUID> presences = new List<UUID>(); if (field == "UserID") { foreach (KeyValuePair<UUID, PresenceData> p in m_presenceData) if (p.Value.UserID == data) presences.Add(p.Key); } else if (field == "SessionID") { UUID session = UUID.Zero; if (UUID.TryParse(data, out session)) { if (m_presenceData.ContainsKey(session)) { presences.Add(session); } } } else if (field == "RegionID") { UUID region = UUID.Zero; if (UUID.TryParse(data, out region)) { foreach (KeyValuePair<UUID, PresenceData> p in m_presenceData) if (p.Value.RegionID == region) presences.Add(p.Key); } } else { foreach (KeyValuePair<UUID, PresenceData> p in m_presenceData) { if (p.Value.Data.ContainsKey(field) && p.Value.Data[field] == data) presences.Add(p.Key); } } foreach (UUID u in presences) m_presenceData.Remove(u); if (presences.Count == 0) return false; return true; } public bool VerifyAgent(UUID agentId, UUID secureSessionID) { if (Instance != this) return Instance.VerifyAgent(agentId, secureSessionID); return false; } } }
using TimedText.Timing; using TimedText.Formatting; using System.Globalization; namespace TimedText { /// <summary> /// The span element functions as a logical container and a temporal /// structuring element for a sequence of textual content units having inline /// level formatting semantics. The span element accepts as its children zero or /// more elements in the Metadata.class element group, followed by zero or more /// elements in the Animation.class element group, followed by zero or more br /// element or text nodes interpreted as anonymous spans. /// /// The span class also represents open text nodes, and thus has a Text property. /// When presented on a visual medium, a span element is intended to generate a /// sequence of inline areas, each containing one or more glyph areas. /// </summary> public class SpanElement : TimedTextElementBase { #region Constructor /// <summary> /// Constructor /// </summary> public SpanElement(string text) { AnonymousSpanElement aSpan = new AnonymousSpanElement(text); Children.Add(aSpan); aSpan.Parent = this; TimeSemantics = TimeContainer.Par; } /// <summary> /// Constructor to set defaults /// </summary> public SpanElement() { TimeSemantics = TimeContainer.Par; } #endregion #region Formatting /// <summary> /// Return formatting object for span element /// </summary> /// <param name="regionId"></param> /// <param name="tick"></param> /// <returns></returns> public override FormattingObject GetFormattingObject(TimeCode tick) { if (TemporallyActive(tick)) { var block = new Inline(this); foreach (var child in Children) { if (child is BrElement || child is AnonymousSpanElement) { #region Add text to the Inline formatting object var fo = (child as TimedTextElementBase).GetFormattingObject(tick); if (fo != null) { fo.Parent = block; block.Children.Add(fo); } #region copy metadata across to inline, since we want to use this foreach (var d in this.Metadata) { if (!child.Metadata.ContainsKey(d.Key)) { child.Metadata.Add(d.Key, d.Value); } } #endregion #endregion } else if (child is SpanElement) { #region flatten span hierarchy var fo = (child as SpanElement).GetFormattingObject(tick); if (fo != null) { /* /// Flattened nested <span>A<span>B</span>C</span> /// -> <Inline>A</Inline><Inline>B</Inline><Inline>C</Inline> /// by hoisting out to outer context. /// Hoisted elements will still inherit correctly, as style is inherited through /// the Timed Text tree, not the formatting object tree. /// something to watch out for when computing relative /// values though. */ foreach (var nestedInline in fo.Children) { nestedInline.Parent = block; block.Children.Add(nestedInline); } } #endregion } if (child is SetElement) { #region Add animations to Inline var fo = ((child as SetElement).GetFormattingObject(tick)) as Animation; if (fo != null) { block.Animations.Add(fo); } #endregion } } return block; } else { return null; } } #endregion #region Validity /* <span begin = <timeExpression> dur = <timeExpression> end = <timeExpression> region = IDREF style = IDREFS timeContainer = (par|seq) xml:id = ID xml:lang = string xml:space = (default|preserve) {any attribute in TT Metadata namespace ...} {any attribute in TT Style namespace ...} {any attribute not in default or any TT namespace ...}> Content: Metadata.class*, Animation.class*, Inline.class* </span> */ /// <summary> /// Check validity of span element attributes /// </summary> protected override void ValidAttributes() { ValidateAttributes(false, true, true, true, true, true); } /// <summary> /// Check valisdity of span element content model /// </summary> protected override void ValidElements() { int child = 0; #region Allow arbitrary metadata while ((child < Children.Count) && ((Children[child] is MetadataElement) || (Children[child] is Metadata.MetadataElement) //|| (Children[child] is anonymousSpan) )) { child++; } #endregion #region Allow arbitrary set elements (Animation class) while ((child < Children.Count) && ((Children[child] is SetElement) //|| (Children[child] is anonymousSpan) )) { child++; } #endregion #region Allow arbitrary span, br and PCDATA (Inline class) while ((child < Children.Count) && ((Children[child] is SpanElement) || (Children[child] is BrElement) || (Children[child] is AnonymousSpanElement) )) { child++; } #endregion #region Ensure no other element present if (Children.Count != child) { Error(Children[child].ToString() + " is not allowed in " + this.ToString() + " at position " + child.ToString(CultureInfo.CurrentCulture)); } #endregion #region Check each of the children is individually valid foreach (TimedTextElementBase element in Children) { element.Valid(); } #endregion } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Lunchorder.Common.Interfaces; using Lunchorder.Domain.Dtos; using Lunchorder.Domain.Entities.Authentication; using Lunchorder.Domain.Entities.DocumentDb; using UserBadge = Lunchorder.Domain.Entities.DocumentDb.UserBadge; namespace Lunchorder.Api.Infrastructure.Services { public class BadgeService : IBadgeService { private readonly IMapper _mapper; public List<Badge> Badges; public BadgeService(IMapper mapper) { _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); Badges = Domain.Constants.Badges.BadgeList; } private string OrderBadgeMessage(Badge badge) { return $"You earned the {badge.Name} badge"; } private string PrepayBadgeMessage(Badge badge, string username) { return $"{username} earned the {badge.Name} badge"; } private void CalculateStatistics(ApplicationUser applicationUser, Domain.Entities.DocumentDb.UserOrderHistory userOrderHistory) { if (!userOrderHistory.StatisticsProcessed) { var monthlyTotal = applicationUser.Statistics.MonthlyTotals.FirstOrDefault(x => x.MonthDate == x.ParseMonth(userOrderHistory.OrderTime)); if (monthlyTotal == null) { monthlyTotal = new MonthlyTotal(userOrderHistory.OrderTime); applicationUser.Statistics.MonthlyTotals.Add(monthlyTotal); } var yearlyTotal = applicationUser.Statistics.YearlyTotals.FirstOrDefault(x => x.YearDate == x.ParseYear(userOrderHistory.OrderTime)); if (yearlyTotal == null) { yearlyTotal = new YearlyTotal(userOrderHistory.OrderTime); applicationUser.Statistics.YearlyTotals.Add(yearlyTotal); } var weeklyTotal = applicationUser.Statistics.WeeklyTotals.FirstOrDefault(x => x.WeekDate == x.ParseWeek(userOrderHistory.OrderTime)); if (weeklyTotal == null) { weeklyTotal = new WeeklyTotal(userOrderHistory.OrderTime); applicationUser.Statistics.WeeklyTotals.Add(weeklyTotal); } var dailyTotal = applicationUser.Statistics.DayTotals.FirstOrDefault(x => x.DayDate == x.ParseDay(userOrderHistory.OrderTime)); if (dailyTotal == null) { dailyTotal = new DayTotal(userOrderHistory.OrderTime); applicationUser.Statistics.DayTotals.Add(dailyTotal); } foreach (var entry in userOrderHistory.Entries) { if (entry.Pasta) { yearlyTotal.PastaOrderCount += 1; } if (entry.Healthy) { weeklyTotal.HealthyOrderCount += 1; } yearlyTotal.OrderCount += 1; yearlyTotal.Amount += entry.FinalPrice; weeklyTotal.OrderCount += 1; weeklyTotal.Amount += entry.FinalPrice; monthlyTotal.OrderCount += 1; monthlyTotal.Amount += entry.FinalPrice; dailyTotal.Amount += entry.FinalPrice; dailyTotal.OrderCount += 1; } applicationUser.Statistics.AppTotalSpend += userOrderHistory.FinalPrice; userOrderHistory.StatisticsProcessed = true; // cleanup old data var daysToDelete = applicationUser.Statistics.DayTotals.Where(x => x.DayDate != x.ParseDay(DateTime.UtcNow)).ToList(); foreach (var dayToDelete in daysToDelete) { applicationUser.Statistics.DayTotals.Remove(dayToDelete); } var weeksToDelete = applicationUser.Statistics.WeeklyTotals.Where(x => x.WeekDate != x.ParseWeek(DateTime.UtcNow)).ToList(); foreach (var weekToDelete in weeksToDelete) { applicationUser.Statistics.WeeklyTotals.Remove(weekToDelete); } var monthsToDelete = applicationUser.Statistics.MonthlyTotals.Where(x => x.MonthDate != x.ParseMonth(DateTime.UtcNow)).ToList(); foreach (var monthToDelete in monthsToDelete) { applicationUser.Statistics.MonthlyTotals.Remove(monthToDelete); } var yearsToDelete = applicationUser.Statistics.YearlyTotals.Where(x => x.YearDate != x.ParseYear(DateTime.UtcNow)).ToList(); foreach (var yearToDelete in yearsToDelete) { applicationUser.Statistics.YearlyTotals.Remove(yearToDelete); } } } public List<string> ExtractPrepayBadges(ApplicationUser applicationUser, decimal prepayAmount) { var badgeAlerts = new List<string>(); if (HaveFaith(applicationUser, prepayAmount)) { badgeAlerts.Add(PrepayBadgeMessage(Domain.Constants.Badges.HaveFaith, applicationUser.UserName)); } return badgeAlerts; } public List<string> ExtractOrderBadges(ApplicationUser applicationUser, Domain.Entities.DocumentDb.UserOrderHistory userOrderHistory, DateTime vendorClosingTime) { CalculateStatistics(applicationUser, userOrderHistory); var badgeAlerts = new List<string>(); if (AssignFirstOrder(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.FirstOrder)); } if (HighRoller(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.HighRoller)); } if (DeepPockets(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.DeepPockets)); } if (Consumer(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.Consumer)); } if (Enjoyer(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.Enjoyer)); } if (DieHard(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.DieHard)); } if (Bankrupt(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.Bankrupt)); } if (Healthy(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.Healthy)); } if (PastaAddict(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.PastaAddict)); } if (CloseCall(applicationUser, userOrderHistory, Domain.Constants.Badges.CloseCall15, 0, 15, vendorClosingTime)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.CloseCall15)); }; if (CloseCall(applicationUser, userOrderHistory, Domain.Constants.Badges.CloseCall30, 15, 30, vendorClosingTime)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.CloseCall30)); }; if (CloseCall(applicationUser, userOrderHistory, Domain.Constants.Badges.CloseCall45, 30, 45, vendorClosingTime)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.CloseCall45)); }; if (CloseCall(applicationUser, userOrderHistory, Domain.Constants.Badges.CloseCall60, 45, 60, vendorClosingTime)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.CloseCall60)); }; // calculation needs to be done over previously earned badges if (BadgeCollector(applicationUser)) { badgeAlerts.Add(OrderBadgeMessage(Domain.Constants.Badges.BadgeCollector)); }; return badgeAlerts; } private bool CloseCall(ApplicationUser applicationUser, Domain.Entities.DocumentDb.UserOrderHistory userOrderHistory, Badge badge, int startSeconds, int endSeconds, DateTime vendorClosingTime) { var closeCallBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == badge.Id); if (CanEarnBadge(closeCallBadge, badge)) { var diffInSeconds = vendorClosingTime.TimeOfDay - userOrderHistory.OrderTime.TimeOfDay; if (diffInSeconds.TotalSeconds > startSeconds && diffInSeconds.TotalSeconds <= endSeconds) { if (closeCallBadge == null) { var closeCallBadgeMap = MapBadge(badge); closeCallBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(closeCallBadgeMap); } else { closeCallBadge.TimesEarned += 1; } return true; } } return false; } private bool Bankrupt(ApplicationUser applicationUser) { var bankruptBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.Bankrupt.Id); if (CanEarnBadge(bankruptBadge, Domain.Constants.Badges.Bankrupt)) { if (applicationUser.Balance == 0) { if (bankruptBadge == null) { var bankruptBadgeMap = MapBadge(Domain.Constants.Badges.Bankrupt); bankruptBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(bankruptBadgeMap); } else { bankruptBadge.TimesEarned += 1; } return true; } } return false; } private bool PastaAddict(ApplicationUser applicationUser) { var pastaBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.PastaAddict.Id); if (CanEarnBadge(pastaBadge, Domain.Constants.Badges.PastaAddict)) { var yearlyStats = applicationUser.Statistics.YearlyTotals.FirstOrDefault(); if (yearlyStats != null) { if (applicationUser.Statistics.YearlyPastas > 52 && !yearlyStats.HasYearlyPastaBadge) { var pastaBadgeMap = MapBadge(Domain.Constants.Badges.PastaAddict); pastaBadgeMap.TimesEarned += 1; yearlyStats.HasYearlyPastaBadge = true; applicationUser.Badges.Add(pastaBadgeMap); return true; } } } return false; } private bool Consumer(ApplicationUser applicationUser) { var consumerBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.Consumer.Id); if (CanEarnBadge(consumerBadge, Domain.Constants.Badges.Consumer)) { if (applicationUser.Statistics.AppTotalSpend > 500) { var consumerBadgeMap = MapBadge(Domain.Constants.Badges.Consumer); consumerBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(consumerBadgeMap); return true; } } return false; } private bool Enjoyer(ApplicationUser applicationUser) { var enjoyerBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.Enjoyer.Id); if (CanEarnBadge(enjoyerBadge, Domain.Constants.Badges.Enjoyer)) { if (applicationUser.Statistics.AppTotalSpend > 1500) { var enjoyerBadgeMap = MapBadge(Domain.Constants.Badges.Enjoyer); enjoyerBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(enjoyerBadgeMap); return true; } } return false; } private bool DieHard(ApplicationUser applicationUser) { var dieHardBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.DieHard.Id); if (CanEarnBadge(dieHardBadge, Domain.Constants.Badges.DieHard)) { if (applicationUser.Statistics.AppTotalSpend > 3000) { var diehardBadgeMap = MapBadge(Domain.Constants.Badges.DieHard); diehardBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(diehardBadgeMap); return true; } } return false; } private bool Healthy(ApplicationUser applicationUser) { var hasHealthy = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.Healthy.Id); if (CanEarnBadge(hasHealthy, Domain.Constants.Badges.Healthy)) { // be backwards compatible with migration foreach (var weeklyTotal in applicationUser.Statistics.WeeklyTotals) { if (weeklyTotal.HealthyOrderCount >= 3 && !weeklyTotal.HasHealthyBadge) { if (hasHealthy != null) { hasHealthy.TimesEarned += 1; } else { var healthyBadgeMap = MapBadge(Domain.Constants.Badges.Healthy); healthyBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(healthyBadgeMap); } weeklyTotal.HasHealthyBadge = true; return true; } } } return false; } private bool DeepPockets(ApplicationUser applicationUser) { var hasDeepPockets = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.DeepPockets.Id); if (CanEarnBadge(hasDeepPockets, Domain.Constants.Badges.DeepPockets)) { // be backwards compatible with migration foreach (var monthlyTotal in applicationUser.Statistics.MonthlyTotals) { if (monthlyTotal.Amount > 75 && !monthlyTotal.HasDeepPocketsBadge) { if (hasDeepPockets != null) { hasDeepPockets.TimesEarned += 1; } else { var deepPocketsBadgeMap = MapBadge(Domain.Constants.Badges.DeepPockets); deepPocketsBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(deepPocketsBadgeMap); } monthlyTotal.HasDeepPocketsBadge = true; return true; } } } return false; } private bool HighRoller(ApplicationUser applicationUser) { var highRollerBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.HighRoller.Id); if (CanEarnBadge(highRollerBadge, Domain.Constants.Badges.HighRoller)) { // be backwards compatible with migration foreach (var weeklyTotal in applicationUser.Statistics.WeeklyTotals) { if (weeklyTotal.Amount > 30 && !weeklyTotal.HasHighRollerBadge) { if (highRollerBadge != null) { highRollerBadge.TimesEarned += 1; } else { var highRollerBadgeMap = MapBadge(Domain.Constants.Badges.HighRoller); highRollerBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(highRollerBadgeMap); } weeklyTotal.HasHighRollerBadge = true; return true; } } } return false; } private bool AssignFirstOrder(ApplicationUser applicationUser) { var firstOrderBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.FirstOrder.Id); if (CanEarnBadge(firstOrderBadge, Domain.Constants.Badges.FirstOrder)) { if (applicationUser.Statistics.AppTotalSpend > 0) { var firstOrderBadgeMap = MapBadge(Domain.Constants.Badges.FirstOrder); firstOrderBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(firstOrderBadgeMap); return true; } } return false; } private bool HaveFaith(ApplicationUser applicationUser, decimal prepayAmount) { var haveFaithBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.HaveFaith.Id); if (CanEarnBadge(haveFaithBadge, Domain.Constants.Badges.HaveFaith)) { if (prepayAmount >= 100) { if (haveFaithBadge != null) { haveFaithBadge.TimesEarned += 1; } else { var haveFaithBadgeMap = MapBadge(Domain.Constants.Badges.HaveFaith); haveFaithBadgeMap.TimesEarned += 1; applicationUser.Badges.Add(haveFaithBadgeMap); } return true; } } return false; } private bool BadgeCollector(ApplicationUser applicationUser) { var collectorBadge = applicationUser.Badges.FirstOrDefault(x => x.Id == Domain.Constants.Badges.BadgeCollector.Id); if (CanEarnBadge(collectorBadge, Domain.Constants.Badges.BadgeCollector)) { var totalBadges = 0; foreach (var b in applicationUser.Badges) { totalBadges += b.TimesEarned; } if (totalBadges > 10) { var badgeCollectorMap = MapBadge(Domain.Constants.Badges.BadgeCollector); badgeCollectorMap.TimesEarned += 1; applicationUser.Badges.Add(badgeCollectorMap); return true; } } return false; } private UserBadge MapBadge(Badge badge) { return _mapper.Map<Badge, UserBadge>(badge); } private bool CanEarnBadge(UserBadge userBadge, Badge badge) { return userBadge == null || badge.CanEarnMultipleTimes; } } }
using HoloJson.Common; using HoloJson.Core; using HoloJson.Lite; using HoloJson.Parser.Core; using HoloJson.Util; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HoloJson.Lite.Parser { // Base class for JsonTokenizer implementation. // TBD: // Make a tokenzier reusable (without having to create a new tokenizer for every Parse()'ing.) ??? // ... // Note: // Current implementation is not thread-safe (and, probably, never will be). // public sealed class LiteJsonTokenizer : Lite.LiteJsonTokenizer { // MAX_STRING_LOOKAHEAD_SIZE should be greater than 6. private const int MAX_STRING_LOOKAHEAD_SIZE = 128; // temporary // private const int MAX_STRING_LOOKAHEAD_SIZE = 512; // temporary private const int MAX_SPACE_LOOKAHEAD_SIZE = 32; // temporary // Note that the charqueue size should be bigger than the longest string in the file + reader_buff_size // (if we use "look ahead" for string parsing)!!!! // The parser/tokenizer fails when it encounters a string longer than that. // We cannot obviously use arbitrarily long char queue size, and // unfortunately, there is no limit in the size of a string in JSON, // which makes it possible that the uncilient parser can always fail, potentially... private const int CHARQUEUE_SIZE = 4096; // temporary // Note that CHARQUEUE_SIZE - delta >= READER_BUFF_SIZE // where delta is "false".Length, // or, more precisely the max length of PeekChars(len). // or, if we use string lookahead, it should be the size of the longest string rounded up to MAX_STRING_LOOKAHEAD_SIZE multiples... private const int READER_BUFF_SIZE = 1024; // temporary private const int HEAD_TRACE_LENGTH = 25; // temporary // ... private TextReader reader; private int curTextReaderIndex = 0; // global var to keep track of the reader reading state. private bool readerEOF = false; // true does not mean we are done, because we are using buffer. private JsonToken curToken = JsonToken.INVALID; // ????? private JsonToken nextToken = JsonToken.INVALID; // or, TokenPool.TOKEN_EOF ??? private JsonToken nextNextToken = JsonToken.INVALID; // ??? TBD: ... // private charQueue charQueue = null; // Note that charQueue is class-wide global variable. private readonly CharQueue charQueue; // If true, use "look ahead" algorithms. // private bool lookAheadParsing; // Ctor's public LiteJsonTokenizer(string str) : this(new StringReader(str)) { } public LiteJsonTokenizer(TextReader reader) : this(reader, CHARQUEUE_SIZE) { } public LiteJsonTokenizer(TextReader reader, int charQueueSize) { // TextReader cannot cannot be null. this.reader = reader; this.charQueue = new CharQueue(charQueueSize); // lookAheadParsing = true; // For subclasses Init(); } // Having multiple ctor's is a bit inconvenient. // Put all init routines here. protected void Init() { // Override this in subclasses. } // Make tokenizer re-usable through Reset(). // TBD: Need to verify this.... public void Reset(string str) { Reset(new StringReader(str)); } public void Reset(TextReader reader) { // This is essentially a copy of ctor. // TextReader cannot cannot be null. this.reader = reader; this.charQueue.Clear(); // Reset the "current state" vars. readerEOF = false; curToken = JsonToken.INVALID; nextToken = JsonToken.INVALID; // No need to call this... ??? // Init(); } // public bool isLookAheadParsing() // { // return lookAheadParsing; // } // TraceableJsonTokenizer interface. // These are primarily for debugging purposes... public string PeekCharsAsString(int length) { char[] c = PeekCharStream(length); if(c != null) { return new String(c); } else { return ""; // ???? } } public char[] PeekCharStream(int length) { char[] c = null; try { c = PeekChars(length); } catch (HoloJsonMiniException e) { System.Diagnostics.Debug.WriteLine("Failed to peek char stream: length = " + length, e); } return c; } public char[] PeekCharStream() { return PeekCharStream(HEAD_TRACE_LENGTH); } // TBD: // These methods really need to be synchronized. // ... /// @Override public bool HasMore() { if(JsonToken.IsTokenInvalid(nextToken)) { nextToken = PrepareNextToken(); } if (JsonToken.IsTokenInvalid(nextToken) || TokenPool.TOKEN_EOF.Equals(nextToken)) { return false; } else { return true; } } /// @Override public JsonToken Next() { if(JsonToken.IsTokenInvalid(nextToken)) { nextToken = PrepareNextToken(); } curToken = nextToken; nextToken = JsonToken.INVALID; return curToken; } /// @Override public JsonToken Peek() { if(JsonToken.IsTokenValid(nextToken)) { return nextToken; } nextToken = PrepareNextToken(); return nextToken; } // temporary // Does this save anything compared to Next();Peek(); ???? // (unless we can do prepareNextTwoTokens() .... ? ) // Remove the next token (and throw away), // and return the next token (without removing it). public JsonToken NextAndPeek() { if(JsonToken.IsTokenInvalid(nextToken)) { curToken = PrepareNextToken(); } else { curToken = nextToken; } nextToken = PrepareNextToken(); return nextToken; } // Note that this method is somewhat unusual in that it cannot be called arbitrarily. // This method changes the internal state by changing the charQueue. // This should be called by a certain select methods only!!! private JsonToken PrepareNextToken() { if(JsonToken.IsTokenValid(nextToken)) { // ??? return nextToken; } JsonToken token = JsonToken.INVALID; char ch; // ch has been peeked, but not popped. // ... // "Look ahead" version should be just a bit faster.... ch = GobbleUpSpaceLookAhead(); // ch = GobbleUpSpace(); // .... // Create a JsonToken and, // reset the curToken. switch(ch) { case (char) CharSymbol.COMMA: case (char) CharSymbol.COLON: case (char) CharSymbol.LSQUARE: case (char) CharSymbol.LCURLY: case (char) CharSymbol.RSQUARE: case (char) CharSymbol.RCURLY: token = TokenPool.GetSymbolToken(ch); // NextChar(); // Consume the current token. SkipCharNoCheck(); // Consume the current token. // nextToken = null; break; case (char) MarkerChar.NULL_START: case (char) MarkerChar.NULL_START_UPPER: token = DoNullLiteral(); break; case (char) MarkerChar.TRUE_START: case (char) MarkerChar.TRUE_START_UPPER: token = DoTrueLiteral(); break; case (char) MarkerChar.FALSE_START: case (char) MarkerChar.FALSE_START_UPPER: token = DoFalseLiteral(); break; case (char) CharSymbol.DQUOTE: token = DoString(); break; case (char) 0: // ??? token = TokenPool.TOKEN_EOF; // NextChar(); // Consume the current token. SkipCharNoCheck(); // Consume the current token. break; default: if(Symbols.IsStartingNumber(ch)) { // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>> ch = " + ch); token = DoNumber(); // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>> number token = " + token); } else { throw new HoloJsonMiniException("Invalid symbol encountered: ch = " + ch); } break; } return token; } private char GobbleUpSpace() { char c = (char) 0; try { c = PeekChar(); //while(c != 0 && char.isSpaceChar(c)) { // ??? -> this doesn't seem to work.... // while(c != 0 && char.IsWhitespace(c) ) { // ??? while(c != 0 && CharUtil.IsWhitespace(c) ) { // ??? // NextChar(); // gobble up space. // c = PeekChar(); c = SkipAndPeekChar(); } } catch(HoloJsonMiniException e) { // ???? System.Diagnostics.Debug.WriteLine("Failed to consume space.", e); c = (char) 0; } return c; } // Returns the next peeked character. // Return value of 0 means we have reached the end of the json string. // TBD: use "look ahead" implementation similar to ReadString() ???? // Note that this is effective only for "formatted" JSON with lots of consecutive spaces... private char GobbleUpSpaceLookAhead() { char c = (char) 0; try { c = PeekChar(); // if(char.IsWhitespace(c)) { if(CharUtil.IsWhitespace(c)) { // SkipCharNoCheck(); c = SkipAndPeekChar(); // Spaces tend appear together. // if(char.IsWhitespace(c)) { if(CharUtil.IsWhitespace(c)) { int chunkLength; CyclicCharArray charArray = PeekCharsInQueue(MAX_SPACE_LOOKAHEAD_SIZE); // if(charArray == null || (chunkLength = charArray.GetLength()) == 0) { // return c; // } chunkLength = charArray.Length; int chunkCounter = 0; int totalLookAheadLength = 0; c = charArray.GetChar(0); // while((chunkCounter < chunkLength - 1) && char.IsWhitespace(c) ) { while((chunkCounter < chunkLength - 1) && CharUtil.IsWhitespace(c) ) { ++chunkCounter; if(chunkCounter >= chunkLength - 1) { totalLookAheadLength += chunkCounter; chunkCounter = 0; // restart a loop. charArray = PeekCharsInQueue(totalLookAheadLength, MAX_SPACE_LOOKAHEAD_SIZE); if(charArray == null || (chunkLength = charArray.Length) == 0) { break; } } c = charArray.GetChar(chunkCounter); } totalLookAheadLength += chunkCounter; SkipChars(totalLookAheadLength); c = PeekChar(); } } } catch(HoloJsonMiniException e) { // ???? System.Diagnostics.Debug.WriteLine("Failed to consume space.", e); c = (char) 0; } return c; } private JsonToken DoNullLiteral() { JsonToken token = JsonToken.INVALID; int length = Literals.NULL_LENGTH; // char[] c = nextChars(length); CyclicCharArray c = NextCharsInQueue(length); if(LiteralUtil.IsNull(c)) { token = TokenPool.TOKEN_NULL; // nextToken = null; } else { // throw new JsonException("Unexpected string: " + Arrays.ToString(c), tailCharStream()); throw new HoloJsonMiniException("Unexpected string: "); } return token; } private JsonToken DoTrueLiteral() { JsonToken token = JsonToken.INVALID; int length = Literals.TRUE_LENGTH; // char[] c = nextChars(length); CyclicCharArray c = NextCharsInQueue(length); if(LiteralUtil.IsTrue(c)) { token = TokenPool.TOKEN_TRUE; // nextToken = null; } else { // throw new JsonException("Unexpected string: " + Arrays.ToString(c), tailCharStream()); throw new HoloJsonMiniException("Unexpected string: "); } return token; } private JsonToken DoFalseLiteral() { JsonToken token = JsonToken.INVALID; int length = Literals.FALSE_LENGTH; // char[] c = nextChars(length); CyclicCharArray c = NextCharsInQueue(length); if(LiteralUtil.IsFalse(c)) { token = TokenPool.TOKEN_FALSE; // nextToken = null; } else { // throw new JsonException("Unexpected string: " + Arrays.ToString(c), tailCharStream()); throw new HoloJsonMiniException("Unexpected string: "); } return token; } // Note that there is no "character". // char is a single letter string. private JsonToken DoString() { JsonToken token = JsonToken.INVALID; string value; // .... // value = ReadString(); // Note that this will fail if we encounter a looooong string. // See the comment below. We try at least once with ReadString() version... value = ReadStringWithLookAhead(); // .... token = TokenPool.Instance.GetToken(TokenType.STRING, value); // nextToken = null; return token; } private string ReadString() { // Note that we may have already "consumed" the beginning \" if we are calling this from ReadStringWithLookAhead()... // So, the following does not work.... // // char c = NextChar(); // char c = NextCharNoCheck(); // if(c == 0 || c != Symbols.DQUOTE) { // // This cannot happen. // throw new HoloJsonMiniException("Expecting String. Invalid token encountered: c = " + c); // } StringBuilder sb = new StringBuilder(); char c = PeekChar(); if(c == 0) { // This cannot happen. throw new HoloJsonMiniException("Expecting String. Invalid token encountered: c = " + c); } else if(c == (char) CharSymbol.DQUOTE) { // consume the leading \". // c = NextCharNoCheck(); SkipCharNoCheck(); // sb.Append(c); // No append: Remove the leading \". } else { // We are already at the beginning of the string. // proceed. } bool escaped = false; char d = PeekChar(); while(d != 0 && (escaped == true || d != (char) CharSymbol.DQUOTE )) { // d = NextChar(); d = NextCharNoCheck(); if(escaped == false && d == (char) CharSymbol.BACKSLASH) { escaped = true; // skip } else { if(escaped == true) { if(d == (char) CharSymbol.UNICODE_PREFIX) { // char[] hex = nextChars(4); CyclicCharArray hex = NextCharsInQueue(4); // TBD: validate ?? try { // ???? // sb.Append((char) CharSymbol.BACKSLASH).Append(d).Append(hex); char u = UnicodeUtil.GetUnicodeChar(hex); if(u != 0) { sb.Append(u); } else { // ???? } } catch(Exception e) { throw new HoloJsonMiniException("Invalid unicode char: hex = " + hex.ToString(), e); } } else { if(Symbols.IsEscapableChar(d)) { // TBD: // Newline cannot be allowed within a string.... // .... char e = Symbols.GetEscapedChar(d); if(e != 0) { sb.Append(e); } else { // This cannot happen. } } else { // error? throw new HoloJsonMiniException("Invalid escaped char: d = \\" + d); } } // toggle the flag. escaped = false; } else { // TBD: // Exclude control characters ??? // ... sb.Append(d); } } d = PeekChar(); } if(d == (char) CharSymbol.DQUOTE) { // d = NextChar(); SkipCharNoCheck(); // sb.Append(d); // No append: Remove the trailing \". } else { // end of the json string. // error??? // return null; } return sb.ToString(); } // Note: // This will cause parse failing // if the longest string in JSON is longer than (CHARQUEUE_SIZE - READER_BUFF_SIZE) // because Forward() will fail. // TBD: // There might be bugs when dealing with short strings, or \\u escaped unicodes at the end of a json string // ... private string ReadStringWithLookAhead() { // char c = NextChar(); char c = NextCharNoCheck(); if(c == 0 || c != (char) CharSymbol.DQUOTE) { // This cannot happen. throw new HoloJsonMiniException("Expecting String. Invalid token encountered: c = " + c); } StringBuilder sb = new StringBuilder(); // sb.Append(c); // No append: Remove the leading \". bool escaped = false; int chunkLength; CyclicCharArray charArray = PeekCharsInQueue(MAX_STRING_LOOKAHEAD_SIZE); if(charArray == null || (chunkLength = charArray.Length) == 0) { // ???? throw new HoloJsonMiniException("string token terminated unexpectedly."); } bool noMoreCharsInQueue = false; if(chunkLength < MAX_STRING_LOOKAHEAD_SIZE) { noMoreCharsInQueue = true; } bool needMore = false; int chunkCounter = 0; int totalLookAheadLength = 0; char d = charArray.GetChar(0); // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>> d = " + d); // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>> chunkLength = " + chunkLength); while((chunkCounter < chunkLength - 1) && // 6 for "\\uxxxx". d != 0 && (escaped == true || d != (char) CharSymbol.DQUOTE )) { // d = charArray.GetChar(++chunkCounter); ++chunkCounter; // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>> d = " + d); if(escaped == false && d == (char) CharSymbol.BACKSLASH) { escaped = true; // skip } else { if(escaped == true) { if(d == (char) CharSymbol.UNICODE_PREFIX) { if(chunkCounter < chunkLength - 4) { char[] hex = charArray.GetChars(chunkCounter, 4); chunkCounter += 4; try { // ???? // sb.Append((char) CharSymbol.BACKSLASH).Append(d).Append(hex); char u = UnicodeUtil.GetUnicodeChar(hex); if(u != 0) { sb.Append(u); } else { // ???? } } catch(Exception e) { throw new HoloJsonMiniException("Invalid unicode char: hex = " + String.Join<char>(",", hex), e); } } else { if(noMoreCharsInQueue == false) { needMore = true; chunkCounter -= 2; // Reset the counter backward for "\\u". } else { // error throw new HoloJsonMiniException("Invalid unicode char."); } } } else { if(Symbols.IsEscapableChar(d)) { // TBD: // Newline cannot be allowed within a string.... // .... char e = Symbols.GetEscapedChar(d); if(e != 0) { sb.Append(e); } else { // This cannot happen. } } else { // error? throw new HoloJsonMiniException("Invalid escaped char: d = \\" + d); } } // toggle the flag. escaped = false; } else { // TBD: // Exclude control characters ??? // ... sb.Append(d); } } if((noMoreCharsInQueue == false) && (needMore || chunkCounter >= chunkLength - 1)) { totalLookAheadLength += chunkCounter; chunkCounter = 0; // restart a loop. needMore = false; // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>>>>>> AddAll() totalLookAheadLength = " + totalLookAheadLength); try { charArray = PeekCharsInQueue(totalLookAheadLength, MAX_STRING_LOOKAHEAD_SIZE); } catch(HoloJsonMiniException e) { // Not sure if this makes sense.... // but since this error might have been due to the fact that we have encountered a looooong string, // Try again??? // ... // Note that this applies one, this particular, string only. // Next time when we encounter a long string, // this may be invoked again.... // .... // We should be careful not to get into the infinite loop.... System.Diagnostics.Debug.WriteLine("string token might have been too long. Trying again with no look-ahead ReadString()."); // Reset the buffer (Peek() status) ????, and call the non "look ahead" version... return ReadString(); // Is this starting from the beginning??? // ... } if(charArray == null || (chunkLength = charArray.Length) == 0) { // ???? throw new HoloJsonMiniException("string token terminated unexpectedly."); } if(chunkLength < MAX_STRING_LOOKAHEAD_SIZE) { noMoreCharsInQueue = true; } } d = charArray.GetChar(chunkCounter); } totalLookAheadLength += chunkCounter; SkipChars(totalLookAheadLength); d = PeekChar(); if(d == (char) CharSymbol.DQUOTE) { // d = NextChar(); SkipCharNoCheck(); // sb.Append(d); // No append: Remove the trailing \". } else { // end of the json string. // error??? // return null; } return sb.ToString(); } private JsonToken DoNumber() { JsonToken token = JsonToken.INVALID; var value = ReadNumber(); token = TokenPool.Instance.GetToken(TokenType.NUMBER, value); // nextToken = null; return token; } // Need a better way to do this .... private Number ReadNumber() { // char c = NextChar(); char c = NextCharNoCheck(); if(! Symbols.IsStartingNumber(c)) { throw new HoloJsonMiniException("Expecting a number. Invalid symbol encountered: c = " + c); } if(c == (char) CharSymbol.PLUS) { // remove the leading +. c = NextChar(); } var sb = new StringBuilder(); if(c == (char) CharSymbol.MINUS) { sb.Append(c); c = NextChar(); } bool periodRead = false; if(c == (char) CharSymbol.PERIOD) { periodRead = true; sb.Append("0."); } else { // Could be a number, nothing else. if(c == '0') { char c2 = PeekChar(); // This does not work because the number happens to be just zero ("0"). // if(c2 != (char) CharSymbol.PERIOD) { // throw new JsonException("Invalid number: c = " + sb.ToString() + c + c2, tailCharStream()); // } // This should be better. // zero followed by other number is not allowed. if(Char.IsDigit(c2)) { throw new HoloJsonMiniException("Invalid number: c = " + sb.ToString() + c + c2); } sb.Append(c); if (c2 == (char) CharSymbol.PERIOD) { periodRead = true; // sb.Append(NextChar()); sb.Append(NextCharNoCheck()); } } else { sb.Append(c); } } bool exponentRead = false; char d = PeekChar(); while(d != 0 && (Char.IsDigit(d) || (periodRead == false && d == (char) CharSymbol.PERIOD) || (exponentRead == false && Symbols.IsExponentChar(d)) )) { // sb.Append(NextChar()); sb.Append(NextCharNoCheck()); if(d == (char) CharSymbol.PERIOD) { periodRead = true; } if(Symbols.IsExponentChar(d)) { char d2 = PeekChar(); if(d2 == (char) CharSymbol.PLUS || d2 == (char) CharSymbol.MINUS || Char.IsDigit(d2)) { // sb.Append(NextChar()); sb.Append(NextCharNoCheck()); } else { throw new HoloJsonMiniException("Invalid number: " + sb.ToString() + d2); } exponentRead = true; } d = PeekChar(); } if(d == 0) { // end of the json string. // ???? // throw new JsonException("Invalid number: " + sb.ToString(), tailCharStream()); } else { // sb.Append(NextChar()); } string str = sb.ToString(); Number number = Number.Invalid; // ???? try { //if(str.Contains(".")) { // double x = Convert.ToDouble(str); // number = new Number(x); //} else { // long y = Convert.ToInt64(str); // number = new Number(y); //} number = str.ToNumber(); } catch(Exception e) { // ??? throw new HoloJsonMiniException("Invalid number encountered: str = " + str, e); } return number; } // because we called PeekChar() already, // no need for check error conditions. private char NextCharNoCheck() { char ch = charQueue.Poll(); return ch; } private void SkipCharNoCheck() { charQueue.Skip(); } private char NextChar() { if(charQueue.IsEmpty) { if(readerEOF == false) { try { Forward(); } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } if(charQueue.IsEmpty) { return (char) 0; // ??? // throw new JsonException("There is no character in the buffer."); } char ch = charQueue.Poll(); return ch; } private char[] NextChars(int length) { // assert length > 0 if(charQueue.Size < length) { if(readerEOF == false) { try { Forward(); } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } char[] c = null; if(charQueue.Size < length) { c = charQueue.Poll(charQueue.Size); // throw new JsonException("There is not enough characters in the buffer. length = " + length); } c = charQueue.Poll(length); return c; } private CyclicCharArray NextCharsInQueue(int length) { // assert length > 0 if(charQueue.Size < length) { if(readerEOF == false) { try { Forward(); } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } CyclicCharArray charArray = null; if(charQueue.Size < length) { charArray = charQueue.PollBuffer(charQueue.Size); // throw new JsonException("There is not enough characters in the buffer. length = " + length); } charArray = charQueue.PollBuffer(length); return charArray; } private void SkipChars(int length) { // assert length > 0 if(charQueue.Size < length) { if(readerEOF == false) { try { Forward(); } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } charQueue.Skip(length); } // Note that PeekChar() and PeekChars() are "idempotent". private char PeekChar() { if(charQueue.IsEmpty) { if(readerEOF == false) { try { Forward(); } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } if(charQueue.IsEmpty) { return (char) 0; // throw new JsonException("There is no character in the buffer."); } return charQueue.Peek(); } private char[] PeekChars(int length) { // assert length > 0 if(charQueue.Size < length) { if(readerEOF == false) { try { Forward(); } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } if(charQueue.Size < length) { return charQueue.Peek(charQueue.Size); // throw new JsonException("There is not enough characters in the buffer. length = " + length); } return charQueue.Peek(length); } private CyclicCharArray PeekCharsInQueue(int length) { // assert length > 0 if(charQueue.Size < length) { if(readerEOF == false) { try { Forward(); } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } if(charQueue.Size < length) { return charQueue.PeekBuffer(charQueue.Size); // throw new JsonException("There is not enough characters in the buffer. length = " + length); } return charQueue.PeekBuffer(length); } private CyclicCharArray PeekCharsInQueue(int offset, int length) { // assert length > 0 if(charQueue.Size < offset + length) { if(readerEOF == false) { try { Forward(); } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } if(charQueue.Size < offset + length) { return charQueue.PeekBuffer(offset, charQueue.Size - offset); // throw new JsonException("There is not enough characters in the buffer. length = " + length); } return charQueue.PeekBuffer(offset, length); } // Poll next char (and gobble up), // and return the next char (without removing it) private char SkipAndPeekChar() { int qSize = charQueue.Size; if(qSize < 2) { if(readerEOF == false) { try { Forward(); qSize = charQueue.Size; } catch (IOException e) { // ??? throw new HoloJsonMiniException("Failed to forward character stream.", e); } } } if(qSize > 0) { charQueue.Skip(); if(qSize > 1) { return charQueue.Peek(); } } return (char) 0; // throw new JsonException("There is no character in the buffer."); } // Read some more bytes from the reader. private readonly char[] buff = new char[READER_BUFF_SIZE]; private async void Forward() { if(readerEOF == false) { int cnt = 0; try { // This throws OOB excpetion at the end.... // cnt = reader.read(buff, curTextReaderIndex, READER_BUFF_SIZE); cnt = await reader.ReadAsync(buff, 0, READER_BUFF_SIZE); } catch(ArgumentOutOfRangeException e) { // ??? // Why does this happen? Does it happen for StringReader only??? // Does read(,,) ever return -1 in the case of StringReader ??? System.Diagnostics.Debug.WriteLine("Looks like we have reached the end of the reader.", e); } if(cnt == -1 || cnt == 0) { readerEOF = true; } else { bool suc = charQueue.AddAll(buff, cnt); if(suc) { curTextReaderIndex += cnt; } else { // ??? throw new HoloJsonMiniException("Unexpected internal error occurred. chars were not added to CharQueue: cnt = " + cnt); } } } } } }
#pragma warning disable 162 using UnityEngine; using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; public enum RuleResult { Done, Working } namespace Casanova.Prelude { public class Tuple<T,E> { public T Item1 { get; set;} public E Item2 { get; set;} public Tuple(T item1, E item2) { Item1 = item1; Item2 = item2; } } public static class MyExtensions { //public T this[List<T> list] //{ // get { return list.ElementAt(0); } //} public static T Head<T>(this List<T> list) { return list.ElementAt(0); } public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); } public static int Length<T>(this List<T> list) { return list.Count; } public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; } } public class Cons<T> : IEnumerable<T> { public class Enumerator : IEnumerator<T> { public Enumerator(Cons<T> parent) { firstEnumerated = 0; this.parent = parent; tailEnumerator = parent.tail.GetEnumerator(); } byte firstEnumerated; Cons<T> parent; IEnumerator<T> tailEnumerator; public T Current { get { if (firstEnumerated == 0) return default(T); if (firstEnumerated == 1) return parent.head; else return tailEnumerator.Current; } } object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } } public bool MoveNext() { if (firstEnumerated == 0) { if (parent.head == null) return false; firstEnumerated++; return true; } if (firstEnumerated == 1) firstEnumerated++; return tailEnumerator.MoveNext(); } public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); } public void Dispose() { } } T head; IEnumerable<T> tail; public Cons(T head, IEnumerable<T> tail) { this.head = head; this.tail = tail; } public IEnumerator<T> GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } } public class Empty<T> : IEnumerable<T> { public Empty() { } public class Enumerator : IEnumerator<T> { public T Current { get { throw new Exception("Empty sequence has no elements"); } } object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } } public bool MoveNext() { return false; } public void Reset() { } public void Dispose() { } } public IEnumerator<T> GetEnumerator() { return new Enumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(); } } public abstract class Option<T> : IComparable, IEquatable<Option<T>> { public bool IsSome; public bool IsNone { get { return !IsSome; } } protected abstract Just<T> Some { get; } public U Match<U>(Func<T,U> f, Func<U> g) { if (this.IsSome) return f(this.Some.Value); else return g(); } public bool Equals(Option<T> b) { return this.Match( x => b.Match( y => x.Equals(y), () => false), () => b.Match( y => false, () => true)); } public override bool Equals(System.Object other) { if (other == null) return false; if (other is Option<T>) { var other1 = other as Option<T>; return this.Equals(other1); } return false; } public override int GetHashCode() { return this.GetHashCode(); } public static bool operator ==(Option<T> a, Option<T> b) { if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b); return a.Equals(b); } public static bool operator !=(Option<T> a, Option<T> b) { if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b); return !(a.Equals(b)); } public int CompareTo(object obj) { if (obj == null) return 1; if (obj is Option<T>) { var obj1 = obj as Option<T>; if (this.Equals(obj1)) return 0; } return -1; } abstract public T Value { get; } public override string ToString() { return "Option<" + typeof(T).ToString() + ">"; } } public class Just<T> : Option<T> { T elem; public Just(T elem) { this.elem = elem; this.IsSome = true; } protected override Just<T> Some { get { return this; } } public override T Value { get { return elem; } } } public class Nothing<T> : Option<T> { public Nothing() { this.IsSome = false; } protected override Just<T> Some { get { return null; } } public override T Value { get { throw new Exception("Cant get a value from a None object"); } } } public class Utils { public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e) { if (c()) return t(); else return e(); } } } public class FastStack { public int[] Elements; public int Top; public FastStack(int elems) { Top = 0; Elements = new int[elems]; } public void Clear() { Top = 0; } public void Push(int x) { Elements[Top++] = x; } } public class RuleTable { public RuleTable(int elems) { ActiveIndices = new FastStack(elems); SupportStack = new FastStack(elems); ActiveSlots = new bool[elems]; } public FastStack ActiveIndices; public FastStack SupportStack; public bool[] ActiveSlots; public void Add(int i) { if (!ActiveSlots[i]) { ActiveSlots[i] = true; ActiveIndices.Push(i); } } } public class World : MonoBehaviour{ void Update () { Update(Time.deltaTime, this); } public void Start() { Cubes = ( Enumerable.Empty<Cube>()).ToList<Cube>(); } public List<Cube> Cubes; public void Update(float dt, World world) { for(int x0 = 0; x0 < Cubes.Count; x0++) { Cubes[x0].Update(dt, world); } this.Rule0(dt, world); this.Rule1(dt, world); } public void Rule0(float dt, World world) { Cubes = ( (Cubes).Select(__ContextSymbol1 => new { ___c00 = __ContextSymbol1 }) .Where(__ContextSymbol2 => ((__ContextSymbol2.___c00.UnityCube.Destroyed) == (false))) .Select(__ContextSymbol3 => __ContextSymbol3.___c00) .ToList<Cube>()).ToList<Cube>(); } int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: if(!(UnityEngine.Input.GetKeyDown(KeyCode.Space))) { s1 = -1; return; }else { goto case 0; } case 0: Cubes = new Cons<Cube>(new Cube(), (Cubes)).ToList<Cube>(); s1 = -1; return; default: return;}} } public class Cube{ public int ID; public Cube() { Factor = 0f; UnityCube = UnityCube.Instantiate(); } public UnityCube UnityCube; public UnityEngine.Color Color{ set{UnityCube.Color = value; } } public System.Single Scale{ get { return UnityCube.Scale; } set{UnityCube.Scale = value; } } public System.Boolean Destroyed{ get { return UnityCube.Destroyed; } set{UnityCube.Destroyed = value; } } public System.Boolean useGUILayout{ get { return UnityCube.useGUILayout; } set{UnityCube.useGUILayout = value; } } public System.Boolean enabled{ get { return UnityCube.enabled; } set{UnityCube.enabled = value; } } public UnityEngine.Transform transform{ get { return UnityCube.transform; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityCube.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityCube.rigidbody2D; } } public UnityEngine.Camera camera{ get { return UnityCube.camera; } } public UnityEngine.Light light{ get { return UnityCube.light; } } public UnityEngine.Animation animation{ get { return UnityCube.animation; } } public UnityEngine.ConstantForce constantForce{ get { return UnityCube.constantForce; } } public UnityEngine.Renderer renderer{ get { return UnityCube.renderer; } } public UnityEngine.AudioSource audio{ get { return UnityCube.audio; } } public UnityEngine.GUIText guiText{ get { return UnityCube.guiText; } } public UnityEngine.NetworkView networkView{ get { return UnityCube.networkView; } } public UnityEngine.GUITexture guiTexture{ get { return UnityCube.guiTexture; } } public UnityEngine.Collider collider{ get { return UnityCube.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityCube.collider2D; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityCube.hingeJoint; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityCube.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityCube.particleSystem; } } public UnityEngine.GameObject gameObject{ get { return UnityCube.gameObject; } } public System.String tag{ get { return UnityCube.tag; } set{UnityCube.tag = value; } } public System.String name{ get { return UnityCube.name; } set{UnityCube.name = value; } } public UnityEngine.HideFlags hideFlags{ get { return UnityCube.hideFlags; } set{UnityCube.hideFlags = value; } } public System.Single Factor; public void Update(float dt, World world) { this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); } public void Rule0(float dt, World world) { UnityCube.Color = Color.Lerp(Color.white,Color.blue,Factor); } int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: if(!(((((Factor) > (2f))) || (((Factor) == (2f)))))) { s1 = -1; return; }else { goto case 0; } case 0: UnityCube.Destroyed = true; s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: Factor = ((Factor) + (0.02f)); s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: UnityCube.Scale = ((1f) - (((Factor) / (2f)))); s3 = -1; return; default: return;}} }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Linky.Sandbox.Areas.HelpPage.ModelDescriptions; using Linky.Sandbox.Areas.HelpPage.Models; namespace Linky.Sandbox.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.OperationalInsights; using Microsoft.Azure.Management.OperationalInsights.Models; namespace Microsoft.Azure.Management.OperationalInsights { /// <summary> /// .Net client wrapper for the REST API for Azure Operational Insights /// </summary> public static partial class SearchOperationsExtensions { /// <summary> /// Creates or updates a saved search for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='savedSearchId'> /// Required. The id of the saved search. /// </param> /// <param name='parameters'> /// Required. The parameters required to save a search. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse CreateOrUpdateSavedSearch(this ISearchOperations operations, string resourceGroupName, string workspaceName, string savedSearchId, SearchCreateOrUpdateSavedSearchParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ISearchOperations)s).CreateOrUpdateSavedSearchAsync(resourceGroupName, workspaceName, savedSearchId, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a saved search for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='savedSearchId'> /// Required. The id of the saved search. /// </param> /// <param name='parameters'> /// Required. The parameters required to save a search. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CreateOrUpdateSavedSearchAsync(this ISearchOperations operations, string resourceGroupName, string workspaceName, string savedSearchId, SearchCreateOrUpdateSavedSearchParameters parameters) { return operations.CreateOrUpdateSavedSearchAsync(resourceGroupName, workspaceName, savedSearchId, parameters, CancellationToken.None); } /// <summary> /// Deletes the specified saved search in a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='savedSearchId'> /// Required. The id of the saved search. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse DeleteSavedSearch(this ISearchOperations operations, string resourceGroupName, string workspaceName, string savedSearchId) { return Task.Factory.StartNew((object s) => { return ((ISearchOperations)s).DeleteSavedSearchAsync(resourceGroupName, workspaceName, savedSearchId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified saved search in a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='savedSearchId'> /// Required. The id of the saved search. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteSavedSearchAsync(this ISearchOperations operations, string resourceGroupName, string workspaceName, string savedSearchId) { return operations.DeleteSavedSearchAsync(resourceGroupName, workspaceName, savedSearchId, CancellationToken.None); } /// <summary> /// Gets the specified saved search for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='savedSearchId'> /// Required. The id of the saved search. /// </param> /// <returns> /// Value object for saved search results. /// </returns> public static SearchGetSavedSearchResponse GetSavedSearch(this ISearchOperations operations, string resourceGroupName, string workspaceName, string savedSearchId) { return Task.Factory.StartNew((object s) => { return ((ISearchOperations)s).GetSavedSearchAsync(resourceGroupName, workspaceName, savedSearchId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the specified saved search for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='savedSearchId'> /// Required. The id of the saved search. /// </param> /// <returns> /// Value object for saved search results. /// </returns> public static Task<SearchGetSavedSearchResponse> GetSavedSearchAsync(this ISearchOperations operations, string resourceGroupName, string workspaceName, string savedSearchId) { return operations.GetSavedSearchAsync(resourceGroupName, workspaceName, savedSearchId, CancellationToken.None); } /// <summary> /// Gets the results from a saved search for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='savedSearchId'> /// Required. The id of the saved search. /// </param> /// <returns> /// The get search result operation response. /// </returns> public static SearchGetSearchResultsResponse GetSavedSearchResults(this ISearchOperations operations, string resourceGroupName, string workspaceName, string savedSearchId) { return Task.Factory.StartNew((object s) => { return ((ISearchOperations)s).GetSavedSearchResultsAsync(resourceGroupName, workspaceName, savedSearchId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the results from a saved search for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='savedSearchId'> /// Required. The id of the saved search. /// </param> /// <returns> /// The get search result operation response. /// </returns> public static Task<SearchGetSearchResultsResponse> GetSavedSearchResultsAsync(this ISearchOperations operations, string resourceGroupName, string workspaceName, string savedSearchId) { return operations.GetSavedSearchResultsAsync(resourceGroupName, workspaceName, savedSearchId, CancellationToken.None); } /// <summary> /// Gets the schema for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <returns> /// The get schema operation response. /// </returns> public static SearchGetSchemaResponse GetSchema(this ISearchOperations operations, string resourceGroupName, string workspaceName) { return Task.Factory.StartNew((object s) => { return ((ISearchOperations)s).GetSchemaAsync(resourceGroupName, workspaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the schema for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <returns> /// The get schema operation response. /// </returns> public static Task<SearchGetSchemaResponse> GetSchemaAsync(this ISearchOperations operations, string resourceGroupName, string workspaceName) { return operations.GetSchemaAsync(resourceGroupName, workspaceName, CancellationToken.None); } /// <summary> /// Gets the search results for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to execute a search query. /// </param> /// <returns> /// The get search result operation response. /// </returns> public static SearchGetSearchResultsResponse GetSearchResults(this ISearchOperations operations, string resourceGroupName, string workspaceName, SearchGetSearchResultsParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ISearchOperations)s).GetSearchResultsAsync(resourceGroupName, workspaceName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the search results for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to execute a search query. /// </param> /// <returns> /// The get search result operation response. /// </returns> public static Task<SearchGetSearchResultsResponse> GetSearchResultsAsync(this ISearchOperations operations, string resourceGroupName, string workspaceName, SearchGetSearchResultsParameters parameters) { return operations.GetSearchResultsAsync(resourceGroupName, workspaceName, parameters, CancellationToken.None); } /// <summary> /// Gets the saved searches for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <returns> /// The saved search operation response. /// </returns> public static SearchListSavedSearchResponse ListSavedSearches(this ISearchOperations operations, string resourceGroupName, string workspaceName) { return Task.Factory.StartNew((object s) => { return ((ISearchOperations)s).ListSavedSearchesAsync(resourceGroupName, workspaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the saved searches for a given workspace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <returns> /// The saved search operation response. /// </returns> public static Task<SearchListSavedSearchResponse> ListSavedSearchesAsync(this ISearchOperations operations, string resourceGroupName, string workspaceName) { return operations.ListSavedSearchesAsync(resourceGroupName, workspaceName, CancellationToken.None); } /// <summary> /// Gets updated search results for a given search query. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='id'> /// Required. The id of the search that will have results updated. /// </param> /// <returns> /// The get search result operation response. /// </returns> public static SearchGetSearchResultsResponse UpdateSearchResults(this ISearchOperations operations, string resourceGroupName, string workspaceName, string id) { return Task.Factory.StartNew((object s) => { return ((ISearchOperations)s).UpdateSearchResultsAsync(resourceGroupName, workspaceName, id); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets updated search results for a given search query. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.OperationalInsights.ISearchOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the workspace. /// </param> /// <param name='workspaceName'> /// Required. A unique workspace instance name. /// </param> /// <param name='id'> /// Required. The id of the search that will have results updated. /// </param> /// <returns> /// The get search result operation response. /// </returns> public static Task<SearchGetSearchResultsResponse> UpdateSearchResultsAsync(this ISearchOperations operations, string resourceGroupName, string workspaceName, string id) { return operations.UpdateSearchResultsAsync(resourceGroupName, workspaceName, id, CancellationToken.None); } } }
// // Will Strohl (will.strohl@gmail.com) // http://www.willstrohl.com // //Copyright (c) 2009-2016, Will Strohl //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 Will Strohl, Content Injection, 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 DotNetNuke.Services.Exceptions; using System; using DotNetNuke.Entities.Modules; using DotNetNuke.UI.Skins.Controls; using System.Web.UI; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.UI.Skins; using DotNetNuke.Web.Client; using DotNetNuke.Web.Client.ClientResourceManagement; using DotNetNuke.Web.Client.Providers; using WillStrohl.Modules.Injection.Components; using WillStrohl.Modules.Injection.Entities; namespace WillStrohl.Modules.Injection { public partial class ViewInjection : WNSPortalModuleBase, IActionable { #region Private Members private string p_Header = string.Empty; private string p_Footer = string.Empty; private string p_EditInjectionUrl = string.Empty; #endregion #region Properties private string HeaderInjection { get { return p_Header; } } private string FooterInjection { get { return p_Footer; } } private string EditInjectionUrl { get { if (!string.IsNullOrEmpty(p_EditInjectionUrl)) { return p_EditInjectionUrl; } p_EditInjectionUrl = EditUrl(string.Empty, string.Empty, "Edit"); return p_EditInjectionUrl; } } #endregion #region Event Handlers protected void Page_Load(object sender, EventArgs e) { try { if (CurrentUserCanEdit) { // If IsEditable, then the visitor has edit permissions to the module, is // currently logged in, and the portal is in edit mode. Skin.AddModuleMessage(this, GetLocalizedString("InjectionInfo.Text"), ModuleMessage.ModuleMessageType.BlueInfo); } else { // hide the module container (and the rest of the module as well) ContainerControl.Visible = false; } // inject any strings insto the page ExecutePageInjection(); } catch (Exception exc) { // Module failed to load Exceptions.ProcessModuleLoadException(this, exc, IsEditable); } } public void InjectIntoFooter(object sender, EventArgs e) { if (!string.IsNullOrEmpty(FooterInjection)) { Page.Form.Controls.Add(new LiteralControl(FooterInjection)); } } #endregion #region Private Helper Methods private void ExecutePageInjection() { var ctlModule = new InjectionController(); var collInj = new InjectionInfoCollection(); collInj = ctlModule.GetActiveInjectionContents(ModuleId); if (collInj.Count <= 0) return; p_Header = string.Format("<!-- {0} -->", GetLocalizedString("HeaderHeader")); p_Footer = string.Format("<!-- {0} -->", GetLocalizedString("FooterHeader")); foreach (var injection in collInj) { var injectionType = InjectionController.GetInjectionType(injection); var priority = InjectionController.GetCrmPriority(injection); var provider = InjectionController.GetCrmProvider(injection); switch (injectionType) { case InjectionType.CSS: RegisterStyleSheet(injection.InjectContent, priority, provider); break; case InjectionType.JavaScript: RegisterScript(injection.InjectContent, priority, provider); break; case InjectionType.HtmlBottom: p_Footer = string.Concat(p_Footer, Server.HtmlDecode(injection.InjectContent)); break; case InjectionType.HtmlTop: p_Header = string.Concat(p_Header, Server.HtmlDecode(injection.InjectContent)); break; } } p_Header = string.Concat(p_Header, string.Format("<!-- {0} -->", GetLocalizedString("HeaderFooter"))); p_Footer = string.Concat(p_Footer, string.Format("<!-- {0} -->", GetLocalizedString("FooterFooter"))); // add the injection content to the header if (!string.IsNullOrEmpty(HeaderInjection)) { Parent.Page.Header.Controls.Add(new LiteralControl(HeaderInjection)); } // add the injection content to the footer if (!string.IsNullOrEmpty(FooterInjection)) { Page.LoadComplete += new EventHandler(InjectIntoFooter); } } private void RegisterStyleSheet(string path, int priority, string provider) { if (priority == Null.NullInteger) { priority = (int)FileOrder.Css.DefaultPriority; } ClientResourceManager.RegisterStyleSheet(this.Page, path, priority, provider); } private void RegisterScript(string path, int priority, string provider) { if (priority == Null.NullInteger) { priority = (int)FileOrder.Js.DefaultPriority; } ClientResourceManager.RegisterScript(this.Page, path, priority, provider); } #endregion #region IActionable Implementation public ModuleActionCollection ModuleActions { get { var Actions = new ModuleActionCollection(); Actions.Add(GetNextActionID(), GetLocalizedString("EditInjection.MenuItem.Title"), string.Empty, string.Empty, string.Empty, EditInjectionUrl, false, DotNetNuke.Security.SecurityAccessLevel.Edit, true, false); return Actions; } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace AcadBlog.WebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Text; namespace Jovian.Communication { [Serializable] // c2s public class packet_UserLogin { public string username; } [Serializable] // c2s public class packet_UserPing { }; [Serializable] // c2s, s2c public class packet_UserMessage { public string from; public string msg; public packet_UserMessage(string f, string m) { from = f; msg = m; } }; [Serializable] // c2s public class packet_Message { public string msg; public packet_Message(string m) { msg = m; } }; [Serializable] // c2s public class packet_CheckOut { public string key; public packet_CheckOut(string k) { key = k; } } [Serializable] // s2c (Successful checkout) public class packet_Deliver { public string key; public string xml; public packet_Deliver(string k, string x) { key = k; xml = x; } } [Serializable] // c2s public class packet_NewApplication { public string name; public packet_NewApplication(string n) { name = n; } } [Serializable] // c2s public class packet_Save { public string key; public string xml; public bool release; public bool create; public packet_Save(string k, string x, bool rel) { key = k; xml = x; release = rel; create = false; } public packet_Save makeCreate() { create = true; return this; } } [Serializable] // s2c public class packet_RegistryPush { public string key; public packet_RegistryPush(string k) { key = k; } } [Serializable] // c2s public class packet_RegistryDelete { public string key; public packet_RegistryDelete(string k) { key = k; } } [Serializable] // s2c public class packet_RegistryDeleteApp { public string key; public packet_RegistryDeleteApp(string k) { key = k; } } [Serializable] // s2c, c2s public class packet_RegistryRename { public string keyFrom; public string keyTo; public packet_RegistryRename(string kf, string kt) { keyFrom = kf; keyTo = kt; } } [Serializable] // c2s public class packet_Complie { public bool Optimize; public packet_Complie(bool opt) { Optimize = opt; } } [Serializable] // c2s public class packet_Dirty { public packet_Dirty() { } } [Serializable] // c2s public class packet_Search { public string App; public string Param; public packet_Search(string a, string p) { App = a; Param = p; } } [Serializable] // c2s public class packet_GetCSS { public string app; public packet_GetCSS(string a) { app = a; } } [Serializable] // s2c public class packet_DeliverCSS { public string app; public string css; public string pcss; public packet_DeliverCSS(string a, string c, string pc) { app = a; css = c; pcss = pc; } } [Serializable] // <-> public class packet_ImageTransit { public string App; public string Filename; public System.Drawing.Bitmap bmp; public packet_ImageTransit(string a, string f, string b) { App = a; Filename = f; System.Drawing.Bitmap bm = new System.Drawing.Bitmap(b); bmp = new System.Drawing.Bitmap(bm); bm.Dispose(); } } [Serializable] // c->s public class packet_ImageCheck { public string App; public string Filename; public packet_ImageCheck(string a, string f) { App = a; Filename = f; } } [Serializable] // s->c public class packet_ImageInformation { public string App; public string Filename; public int Width; public int Height; //public System.Drawing.Bitmap bmp; public packet_ImageInformation(string a, string f, int w, int h) { App = a; Filename = f; Width = w; Height = h; } } [Serializable] // s->c public class packet_InitPackage { public packet_InitPackage() { } } [Serializable] // s->c public class packet_ExportedApp { public string App; public string XML; } [Serializable] // s->c public class packet_ExportAppRequest { public string App; public packet_ExportAppRequest(string a) { App = a; } } [Serializable] // s->c public class packet_ImportApp { public string App; public string XML; public packet_ImportApp(string a, string f) { App = a; XML = f; } } [Serializable] // s->c public class packet_DumpReq { public packet_DumpReq() { } } [Serializable] // s->c public class packet_LayerWiz { public string App; public string Group; public string Commands; public packet_LayerWiz(string a, string g, string c) { App = a; Group = g; Commands = c; } } [Serializable] // s->c public class packet_BusinessWiz { public string App; public string Name; public string Group; public string Commands; public packet_BusinessWiz(string a,string n,string g, string c) { Name = n; App = a; Group = g; Commands = c; } } }
/* * 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. */ //#define SPAM using System; using System.Collections.Generic; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; using OpenMetaverse; using OpenMetaverse.StructuredData; using System.Drawing; using System.Drawing.Imaging; using System.IO.Compression; using PrimMesher; using log4net; using Nini.Config; using System.Reflection; using System.IO; namespace OpenSim.Region.Physics.Meshing { public class MeshmerizerPlugin : IMeshingPlugin { public MeshmerizerPlugin() { } public string GetName() { return "Meshmerizer"; } public IMesher GetMesher(IConfigSource config) { return new Meshmerizer(config); } } public class Meshmerizer : IMesher { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[MESH]"; // Setting baseDir to a path will enable the dumping of raw files // raw files can be imported by blender so a visual inspection of the results can be done #if SPAM const string baseDir = "rawFiles"; #else private const string baseDir = null; //"rawFiles"; #endif // If 'true', lots of DEBUG logging of asset parsing details private bool debugDetail = false; private bool cacheSculptMaps = true; private string decodedSculptMapPath = null; private bool useMeshiesPhysicsMesh = false; private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh private List<List<Vector3>> mConvexHulls = null; private List<Vector3> mBoundingHull = null; // Mesh cache. Static so it can be shared across instances of this class private static Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>(); public Meshmerizer(IConfigSource config) { IConfig start_config = config.Configs["Startup"]; IConfig mesh_config = config.Configs["Mesh"]; decodedSculptMapPath = start_config.GetString("DecodedSculptMapPath","j2kDecodeCache"); cacheSculptMaps = start_config.GetBoolean("CacheSculptMaps", cacheSculptMaps); if (mesh_config != null) { useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh); debugDetail = mesh_config.GetBoolean("LogMeshDetails", debugDetail); } try { if (!Directory.Exists(decodedSculptMapPath)) Directory.CreateDirectory(decodedSculptMapPath); } catch (Exception e) { m_log.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedSculptMapPath, e.Message); } } /// <summary> /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail /// for some reason /// </summary> /// <param name="minX"></param> /// <param name="maxX"></param> /// <param name="minY"></param> /// <param name="maxY"></param> /// <param name="minZ"></param> /// <param name="maxZ"></param> /// <returns></returns> private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ) { Mesh box = new Mesh(); List<Vertex> vertices = new List<Vertex>(); // bottom vertices.Add(new Vertex(minX, maxY, minZ)); vertices.Add(new Vertex(maxX, maxY, minZ)); vertices.Add(new Vertex(maxX, minY, minZ)); vertices.Add(new Vertex(minX, minY, minZ)); box.Add(new Triangle(vertices[0], vertices[1], vertices[2])); box.Add(new Triangle(vertices[0], vertices[2], vertices[3])); // top vertices.Add(new Vertex(maxX, maxY, maxZ)); vertices.Add(new Vertex(minX, maxY, maxZ)); vertices.Add(new Vertex(minX, minY, maxZ)); vertices.Add(new Vertex(maxX, minY, maxZ)); box.Add(new Triangle(vertices[4], vertices[5], vertices[6])); box.Add(new Triangle(vertices[4], vertices[6], vertices[7])); // sides box.Add(new Triangle(vertices[5], vertices[0], vertices[3])); box.Add(new Triangle(vertices[5], vertices[3], vertices[6])); box.Add(new Triangle(vertices[1], vertices[0], vertices[5])); box.Add(new Triangle(vertices[1], vertices[5], vertices[4])); box.Add(new Triangle(vertices[7], vertices[1], vertices[4])); box.Add(new Triangle(vertices[7], vertices[2], vertices[1])); box.Add(new Triangle(vertices[3], vertices[2], vertices[7])); box.Add(new Triangle(vertices[3], vertices[7], vertices[6])); return box; } /// <summary> /// Creates a simple bounding box mesh for a complex input mesh /// </summary> /// <param name="meshIn"></param> /// <returns></returns> private static Mesh CreateBoundingBoxMesh(Mesh meshIn) { float minX = float.MaxValue; float maxX = float.MinValue; float minY = float.MaxValue; float maxY = float.MinValue; float minZ = float.MaxValue; float maxZ = float.MinValue; foreach (Vector3 v in meshIn.getVertexList()) { if (v.X < minX) minX = v.X; if (v.Y < minY) minY = v.Y; if (v.Z < minZ) minZ = v.Z; if (v.X > maxX) maxX = v.X; if (v.Y > maxY) maxY = v.Y; if (v.Z > maxZ) maxZ = v.Z; } return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ); } private void ReportPrimError(string message, string primName, PrimMesh primMesh) { m_log.Error(message); m_log.Error("\nPrim Name: " + primName); m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString()); } /// <summary> /// Add a submesh to an existing list of coords and faces. /// </summary> /// <param name="subMeshData"></param> /// <param name="size">Size of entire object</param> /// <param name="coords"></param> /// <param name="faces"></param> private void AddSubMesh(OSDMap subMeshData, Vector3 size, List<Coord> coords, List<Face> faces) { // Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap)); // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no // geometry for this submesh. if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"])) return; OpenMetaverse.Vector3 posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3(); OpenMetaverse.Vector3 posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3(); ushort faceIndexOffset = (ushort)coords.Count; byte[] posBytes = subMeshData["Position"].AsBinary(); for (int i = 0; i < posBytes.Length; i += 6) { ushort uX = Utils.BytesToUInt16(posBytes, i); ushort uY = Utils.BytesToUInt16(posBytes, i + 2); ushort uZ = Utils.BytesToUInt16(posBytes, i + 4); Coord c = new Coord( Utils.UInt16ToFloat(uX, posMin.X, posMax.X) * size.X, Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y) * size.Y, Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z) * size.Z); coords.Add(c); } byte[] triangleBytes = subMeshData["TriangleList"].AsBinary(); for (int i = 0; i < triangleBytes.Length; i += 6) { ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset); ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset); ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset); Face f = new Face(v1, v2, v3); faces.Add(f); } } /// <summary> /// Create a physics mesh from data that comes with the prim. The actual data used depends on the prim type. /// </summary> /// <param name="primName"></param> /// <param name="primShape"></param> /// <param name="size"></param> /// <param name="lod"></param> /// <returns></returns> private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod) { // m_log.DebugFormat( // "[MESH]: Creating physics proxy for {0}, shape {1}", // primName, (OpenMetaverse.SculptType)primShape.SculptType); List<Coord> coords; List<Face> faces; if (primShape.SculptEntry) { if (((OpenMetaverse.SculptType)primShape.SculptType) == SculptType.Mesh) { if (!useMeshiesPhysicsMesh) return null; if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, size, out coords, out faces)) return null; } else { if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, size, lod, out coords, out faces)) return null; } } else { if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, size, lod, out coords, out faces)) return null; } // Remove the reference to any JPEG2000 sculpt data so it can be GCed primShape.SculptData = Utils.EmptyBytes; int numCoords = coords.Count; int numFaces = faces.Count; // Create the list of vertices List<Vertex> vertices = new List<Vertex>(); for (int i = 0; i < numCoords; i++) { Coord c = coords[i]; vertices.Add(new Vertex(c.X, c.Y, c.Z)); } Mesh mesh = new Mesh(); // Add the corresponding triangles to the mesh for (int i = 0; i < numFaces; i++) { Face f = faces[i]; mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3])); } return mesh; } /// <summary> /// Generate the co-ords and faces necessary to construct a mesh from the mesh data the accompanies a prim. /// </summary> /// <param name="primName"></param> /// <param name="primShape"></param> /// <param name="size"></param> /// <param name="coords">Coords are added to this list by the method.</param> /// <param name="faces">Faces are added to this list by the method.</param> /// <returns>true if coords and faces were successfully generated, false if not</returns> private bool GenerateCoordsAndFacesFromPrimMeshData( string primName, PrimitiveBaseShape primShape, Vector3 size, out List<Coord> coords, out List<Face> faces) { // m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName); coords = new List<Coord>(); faces = new List<Face>(); OSD meshOsd = null; mConvexHulls = null; mBoundingHull = null; if (primShape.SculptData.Length <= 0) { // XXX: At the moment we can not log here since ODEPrim, for instance, ends up triggering this // method twice - once before it has loaded sculpt data from the asset service and once afterwards. // The first time will always call with unloaded SculptData if this needs to be uploaded. // m_log.ErrorFormat("[MESH]: asset data for {0} is zero length", primName); return false; } long start = 0; using (MemoryStream data = new MemoryStream(primShape.SculptData)) { try { OSD osd = OSDParser.DeserializeLLSDBinary(data); if (osd is OSDMap) meshOsd = (OSDMap)osd; else { m_log.Warn("[Mesh}: unable to cast mesh asset to OSDMap"); return false; } } catch (Exception e) { m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString()); } start = data.Position; } if (meshOsd is OSDMap) { OSDMap physicsParms = null; OSDMap map = (OSDMap)meshOsd; if (map.ContainsKey("physics_shape")) { physicsParms = (OSDMap)map["physics_shape"]; // old asset format if (debugDetail) m_log.DebugFormat("{0} prim='{1}': using 'physics_shape' mesh data", LogHeader, primName); } else if (map.ContainsKey("physics_mesh")) { physicsParms = (OSDMap)map["physics_mesh"]; // new asset format if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'physics_mesh' mesh data", LogHeader, primName); } else if (map.ContainsKey("medium_lod")) { physicsParms = (OSDMap)map["medium_lod"]; // if no physics mesh, try to fall back to medium LOD display mesh if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'medium_lod' mesh data", LogHeader, primName); } else if (map.ContainsKey("high_lod")) { physicsParms = (OSDMap)map["high_lod"]; // if all else fails, use highest LOD display mesh and hope it works :) if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'high_lod' mesh data", LogHeader, primName); } if (map.ContainsKey("physics_convex")) { // pull this out also in case physics engine can use it OSD convexBlockOsd = null; try { OSDMap convexBlock = (OSDMap)map["physics_convex"]; { int convexOffset = convexBlock["offset"].AsInteger() + (int)start; int convexSize = convexBlock["size"].AsInteger(); byte[] convexBytes = new byte[convexSize]; System.Buffer.BlockCopy(primShape.SculptData, convexOffset, convexBytes, 0, convexSize); try { convexBlockOsd = DecompressOsd(convexBytes); } catch (Exception e) { m_log.ErrorFormat("{0} prim='{1}': exception decoding convex block: {2}", LogHeader, primName, e); //return false; } } if (convexBlockOsd != null && convexBlockOsd is OSDMap) { convexBlock = convexBlockOsd as OSDMap; if (debugDetail) { string keys = LogHeader + " keys found in convexBlock: "; foreach (KeyValuePair<string, OSD> kvp in convexBlock) keys += "'" + kvp.Key + "' "; m_log.Debug(keys); } Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f); if (convexBlock.ContainsKey("Min")) min = convexBlock["Min"].AsVector3(); Vector3 max = new Vector3(0.5f, 0.5f, 0.5f); if (convexBlock.ContainsKey("Max")) max = convexBlock["Max"].AsVector3(); List<Vector3> boundingHull = null; if (convexBlock.ContainsKey("BoundingVerts")) { byte[] boundingVertsBytes = convexBlock["BoundingVerts"].AsBinary(); boundingHull = new List<Vector3>(); for (int i = 0; i < boundingVertsBytes.Length; ) { ushort uX = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; ushort uY = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; ushort uZ = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; Vector3 pos = new Vector3( Utils.UInt16ToFloat(uX, min.X, max.X), Utils.UInt16ToFloat(uY, min.Y, max.Y), Utils.UInt16ToFloat(uZ, min.Z, max.Z) ); boundingHull.Add(pos); } mBoundingHull = boundingHull; if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed bounding hull. nVerts={2}", LogHeader, primName, mBoundingHull.Count); } if (convexBlock.ContainsKey("HullList")) { byte[] hullList = convexBlock["HullList"].AsBinary(); byte[] posBytes = convexBlock["Positions"].AsBinary(); List<List<Vector3>> hulls = new List<List<Vector3>>(); int posNdx = 0; foreach (byte cnt in hullList) { int count = cnt == 0 ? 256 : cnt; List<Vector3> hull = new List<Vector3>(); for (int i = 0; i < count; i++) { ushort uX = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; ushort uY = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; ushort uZ = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; Vector3 pos = new Vector3( Utils.UInt16ToFloat(uX, min.X, max.X), Utils.UInt16ToFloat(uY, min.Y, max.Y), Utils.UInt16ToFloat(uZ, min.Z, max.Z) ); hull.Add(pos); } hulls.Add(hull); } mConvexHulls = hulls; if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed hulls. nHulls={2}", LogHeader, primName, mConvexHulls.Count); } else { if (debugDetail) m_log.DebugFormat("{0} prim='{1}' has physics_convex but no HullList", LogHeader, primName); } } } catch (Exception e) { m_log.WarnFormat("{0} exception decoding convex block: {1}", LogHeader, e); } } if (physicsParms == null) { m_log.WarnFormat("[MESH]: No recognized physics mesh found in mesh asset for {0}", primName); return false; } int physOffset = physicsParms["offset"].AsInteger() + (int)start; int physSize = physicsParms["size"].AsInteger(); if (physOffset < 0 || physSize == 0) return false; // no mesh data in asset OSD decodedMeshOsd = new OSD(); byte[] meshBytes = new byte[physSize]; System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize); // byte[] decompressed = new byte[physSize * 5]; try { decodedMeshOsd = DecompressOsd(meshBytes); } catch (Exception e) { m_log.ErrorFormat("{0} prim='{1}': exception decoding physical mesh: {2}", LogHeader, primName, e); return false; } OSDArray decodedMeshOsdArray = null; // physics_shape is an array of OSDMaps, one for each submesh if (decodedMeshOsd is OSDArray) { // Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd)); decodedMeshOsdArray = (OSDArray)decodedMeshOsd; foreach (OSD subMeshOsd in decodedMeshOsdArray) { if (subMeshOsd is OSDMap) AddSubMesh(subMeshOsd as OSDMap, size, coords, faces); } if (debugDetail) m_log.DebugFormat("{0} {1}: mesh decoded. offset={2}, size={3}, nCoords={4}, nFaces={5}", LogHeader, primName, physOffset, physSize, coords.Count, faces.Count); } } return true; } /// <summary> /// decompresses a gzipped OSD object /// </summary> /// <param name="decodedOsd"></param> the OSD object /// <param name="meshBytes"></param> /// <returns></returns> private static OSD DecompressOsd(byte[] meshBytes) { OSD decodedOsd = null; using (MemoryStream inMs = new MemoryStream(meshBytes)) { using (MemoryStream outMs = new MemoryStream()) { using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress)) { byte[] readBuffer = new byte[2048]; inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header int readLen = 0; while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0) outMs.Write(readBuffer, 0, readLen); outMs.Flush(); outMs.Seek(0, SeekOrigin.Begin); byte[] decompressedBuf = outMs.GetBuffer(); decodedOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf); } } } return decodedOsd; } /// <summary> /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim. /// </summary> /// <param name="primName"></param> /// <param name="primShape"></param> /// <param name="size"></param> /// <param name="lod"></param> /// <param name="coords">Coords are added to this list by the method.</param> /// <param name="faces">Faces are added to this list by the method.</param> /// <returns>true if coords and faces were successfully generated, false if not</returns> private bool GenerateCoordsAndFacesFromPrimSculptData( string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces) { coords = new List<Coord>(); faces = new List<Face>(); PrimMesher.SculptMesh sculptMesh; Image idata = null; string decodedSculptFileName = ""; if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero) { decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString()); try { if (File.Exists(decodedSculptFileName)) { idata = Image.FromFile(decodedSculptFileName); } } catch (Exception e) { m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message); } //if (idata != null) // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString()); } if (idata == null) { if (primShape.SculptData == null || primShape.SculptData.Length == 0) return false; try { OpenMetaverse.Imaging.ManagedImage managedImage; OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out managedImage); if (managedImage == null) { // In some cases it seems that the decode can return a null bitmap without throwing // an exception m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName); return false; } if ((managedImage.Channels & OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha) != 0) managedImage.ConvertChannels(managedImage.Channels & ~OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha); Bitmap imgData = OpenMetaverse.Imaging.LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA())); idata = (Image)imgData; managedImage = null; if (cacheSculptMaps) { try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); } catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); } } } catch (DllNotFoundException) { m_log.Error("[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed. Often times this is because of an old version of GLIBC. You must have version 2.4 or above!"); return false; } catch (IndexOutOfRangeException) { m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed"); return false; } catch (Exception ex) { m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message); return false; } } PrimMesher.SculptMesh.SculptType sculptType; switch ((OpenMetaverse.SculptType)primShape.SculptType) { case OpenMetaverse.SculptType.Cylinder: sculptType = PrimMesher.SculptMesh.SculptType.cylinder; break; case OpenMetaverse.SculptType.Plane: sculptType = PrimMesher.SculptMesh.SculptType.plane; break; case OpenMetaverse.SculptType.Torus: sculptType = PrimMesher.SculptMesh.SculptType.torus; break; case OpenMetaverse.SculptType.Sphere: sculptType = PrimMesher.SculptMesh.SculptType.sphere; break; default: sculptType = PrimMesher.SculptMesh.SculptType.plane; break; } bool mirror = ((primShape.SculptType & 128) != 0); bool invert = ((primShape.SculptType & 64) != 0); sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert); idata.Dispose(); sculptMesh.DumpRaw(baseDir, primName, "primMesh"); sculptMesh.Scale(size.X, size.Y, size.Z); coords = sculptMesh.coords; faces = sculptMesh.faces; return true; } /// <summary> /// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim. /// </summary> /// <param name="primName"></param> /// <param name="primShape"></param> /// <param name="size"></param> /// <param name="coords">Coords are added to this list by the method.</param> /// <param name="faces">Faces are added to this list by the method.</param> /// <returns>true if coords and faces were successfully generated, false if not</returns> private bool GenerateCoordsAndFacesFromPrimShapeData( string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces) { PrimMesh primMesh; coords = new List<Coord>(); faces = new List<Face>(); float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f; float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f; float pathBegin = (float)primShape.PathBegin * 2.0e-5f; float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f; float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f; float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f; float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f; float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f; float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f; if (profileHollow > 0.95f) profileHollow = 0.95f; int sides = 4; LevelOfDetail iLOD = (LevelOfDetail)lod; if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle) sides = 3; else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle) { switch (iLOD) { case LevelOfDetail.High: sides = 24; break; case LevelOfDetail.Medium: sides = 12; break; case LevelOfDetail.Low: sides = 6; break; case LevelOfDetail.VeryLow: sides = 3; break; default: sides = 24; break; } } else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle) { // half circle, prim is a sphere switch (iLOD) { case LevelOfDetail.High: sides = 24; break; case LevelOfDetail.Medium: sides = 12; break; case LevelOfDetail.Low: sides = 6; break; case LevelOfDetail.VeryLow: sides = 3; break; default: sides = 24; break; } profileBegin = 0.5f * profileBegin + 0.5f; profileEnd = 0.5f * profileEnd + 0.5f; } int hollowSides = sides; if (primShape.HollowShape == HollowShape.Circle) { switch (iLOD) { case LevelOfDetail.High: hollowSides = 24; break; case LevelOfDetail.Medium: hollowSides = 12; break; case LevelOfDetail.Low: hollowSides = 6; break; case LevelOfDetail.VeryLow: hollowSides = 3; break; default: hollowSides = 24; break; } } else if (primShape.HollowShape == HollowShape.Square) hollowSides = 4; else if (primShape.HollowShape == HollowShape.Triangle) hollowSides = 3; primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides); if (primMesh.errorMessage != null) if (primMesh.errorMessage.Length > 0) m_log.Error("[ERROR] " + primMesh.errorMessage); primMesh.topShearX = pathShearX; primMesh.topShearY = pathShearY; primMesh.pathCutBegin = pathBegin; primMesh.pathCutEnd = pathEnd; if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible) { primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10; primMesh.twistEnd = primShape.PathTwist * 18 / 10; primMesh.taperX = pathScaleX; primMesh.taperY = pathScaleY; if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f) { ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh); if (profileBegin < 0.0f) profileBegin = 0.0f; if (profileEnd > 1.0f) profileEnd = 1.0f; } #if SPAM m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString()); #endif try { primMesh.ExtrudeLinear(); } catch (Exception ex) { ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh); return false; } } else { primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f; primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f; primMesh.radius = 0.01f * primShape.PathRadiusOffset; primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions; primMesh.skew = 0.01f * primShape.PathSkew; primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10; primMesh.twistEnd = primShape.PathTwist * 36 / 10; primMesh.taperX = primShape.PathTaperX * 0.01f; primMesh.taperY = primShape.PathTaperY * 0.01f; if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f) { ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh); if (profileBegin < 0.0f) profileBegin = 0.0f; if (profileEnd > 1.0f) profileEnd = 1.0f; } #if SPAM m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString()); #endif try { primMesh.ExtrudeCircular(); } catch (Exception ex) { ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh); return false; } } primMesh.DumpRaw(baseDir, primName, "primMesh"); primMesh.Scale(size.X, size.Y, size.Z); coords = primMesh.coords; faces = primMesh.faces; return true; } /// <summary> /// temporary prototype code - please do not use until the interface has been finalized! /// </summary> /// <param name="size">value to scale the hull points by</param> /// <returns>a list of vertices in the bounding hull if it exists and has been successfully decoded, otherwise null</returns> public List<Vector3> GetBoundingHull(Vector3 size) { if (mBoundingHull == null) return null; List<Vector3> verts = new List<Vector3>(); foreach (var vert in mBoundingHull) verts.Add(vert * size); return verts; } /// <summary> /// temporary prototype code - please do not use until the interface has been finalized! /// </summary> /// <param name="size">value to scale the hull points by</param> /// <returns>a list of hulls if they exist and have been successfully decoded, otherwise null</returns> public List<List<Vector3>> GetConvexHulls(Vector3 size) { if (mConvexHulls == null) return null; List<List<Vector3>> hulls = new List<List<Vector3>>(); foreach (var hull in mConvexHulls) { List<Vector3> verts = new List<Vector3>(); foreach (var vert in hull) verts.Add(vert * size); hulls.Add(verts); } return hulls; } public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod) { return CreateMesh(primName, primShape, size, lod, false, true); } public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical) { return CreateMesh(primName, primShape, size, lod, isPhysical, true); } public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache) { #if SPAM m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName); #endif Mesh mesh = null; ulong key = 0; // If this mesh has been created already, return it instead of creating another copy // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory if (shouldCache) { key = primShape.GetMeshKey(size, lod); lock (m_uniqueMeshes) { if (m_uniqueMeshes.TryGetValue(key, out mesh)) return mesh; } } if (size.X < 0.01f) size.X = 0.01f; if (size.Y < 0.01f) size.Y = 0.01f; if (size.Z < 0.01f) size.Z = 0.01f; mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod); if (mesh != null) { if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh) { #if SPAM m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " + minSizeForComplexMesh.ToString() + " - creating simple bounding box"); #endif mesh = CreateBoundingBoxMesh(mesh); mesh.DumpRaw(baseDir, primName, "Z extruded"); } // trim the vertex and triangle lists to free up memory mesh.TrimExcess(); if (shouldCache) { lock (m_uniqueMeshes) { m_uniqueMeshes.Add(key, mesh); } } } return mesh; } } }
#if SILVERLIGHT using Microsoft.VisualStudio.TestTools.UnitTesting; #elif NETFX_CORE #else using NUnit.Framework; #endif #if !FREE && !NETFX_CORE using DevExpress.Xpf.Core.Tests; #endif using System; using System.Linq.Expressions; using DevExpress.Mvvm.DataAnnotations; using System.Windows.Input; using DevExpress.Mvvm.Native; using System.ComponentModel.DataAnnotations; #if !NETFX_CORE using System.Windows.Controls; using System.Windows.Data; using System.ComponentModel; #endif namespace DevExpress.Mvvm.Tests { #if !NETFX_CORE [TestFixture] public class ViewModelBaseTests { public interface IService1 { } public interface IService2 { } public class TestService1 : IService1 { } public class TestService2 : IService2 { } [Test] public void Interfaces() { var viewModel = new TestViewModel(); var parentViewModel = new TestViewModel(); Assert.IsNull(viewModel.ParentViewModelChangedValue); ((ISupportParentViewModel)viewModel).ParentViewModel = parentViewModel; Assert.AreEqual(parentViewModel, viewModel.ParentViewModelChangedValue); parentViewModel.ServiceContainer.RegisterService(new TestService1()); Assert.IsNotNull(parentViewModel.ServiceContainer.GetService<IService1>()); Assert.IsNotNull(viewModel.ServiceContainer.GetService<IService1>()); Assert.IsNotNull(viewModel.GetService<IService1>()); Assert.IsNull(viewModel.GetService<IService1>(ServiceSearchMode.LocalOnly)); Assert.IsNull(viewModel.NavigatedToParameter); ((ISupportParameter)viewModel).Parameter = "test"; Assert.AreEqual("test", viewModel.NavigatedToParameter); Assert.AreEqual("test", ((ISupportParameter)viewModel).Parameter); } [Test] public void NullParameterCausesOnParameterChanged() { var viewModel = new TestViewModel(); Assert.IsNull(((ISupportParameter)viewModel).Parameter); Assert.AreEqual(0, viewModel.ParameterChangedCount); ((ISupportParameter)viewModel).Parameter = null; Assert.IsNull(((ISupportParameter)viewModel).Parameter); Assert.AreEqual(1, viewModel.ParameterChangedCount); } [Test] public void InitializeInDesignMode() { var viewModel = new TestViewModel(); Assert.IsNull(((ISupportParameter)viewModel).Parameter); Assert.AreEqual(0, viewModel.ParameterChangedCount); viewModel.ForceInitializeInDesignMode(); Assert.IsNull(((ISupportParameter)viewModel).Parameter); Assert.AreEqual(1, viewModel.ParameterChangedCount); } [Test] public void InitializeInRuntime() { ViewModelDesignHelper.IsInDesignModeOverride = true; var viewModel = new TestViewModel(); Assert.AreEqual(0, viewModel.InitializeInRuntimeCount); ViewModelDesignHelper.IsInDesignModeOverride = false; var viewModel2 = new TestViewModel(); Assert.AreEqual(1, viewModel2.InitializeInRuntimeCount); } #region command attrbute public abstract class CommandAttributeViewModelBaseCounters : ViewModelBase { public int BaseClassCommandCallCount; public int SimpleMethodCallCount; public int MethodWithCommandCallCount; public int CustomNameCommandCallCount; public bool MethodWithCanExecuteCanExcute = false; public int MethodWithReturnTypeCallCount; public int MethodWithParameterCallCount; public int MethodWithParameterLastParameter; public bool MethodWithCustomCanExecuteCanExcute = false; } public abstract class CommandAttributeViewModelBase : CommandAttributeViewModelBaseCounters { [Command] public void BaseClassCommand() { BaseClassCommandCallCount++; } } public class CommandAttributeViewModel : CommandAttributeViewModelBase { [Command] public void Simple() { SimpleMethodCallCount++; } [Command] public void MethodWithCommand() { MethodWithCommandCallCount++; } public void NoAttribute() { } [Command(Name = "MyCommand")] public void CustomName() { CustomNameCommandCallCount++; } [Command] public void MethodWithCanExecute() { } public bool CanMethodWithCanExecute() { return MethodWithCanExecuteCanExcute; } [Command] public int MethodWithReturnType() { MethodWithReturnTypeCallCount++; return 0; } [Command] public void MethodWithParameter(int parameter) { MethodWithParameterCallCount++; MethodWithParameterLastParameter = parameter; } public bool CanMethodWithParameter(int parameter) { return parameter != 13; } [Command(CanExecuteMethodName = "CanMethodWithCustomCanExecute_" #if !SILVERLIGHT , UseCommandManager = false #endif )] public void MethodWithCustomCanExecute() { } public bool CanMethodWithCustomCanExecute_() { return MethodWithCustomCanExecuteCanExcute; } } [MetadataType(typeof(CommandAttributeViewModelMetadata))] public class CommandAttributeViewModel_FluentAPI : CommandAttributeViewModelBaseCounters { public void BaseClassCommand() { BaseClassCommandCallCount++; } public void Simple() { SimpleMethodCallCount++; } public void MethodWithCommand() { MethodWithCommandCallCount++; } public void NoAttribute() { } public void CustomName() { CustomNameCommandCallCount++; } public void MethodWithCanExecute() { } public bool CanMethodWithCanExecute() { return MethodWithCanExecuteCanExcute; } public int MethodWithReturnType() { MethodWithReturnTypeCallCount++; return 0; } public void MethodWithParameter(int parameter) { MethodWithParameterCallCount++; MethodWithParameterLastParameter = parameter; } public bool CanMethodWithParameter(int parameter) { return parameter != 13; } public void MethodWithCustomCanExecute() { } public bool CanMethodWithCustomCanExecute_(int x) { throw new InvalidOperationException(); } public bool CanMethodWithCustomCanExecute_() { return MethodWithCustomCanExecuteCanExcute; } } public class CommandAttributeViewModelMetadata : IMetadataProvider<CommandAttributeViewModel_FluentAPI> { void IMetadataProvider<CommandAttributeViewModel_FluentAPI>.BuildMetadata(MetadataBuilder<CommandAttributeViewModel_FluentAPI> builder) { builder.CommandFromMethod(x => x.BaseClassCommand()); builder.CommandFromMethod(x => x.Simple()); builder.CommandFromMethod(x => x.MethodWithCommand()); builder.CommandFromMethod(x => x.CustomName()).CommandName("MyCommand"); builder.CommandFromMethod(x => x.MethodWithCanExecute()); builder.CommandFromMethod(x => x.MethodWithReturnType()); builder.CommandFromMethod(x => x.MethodWithParameter(default(int))); builder.CommandFromMethod(x => x.MethodWithCustomCanExecute()) #if !SILVERLIGHT .DoNotUseCommandManager() #endif .CanExecuteMethod(x => x.CanMethodWithCustomCanExecute_()) #if !SILVERLIGHT .DoNotUseCommandManager() #endif ; } } [Test] public void CommandAttribute_ViewModelTest() { var viewModel = new CommandAttributeViewModel(); CommandAttribute_ViewModelTestCore(viewModel, () => viewModel.MethodWithCanExecute(), () => viewModel.MethodWithCustomCanExecute()); viewModel = new CommandAttributeViewModel(); CommandAttribute_ViewModelTestCore(viewModel, () => viewModel.MethodWithCanExecute(), () => viewModel.MethodWithCustomCanExecute()); } #if !SILVERLIGHT [Test] public void CommandAttribute_ViewModelTest_FluentAPI() { var viewModel = new CommandAttributeViewModel_FluentAPI(); CommandAttribute_ViewModelTestCore(viewModel, () => viewModel.MethodWithCanExecute(), () => viewModel.MethodWithCustomCanExecute()); Assert.AreSame(((ICustomTypeDescriptor)viewModel).GetProperties(), ((ICustomTypeDescriptor)viewModel).GetProperties()); } #endif void CommandAttribute_ViewModelTestCore(CommandAttributeViewModelBaseCounters viewModel, Expression<Action> methodWithCanExecuteExpression, Expression<Action> methodWithCustomCanExecuteExpression) { var button = new Button() { DataContext = viewModel }; button.SetBinding(Button.CommandProperty, new Binding("SimpleCommand")); button.Command.Execute(null); Assert.AreEqual(1, viewModel.SimpleMethodCallCount); button.SetBinding(Button.CommandProperty, new Binding("NoAttributeCommand")); Assert.IsNull(button.Command); button.SetBinding(Button.CommandProperty, new Binding("MethodWithCommand")); button.Command.Execute(null); Assert.AreEqual(1, viewModel.MethodWithCommandCallCount); button.SetBinding(Button.CommandProperty, new Binding("MyCommand")); button.Command.Execute(null); Assert.AreEqual(1, viewModel.CustomNameCommandCallCount); button.SetBinding(Button.CommandProperty, new Binding("BaseClassCommand")); button.Command.Execute(null); Assert.AreEqual(1, viewModel.BaseClassCommandCallCount); Assert.IsTrue(button.IsEnabled); button.SetBinding(Button.CommandProperty, new Binding("MethodWithCanExecuteCommand")); Assert.IsFalse(button.IsEnabled); viewModel.MethodWithCanExecuteCanExcute = true; #if !SILVERLIGHT DispatcherHelper.DoEvents(); #endif Assert.IsFalse(button.IsEnabled); viewModel.RaiseCanExecuteChanged(methodWithCanExecuteExpression); #if !SILVERLIGHT Assert.IsFalse(button.IsEnabled); DispatcherHelper.DoEvents(); #endif Assert.IsTrue(button.IsEnabled); button.SetBinding(Button.CommandProperty, new Binding("MethodWithReturnTypeCommand")); button.Command.Execute(null); Assert.AreEqual(1, viewModel.MethodWithReturnTypeCallCount); button.SetBinding(Button.CommandProperty, new Binding("MethodWithParameterCommand")); button.Command.Execute(9); Assert.AreEqual(1, viewModel.MethodWithParameterCallCount); Assert.AreEqual(9, viewModel.MethodWithParameterLastParameter); Assert.IsTrue(button.Command.CanExecute(9)); Assert.IsFalse(button.Command.CanExecute(13)); button.Command.Execute("10"); Assert.AreEqual(2, viewModel.MethodWithParameterCallCount); Assert.AreEqual(10, viewModel.MethodWithParameterLastParameter); button.SetBinding(Button.CommandProperty, new Binding("MethodWithCustomCanExecuteCommand")); Assert.IsFalse(button.IsEnabled); viewModel.MethodWithCustomCanExecuteCanExcute = true; Assert.IsFalse(button.IsEnabled); viewModel.RaiseCanExecuteChanged(methodWithCustomCanExecuteExpression); Assert.IsTrue(button.IsEnabled); } #region exceptions #pragma warning disable 0618 public class NameConflictViewModel : ViewModelBase { [Command] public void Simple() { } public ICommand SimpleCommand { get; private set; } } [Test] public void CommandAttribute_NameConflictTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new NameConflictViewModel(); }, x => Assert.AreEqual("Property with the same name already exists: SimpleCommand.", x.Message)); } public class DuplicateNamesViewModel : ViewModelBase { [Command(Name = "MyCommand")] public void Method1() { } [Command(Name = "MyCommand")] public void Method2() { } } [Test] public void CommandAttribute_DuplicateNamesTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new DuplicateNamesViewModel(); }, x => Assert.AreEqual("Property with the same name already exists: MyCommand.", x.Message)); } public class NotPublicMethodViewModel : ViewModelBase { [Command] protected internal void NotPublicMethod() { } } [Test] public void CommandAttribute_NotPublicMethodTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new NotPublicMethodViewModel(); }, x => Assert.AreEqual("Method should be public: NotPublicMethod.", x.Message)); } public class TooMuchArgumentsMethodViewModel : ViewModelBase { [Command] public void TooMuchArgumentsMethod(int a, int b) { } } [Test] public void CommandAttribute_TooMuchArgumentsMethodTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new TooMuchArgumentsMethodViewModel(); }, x => Assert.AreEqual("Method cannot have more than one parameter: TooMuchArgumentsMethod.", x.Message)); } public class OutParameterMethodViewModel : ViewModelBase { [Command] public void OutParameterMethod(out int a) { a = 0; } } [Test] public void CommandAttribute_OutParameterMethodTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new OutParameterMethodViewModel(); }, x => Assert.AreEqual("Method cannot have out or reference parameter: OutParameterMethod.", x.Message)); } public class RefParameterMethodViewModel : ViewModelBase { [Command] public void RefParameterMethod(ref int a) { a = 0; } } [Test] public void CommandAttribute_RefParameterMethodTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new RefParameterMethodViewModel(); }, x => Assert.AreEqual("Method cannot have out or reference parameter: RefParameterMethod.", x.Message)); } public class CanExecuteParameterCountMismatchViewModel : ViewModelBase { [Command] public void Method() { } public bool CanMethod(int a) { return true; } } [Test] public void CommandAttribute_CanExecuteParameterCountMismatchTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new CanExecuteParameterCountMismatchViewModel(); }, x => Assert.AreEqual("Can execute method has incorrect parameters: CanMethod.", x.Message)); } public class CanExecuteParametersMismatchViewModel : ViewModelBase { [Command] public void Method(long a) { } public bool CanMethod(int a) { return true; } } [Test] public void CommandAttribute_CanExecuteParametersMismatchTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new CanExecuteParametersMismatchViewModel(); }, x => Assert.AreEqual("Can execute method has incorrect parameters: CanMethod.", x.Message)); } public class CanExecuteParametersMismatchViewModel2 : ViewModelBase { [Command] public void Method(int a) { } public bool CanMethod(out int a) { a = 0; return true; } } [Test] public void CommandAttribute_CanExecuteParametersMismatchTest2() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new CanExecuteParametersMismatchViewModel2(); }, x => Assert.AreEqual("Can execute method has incorrect parameters: CanMethod.", x.Message)); } public class NotPublicCanExecuteViewModel : ViewModelBase { [Command] public void Method() { } bool CanMethod() { return true; } } [Test] public void CommandAttribute_NotPublicCanExecuteTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new NotPublicCanExecuteViewModel(); }, x => Assert.AreEqual("Method should be public: CanMethod.", x.Message)); } public class InvalidCanExecuteMethodNameViewModel : ViewModelBase { [Command(CanExecuteMethodName = "CanMethod_")] public void Method() { } } [Test] public void CommandAttribute_InvalidCanExecuteMethodNameTest() { AssertHelper.AssertThrows<CommandAttributeException>(() => { new InvalidCanExecuteMethodNameViewModel(); }, x => Assert.AreEqual("Method not found: CanMethod_.", x.Message)); } #pragma warning restore 0618 #endregion #endregion } #endif public class TestViewModel : ViewModelBase { public new IServiceContainer ServiceContainer { get { return base.ServiceContainer; } } public object ParentViewModelChangedValue { get; private set; } protected override void OnParentViewModelChanged(object parentViewModel) { ParentViewModelChangedValue = parentViewModel; base.OnParentViewModelChanged(parentViewModel); } public object NavigatedToParameter { get; private set; } protected override void OnParameterChanged(object parameter) { NavigatedToParameter = parameter; ParameterChangedCount++; base.OnParameterChanged(parameter); } public new T GetService<T>(ServiceSearchMode searchMode = ServiceSearchMode.PreferLocal) where T : class { return base.GetService<T>(searchMode); } public int ParameterChangedCount { get; private set; } public void ForceInitializeInDesignMode() { OnInitializeInDesignMode(); } public int InitializeInRuntimeCount { get; private set; } protected override void OnInitializeInRuntime() { base.OnInitializeInRuntime(); InitializeInRuntimeCount++; } } }
// 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.InteropServices; using System.Runtime.ConstrainedExecution; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using MemberListType = System.RuntimeType.MemberListType; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; using System.Runtime.CompilerServices; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class MethodInfo : MethodBase, _MethodInfo { #region Constructor protected MethodInfo() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(MethodInfo left, MethodInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeMethodInfo || right is RuntimeMethodInfo) { return false; } return left.Equals(right); } public static bool operator !=(MethodInfo left, MethodInfo right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } } #endregion #region Public Abstract\Virtual Members public virtual Type ReturnType { get { throw new NotImplementedException(); } } public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } } public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; } public abstract MethodInfo GetBaseDefinition(); [System.Runtime.InteropServices.ComVisible(true)] public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } [System.Runtime.InteropServices.ComVisible(true)] public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } #endregion #if !FEATURE_CORECLR Type _MethodInfo.GetType() { return base.GetType(); } void _MethodInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _MethodInfo.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 _MethodInfo.Invoke in VM\DangerousAPIs.h and // include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _MethodInfo.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 sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo { #region Private Data Members private IntPtr m_handle; private RuntimeTypeCache m_reflectedTypeCache; private string m_name; private string m_toString; private ParameterInfo[] m_parameters; private ParameterInfo m_returnParameter; private BindingFlags m_bindingFlags; private MethodAttributes m_methodAttributes; private Signature m_signature; private RuntimeType m_declaringType; private object m_keepalive; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (m_declaringType.IsArray && IsPublic && !IsStatic) 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; } if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; if (IsGenericMethod && !IsGenericMethodDefinition) { foreach (Type t in GetGenericArguments()) { if (((RuntimeType)t).IsNonW8PFrameworkAPI()) return true; } } return false; } internal override bool IsDynamicallyInvokable { get { return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI(); } } #endif internal INVOCATION_FLAGS InvocationFlags { [System.Security.SecuritySafeCritical] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; Type declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. if (ContainsGenericParameters || ReturnType.IsByRef || (declaringType != null && declaringType.ContainsGenericParameters) || ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) { // We don't need other flags if this method cannot be invoked invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else { // this should be an invocable method, determine the other flags that participate in invocation invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0) { if ( (Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || (declaringType != null && declaringType.NeedsReflectionSecurityCheck) ) { // If method is non-public, or declaring type is not visible invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; } else if (IsGenericMethod) { Type[] genericArguments = GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i].NeedsReflectionSecurityCheck) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; break; } } } } } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion #region Constructor [System.Security.SecurityCritical] // auto-generated internal RuntimeMethodInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) { Contract.Ensures(!m_handle.IsNull()); Contract.Assert(!handle.IsNullHandle()); Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_keepalive = keepalive; m_handle = handle.Value; m_reflectedTypeCache = reflectedTypeCache; m_methodAttributes = methodAttributes; } #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 RemotingMethodCachedData m_cachedData; internal RemotingMethodCachedData 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. RemotingMethodCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingMethodCachedData(this); RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region Private Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeMethodHandleInternal(m_handle); } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } [System.Security.SecurityCritical] // auto-generated private ParameterInfo[] FetchNonReturnParameters() { if (m_parameters == null) m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); return m_parameters; } [System.Security.SecurityCritical] // auto-generated private ParameterInfo FetchReturnParameter() { if (m_returnParameter == null) m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature); return m_returnParameter; } #endregion #region Internal Members internal override string FormatNameAndSig(bool serialization) { // Serialization uses ToString to resolve MethodInfo overloads. StringBuilder sbName = new StringBuilder(Name); // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads. // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString(). TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic; if (IsGenericMethod) sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format)); sbName.Append("("); sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); sbName.Append(")"); return sbName.ToString(); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimeMethodInfo m = o as RuntimeMethodInfo; if ((object)m == null) return false; return m.m_handle == m_handle; } internal Signature Signature { get { if (m_signature == null) m_signature = new Signature(this, m_declaringType); return m_signature; } } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types internal RuntimeMethodHandle GetMethodHandle() { return new RuntimeMethodHandle(this); } [System.Security.SecuritySafeCritical] // auto-generated internal RuntimeMethodInfo GetParentDefinition() { if (!IsVirtual || m_declaringType.IsInterface) return null; RuntimeType parent = (RuntimeType)m_declaringType.BaseType; if (parent == null) return null; int slot = RuntimeMethodHandle.GetSlot(this); if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot) return null; return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); } // Unlike DeclaringType, this will return a valid type even for global methods internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } #endregion #region Object Overrides public override String ToString() { if (m_toString == null) m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig(); return m_toString; } public override int GetHashCode() { // See RuntimeMethodInfo.Equals() below. if (IsGenericMethod) return ValueType.GetHashCodeOfPtr(m_handle); else return base.GetHashCode(); } [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(object obj) { if (!IsGenericMethod) return obj == (object)this; // We cannot do simple object identity comparisons for generic methods. // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo() // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable. RuntimeMethodInfo mi = obj as RuntimeMethodInfo; if (mi == null || !mi.IsGenericMethod) return false; // now we know that both operands are generic methods IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this); IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi); if (handle1.Value.Value != handle2.Value.Value) return false; Type[] lhs = GetGenericArguments(); Type[] rhs = mi.GetGenericArguments(); if (lhs.Length != rhs.Length) return false; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != rhs[i]) return false; } if (DeclaringType != mi.DeclaringType) return false; if (ReflectedType != mi.ReflectedType) return false; return true; } #endregion #region ICustomAttributeProvider [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit); } [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = RuntimeMethodHandle.GetName(this); return m_name; } } public override Type DeclaringType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_declaringType; } } public override Type ReflectedType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_reflectedTypeCache.GetRuntimeType(); } } public override MemberTypes MemberType { get { return MemberTypes.Method; } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } public override bool IsSecurityCritical { get { return RuntimeMethodHandle.IsSecurityCritical(this); } } public override bool IsSecuritySafeCritical { get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); } } public override bool IsSecurityTransparent { get { return RuntimeMethodHandle.IsSecurityTransparent(this); } } #endregion #region MethodBase Overrides [System.Security.SecuritySafeCritical] // auto-generated internal override ParameterInfo[] GetParametersNoCopy() { FetchNonReturnParameters(); return m_parameters; } [System.Security.SecuritySafeCritical] // auto-generated [System.Diagnostics.Contracts.Pure] public override ParameterInfo[] GetParameters() { FetchNonReturnParameters(); if (m_parameters.Length == 0) return m_parameters; ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; Array.Copy(m_parameters, ret, m_parameters.Length); return ret; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } internal bool IsOverloaded { get { return m_reflectedTypeCache.GetMethodList(MemberListType.CaseSensitive, Name).Length > 1; } } public override RuntimeMethodHandle MethodHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeMethodHandle(this); } } public override MethodAttributes Attributes { get { return m_methodAttributes; } } public override CallingConventions CallingConvention { get { return Signature.CallingConvention; } } [System.Security.SecuritySafeCritical] // overrides SafeCritical member #if !FEATURE_CORECLR #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 #endif public override MethodBody GetMethodBody() { MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb.m_methodBase = this; return mb; } #endregion #region Invocation Logic(On MemberBase) private void CheckConsistency(Object target) { // only test instance methods if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) { if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); else throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); } } } [System.Security.SecuritySafeCritical] private void ThrowNoInvokeException() { // method is ReflectionOnly Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) { throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); } // method is on a class that contains stack pointers else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0) { throw new NotSupportedException(); } // method is vararg else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(); } // method is generic or on a generic class else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam")); } // method is abstract class else if (IsAbstract) { throw new MemberAccessException(); } // ByRef return are not allowed in reflection else if (ReturnType.IsByRef) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn")); } throw new TargetException(); } [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); #region Security Check INVOCATION_FLAGS invocationFlags = InvocationFlags; #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif #if !FEATURE_CORECLR if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) { if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags); } #endif // !FEATURE_CORECLR #endregion return UnsafeInvokeInternal(obj, parameters, arguments); } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); return UnsafeInvokeInternal(obj, parameters, arguments); } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) { if (arguments == null || arguments.Length == 0) return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false); else { Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { Signature sig = Signature; // get the signature int formalCount = sig.Arguments.Length; int actualCount = (parameters != null) ? parameters.Length : 0; INVOCATION_FLAGS invocationFlags = InvocationFlags; // INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type) // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) ThrowNoInvokeException(); // check basic method consistency. This call will throw if there are problems in the target/method relationship CheckConsistency(obj); if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); if (actualCount != 0) return CheckArguments(parameters, binder, invokeAttr, culture, sig); else return null; } #endregion #region MethodInfo Overrides public override Type ReturnType { get { return Signature.ReturnType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return ReturnParameter; } } public override ParameterInfo ReturnParameter { [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(m_returnParameter != null); FetchReturnParameter(); return m_returnParameter as ParameterInfo; } } [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo GetBaseDefinition() { if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) return this; int slot = RuntimeMethodHandle.GetSlot(this); RuntimeType declaringType = (RuntimeType)DeclaringType; RuntimeType baseDeclaringType = declaringType; RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal(); do { int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType); if (cVtblSlots <= slot) break; baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot); baseDeclaringType = declaringType; declaringType = (RuntimeType)declaringType.BaseType; } while (declaringType != null); return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); } [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodInfo to // open delegates only for backwards compatibility. But we'll allow // relaxed signature checking and open static delegates because // there's no ambiguity there (the caller would have to explicitly // pass us a static method or a method with a non-exact signature // and the only change in behavior from v1.1 there is that we won't // fail the call). return CreateDelegateInternal( delegateType, null, DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, ref stackMark); } [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType, Object target) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API is new in Whidbey and allows the full range of delegate // flexability (open or closed delegates binding to static or // instance methods with relaxed signature checking). The delegate // can also be closed over null. There's no ambiguity with all these // options since the caller is providing us a specific MethodInfo. return CreateDelegateInternal( delegateType, target, DelegateBindingFlags.RelaxedSignature, ref stackMark); } [System.Security.SecurityCritical] private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark) { // Validate the parameters. if (delegateType == null) throw new ArgumentNullException("delegateType"); Contract.EndContractBlock(); RuntimeType rtType = delegateType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "delegateType"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "delegateType"); Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark); if (d == null) { throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); } return d; } #endregion #region Generics [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) throw new ArgumentNullException("methodInstantiation"); Contract.EndContractBlock(); RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; if (!IsGenericMethodDefinition) throw new InvalidOperationException( Environment.GetResourceString("Arg_NotGenericMethodDefinition", this)); for (int i = 0; i < methodInstantiation.Length; i++) { Type methodInstantiationElem = methodInstantiation[i]; if (methodInstantiationElem == null) throw new ArgumentNullException(); RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; if (rtMethodInstantiationElem == null) { Type[] methodInstantiationCopy = new Type[methodInstantiation.Length]; for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++) methodInstantiationCopy[iCopy] = methodInstantiation[iCopy]; methodInstantiation = methodInstantiationCopy; return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation); } methodInstantionRuntimeType[i] = rtMethodInstantiationElem; } RuntimeType[] genericParameters = GetGenericArgumentsInternal(); RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters); MethodInfo ret = null; try { ret = RuntimeType.GetMethodBase(ReflectedTypeInternal, RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(this.m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo; } catch (VerificationException e) { RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e); throw; } return ret; } internal RuntimeType[] GetGenericArgumentsInternal() { return RuntimeMethodHandle.GetMethodInstantiationInternal(this); } public override Type[] GetGenericArguments() { Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this); if (types == null) { types = EmptyArray<Type>.Value; } return types; } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); Contract.EndContractBlock(); return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; } public override bool IsGenericMethod { get { return RuntimeMethodHandle.HasMethodInstantiation(this); } } public override bool IsGenericMethodDefinition { get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); } } public override bool ContainsGenericParameters { get { if (DeclaringType != null && DeclaringType.ContainsGenericParameters) return true; if (!IsGenericMethod) return false; Type[] pis = GetGenericArguments(); for (int i = 0; i < pis.Length; i++) { if (pis[i].ContainsGenericParameters) return true; } return false; } } #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); if (m_reflectedTypeCache.IsGlobal) throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization")); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), SerializationToString(), MemberTypes.Method, IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null); } internal string SerializationToString() { return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true); } #endregion #region Legacy Internal internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) { IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); if (method == null) return null; return RuntimeType.GetMethodBase(method); } #endregion } }
/* * Muhimbi PDF * * Convert, Merge, Watermark, Secure and OCR files. * * OpenAPI spec version: 9.15 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Muhimbi.PDF.Online.Client.Client; using Muhimbi.PDF.Online.Client.Model; namespace Muhimbi.PDF.Online.Client.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface ISecureApi : IApiAccessor { #region Synchronous Operations /// <summary> /// /// </summary> /// <remarks> /// Secure document. Apply security and encryption settings to PDF and Office documents. /// </remarks> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>OperationResponse</returns> OperationResponse SecureDocument (SecureDocumentData inputData); /// <summary> /// /// </summary> /// <remarks> /// Secure document. Apply security and encryption settings to PDF and Office documents. /// </remarks> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>ApiResponse of OperationResponse</returns> ApiResponse<OperationResponse> SecureDocumentWithHttpInfo (SecureDocumentData inputData); /// <summary> /// Secure document /// </summary> /// <remarks> /// Apply security and encryption settings. /// </remarks> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>OperationResponse</returns> OperationResponse SecurePdf (SecurePdfData inputData); /// <summary> /// Secure document /// </summary> /// <remarks> /// Apply security and encryption settings. /// </remarks> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>ApiResponse of OperationResponse</returns> ApiResponse<OperationResponse> SecurePdfWithHttpInfo (SecurePdfData inputData); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// /// </summary> /// <remarks> /// Secure document. Apply security and encryption settings to PDF and Office documents. /// </remarks> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>Task of OperationResponse</returns> System.Threading.Tasks.Task<OperationResponse> SecureDocumentAsync (SecureDocumentData inputData); /// <summary> /// /// </summary> /// <remarks> /// Secure document. Apply security and encryption settings to PDF and Office documents. /// </remarks> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>Task of ApiResponse (OperationResponse)</returns> System.Threading.Tasks.Task<ApiResponse<OperationResponse>> SecureDocumentAsyncWithHttpInfo (SecureDocumentData inputData); /// <summary> /// Secure document /// </summary> /// <remarks> /// Apply security and encryption settings. /// </remarks> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>Task of OperationResponse</returns> System.Threading.Tasks.Task<OperationResponse> SecurePdfAsync (SecurePdfData inputData); /// <summary> /// Secure document /// </summary> /// <remarks> /// Apply security and encryption settings. /// </remarks> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>Task of ApiResponse (OperationResponse)</returns> System.Threading.Tasks.Task<ApiResponse<OperationResponse>> SecurePdfAsyncWithHttpInfo (SecurePdfData inputData); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class SecureApi : ISecureApi { private Muhimbi.PDF.Online.Client.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="SecureApi"/> class. /// </summary> /// <returns></returns> public SecureApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Muhimbi.PDF.Online.Client.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="SecureApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public SecureApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Muhimbi.PDF.Online.Client.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Muhimbi.PDF.Online.Client.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Secure document. Apply security and encryption settings to PDF and Office documents. /// </summary> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>OperationResponse</returns> public OperationResponse SecureDocument (SecureDocumentData inputData) { ApiResponse<OperationResponse> localVarResponse = SecureDocumentWithHttpInfo(inputData); return localVarResponse.Data; } /// <summary> /// Secure document. Apply security and encryption settings to PDF and Office documents. /// </summary> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>ApiResponse of OperationResponse</returns> public ApiResponse< OperationResponse > SecureDocumentWithHttpInfo (SecureDocumentData inputData) { // verify the required parameter 'inputData' is set if (inputData == null) throw new ApiException(400, "Missing required parameter 'inputData' when calling SecureApi->SecureDocument"); var localVarPath = "/v1/operations/secure_document"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (inputData != null && inputData.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter } else { localVarPostBody = inputData; // byte array } // authentication (oauth2_auth) required // oauth required if (!String.IsNullOrEmpty(Configuration.AccessToken)) { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key"))) { localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("SecureDocument", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OperationResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperationResponse))); } /// <summary> /// Secure document. Apply security and encryption settings to PDF and Office documents. /// </summary> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>Task of OperationResponse</returns> public async System.Threading.Tasks.Task<OperationResponse> SecureDocumentAsync (SecureDocumentData inputData) { ApiResponse<OperationResponse> localVarResponse = await SecureDocumentAsyncWithHttpInfo(inputData); return localVarResponse.Data; } /// <summary> /// Secure document. Apply security and encryption settings to PDF and Office documents. /// </summary> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>Task of ApiResponse (OperationResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<OperationResponse>> SecureDocumentAsyncWithHttpInfo (SecureDocumentData inputData) { // verify the required parameter 'inputData' is set if (inputData == null) throw new ApiException(400, "Missing required parameter 'inputData' when calling SecureApi->SecureDocument"); var localVarPath = "/v1/operations/secure_document"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (inputData != null && inputData.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter } else { localVarPostBody = inputData; // byte array } // authentication (oauth2_auth) required // oauth required if (!String.IsNullOrEmpty(Configuration.AccessToken)) { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key"))) { localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("SecureDocument", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OperationResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperationResponse))); } /// <summary> /// Secure document Apply security and encryption settings. /// </summary> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>OperationResponse</returns> public OperationResponse SecurePdf (SecurePdfData inputData) { ApiResponse<OperationResponse> localVarResponse = SecurePdfWithHttpInfo(inputData); return localVarResponse.Data; } /// <summary> /// Secure document Apply security and encryption settings. /// </summary> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>ApiResponse of OperationResponse</returns> public ApiResponse< OperationResponse > SecurePdfWithHttpInfo (SecurePdfData inputData) { // verify the required parameter 'inputData' is set if (inputData == null) throw new ApiException(400, "Missing required parameter 'inputData' when calling SecureApi->SecurePdf"); var localVarPath = "/v1/operations/secure_pdf"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (inputData != null && inputData.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter } else { localVarPostBody = inputData; // byte array } // authentication (oauth2_auth) required // oauth required if (!String.IsNullOrEmpty(Configuration.AccessToken)) { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key"))) { localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("SecurePdf", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OperationResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperationResponse))); } /// <summary> /// Secure document Apply security and encryption settings. /// </summary> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>Task of OperationResponse</returns> public async System.Threading.Tasks.Task<OperationResponse> SecurePdfAsync (SecurePdfData inputData) { ApiResponse<OperationResponse> localVarResponse = await SecurePdfAsyncWithHttpInfo(inputData); return localVarResponse.Data; } /// <summary> /// Secure document Apply security and encryption settings. /// </summary> /// <exception cref="Muhimbi.PDF.Online.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="inputData"></param> /// <returns>Task of ApiResponse (OperationResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<OperationResponse>> SecurePdfAsyncWithHttpInfo (SecurePdfData inputData) { // verify the required parameter 'inputData' is set if (inputData == null) throw new ApiException(400, "Missing required parameter 'inputData' when calling SecureApi->SecurePdf"); var localVarPath = "/v1/operations/secure_pdf"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (inputData != null && inputData.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(inputData); // http body (model) parameter } else { localVarPostBody = inputData; // byte array } // authentication (oauth2_auth) required // oauth required if (!String.IsNullOrEmpty(Configuration.AccessToken)) { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key"))) { localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("SecurePdf", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OperationResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OperationResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperationResponse))); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace BuildIt.CognitiveServices { using System.Threading.Tasks; using Models; /// <summary> /// Extension methods for AzureMachineLearningTextAnalytics. /// </summary> public static partial class AzureMachineLearningTextAnalyticsExtensions { /// <summary> /// The API returns a list of strings denoting the key talking points in the /// input text. /// We employ techniques from Microsoft Office's sophisticated /// Natural Language Processing toolkit. /// Currently, the following languages are supported: English, /// German, Spanish and Japanese. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='multiLanguageBatchInputV2'> /// </param> public static object KeyPhrases(this IAzureMachineLearningTextAnalytics operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), MultiLanguageBatchInputV2 multiLanguageBatchInputV2 = default(MultiLanguageBatchInputV2)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAzureMachineLearningTextAnalytics)s).KeyPhrasesAsync(subscriptionKey, ocpApimSubscriptionKey, multiLanguageBatchInputV2), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The API returns a list of strings denoting the key talking points in the /// input text. /// We employ techniques from Microsoft Office's sophisticated /// Natural Language Processing toolkit. /// Currently, the following languages are supported: English, /// German, Spanish and Japanese. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='multiLanguageBatchInputV2'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<object> KeyPhrasesAsync(this IAzureMachineLearningTextAnalytics operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), MultiLanguageBatchInputV2 multiLanguageBatchInputV2 = default(MultiLanguageBatchInputV2), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.KeyPhrasesWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, multiLanguageBatchInputV2, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The API returns the detected language and a numeric score between 0 and 1. /// /// Scores close to 1 indicate 100% certainty that the identified /// language is true. /// A total of 120 languages are supported. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberOfLanguagesToDetect'> /// Format - int32. (Optional) Number of languages to detect. Set to 1 by /// default. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='batchInputV2'> /// </param> public static object DetectLanguage(this IAzureMachineLearningTextAnalytics operations, int? numberOfLanguagesToDetect = default(int?), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), BatchInputV2 batchInputV2 = default(BatchInputV2)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAzureMachineLearningTextAnalytics)s).DetectLanguageAsync(numberOfLanguagesToDetect, subscriptionKey, ocpApimSubscriptionKey, batchInputV2), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The API returns the detected language and a numeric score between 0 and 1. /// /// Scores close to 1 indicate 100% certainty that the identified /// language is true. /// A total of 120 languages are supported. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='numberOfLanguagesToDetect'> /// Format - int32. (Optional) Number of languages to detect. Set to 1 by /// default. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='batchInputV2'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<object> DetectLanguageAsync(this IAzureMachineLearningTextAnalytics operations, int? numberOfLanguagesToDetect = default(int?), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), BatchInputV2 batchInputV2 = default(BatchInputV2), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.DetectLanguageWithHttpMessagesAsync(numberOfLanguagesToDetect, subscriptionKey, ocpApimSubscriptionKey, batchInputV2, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get the status of an operation submitted for processing. If the the /// operation has reached a 'Succeeded' state, will also return the result. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='operationId'> /// A unique id for the submitted operation. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> public static object OperationStatus(this IAzureMachineLearningTextAnalytics operations, string operationId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAzureMachineLearningTextAnalytics)s).OperationStatusAsync(operationId, subscriptionKey, ocpApimSubscriptionKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the status of an operation submitted for processing. If the the /// operation has reached a 'Succeeded' state, will also return the result. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='operationId'> /// A unique id for the submitted operation. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<object> OperationStatusAsync(this IAzureMachineLearningTextAnalytics operations, string operationId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.OperationStatusWithHttpMessagesAsync(operationId, subscriptionKey, ocpApimSubscriptionKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The API returns a numeric score between 0 and 1. /// Scores close to 1 indicate positive sentiment, while scores /// close to 0 indicate negative sentiment. /// Sentiment score is generated using classification techniques. /// The input features to the classifier include n-grams, features /// generated from part-of-speech tags, and word embeddings. /// Currently, the following languages are supported: English, /// Spanish, French, Portuguese. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='multiLanguageBatchInputV2'> /// </param> public static object Sentiment(this IAzureMachineLearningTextAnalytics operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), MultiLanguageBatchInputV2 multiLanguageBatchInputV2 = default(MultiLanguageBatchInputV2)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAzureMachineLearningTextAnalytics)s).SentimentAsync(subscriptionKey, ocpApimSubscriptionKey, multiLanguageBatchInputV2), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The API returns a numeric score between 0 and 1. /// Scores close to 1 indicate positive sentiment, while scores /// close to 0 indicate negative sentiment. /// Sentiment score is generated using classification techniques. /// The input features to the classifier include n-grams, features /// generated from part-of-speech tags, and word embeddings. /// Currently, the following languages are supported: English, /// Spanish, French, Portuguese. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='multiLanguageBatchInputV2'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<object> SentimentAsync(this IAzureMachineLearningTextAnalytics operations, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), MultiLanguageBatchInputV2 multiLanguageBatchInputV2 = default(MultiLanguageBatchInputV2), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.SentimentWithHttpMessagesAsync(subscriptionKey, ocpApimSubscriptionKey, multiLanguageBatchInputV2, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The API returns the top detected topics for a list of submitted text /// documents. /// A topic is identified with a key phrase, which can be one or /// more related words. /// Use the URL parameters and stop word list to control which /// words or documents are filtered out. /// You can also supply a list of topics to exclude from the /// response. /// At least 100 text documents must be submitted, however it is /// designed to detect topics across hundreds to thousands of documents. /// Note that one transaction is charged per text document /// submitted. /// For best performance, limit each document to a short, human /// written text paragraph such as review, conversation or user feedback. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='minDocumentsPerWord'> /// Format - int32. (optional) Words that occur in less than this many /// documents are ignored. /// Use this parameter to help exclude rare document topics. /// Omit to let the service choose appropriate value. /// </param> /// <param name='maxDocumentsPerWord'> /// Format - int32. (optional) Words that occur in more than this many /// documents are ignored. /// Use this parameter to help exclude ubiquitous document topics. /// Omit to let the service choose appropriate value. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='topicDetectionInputV2'> /// </param> public static ErrorResponse DetectTopics(this IAzureMachineLearningTextAnalytics operations, int? minDocumentsPerWord = default(int?), int? maxDocumentsPerWord = default(int?), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), TopicDetectionInputV2 topicDetectionInputV2 = default(TopicDetectionInputV2)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAzureMachineLearningTextAnalytics)s).DetectTopicsAsync(minDocumentsPerWord, maxDocumentsPerWord, subscriptionKey, ocpApimSubscriptionKey, topicDetectionInputV2), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The API returns the top detected topics for a list of submitted text /// documents. /// A topic is identified with a key phrase, which can be one or /// more related words. /// Use the URL parameters and stop word list to control which /// words or documents are filtered out. /// You can also supply a list of topics to exclude from the /// response. /// At least 100 text documents must be submitted, however it is /// designed to detect topics across hundreds to thousands of documents. /// Note that one transaction is charged per text document /// submitted. /// For best performance, limit each document to a short, human /// written text paragraph such as review, conversation or user feedback. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='minDocumentsPerWord'> /// Format - int32. (optional) Words that occur in less than this many /// documents are ignored. /// Use this parameter to help exclude rare document topics. /// Omit to let the service choose appropriate value. /// </param> /// <param name='maxDocumentsPerWord'> /// Format - int32. (optional) Words that occur in more than this many /// documents are ignored. /// Use this parameter to help exclude ubiquitous document topics. /// Omit to let the service choose appropriate value. /// </param> /// <param name='subscriptionKey'> /// subscription key in url /// </param> /// <param name='ocpApimSubscriptionKey'> /// subscription key in header /// </param> /// <param name='topicDetectionInputV2'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ErrorResponse> DetectTopicsAsync(this IAzureMachineLearningTextAnalytics operations, int? minDocumentsPerWord = default(int?), int? maxDocumentsPerWord = default(int?), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), TopicDetectionInputV2 topicDetectionInputV2 = default(TopicDetectionInputV2), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.DetectTopicsWithHttpMessagesAsync(minDocumentsPerWord, maxDocumentsPerWord, subscriptionKey, ocpApimSubscriptionKey, topicDetectionInputV2, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents an operation between an expression and a type. /// </summary> [DebuggerTypeProxy(typeof(Expression.TypeBinaryExpressionProxy))] public sealed class TypeBinaryExpression : Expression { private readonly Expression _expression; private readonly Type _typeOperand; private readonly ExpressionType _nodeKind; internal TypeBinaryExpression(Expression expression, Type typeOperand, ExpressionType nodeKind) { _expression = expression; _typeOperand = typeOperand; _nodeKind = nodeKind; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return typeof(bool); } } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return _nodeKind; } } /// <summary> /// Gets the expression operand of a type test operation. /// </summary> public Expression Expression { get { return _expression; } } /// <summary> /// Gets the type operand of a type test operation. /// </summary> public Type TypeOperand { get { return _typeOperand; } } #region Reduce TypeEqual internal Expression ReduceTypeEqual() { Type cType = Expression.Type; // For value types (including Void, but not nullables), we can // determine the result now if (cType.GetTypeInfo().IsValueType && !cType.IsNullableType()) { return Expression.Block(Expression, Expression.Constant(cType == _typeOperand.GetNonNullableType())); } // Can check the value right now for constants. if (Expression.NodeType == ExpressionType.Constant) { return ReduceConstantTypeEqual(); } // If the expression type is a sealed reference type or a nullable // type, it will match if the value is not null and the type operand // either matches or one is a nullable type while the other is its // type argument (T to the other's T?). if (cType.GetTypeInfo().IsSealed) { if (cType.GetNonNullableType() != _typeOperand.GetNonNullableType()) { return Expression.Block(Expression, Expression.Constant(false)); } else if (cType.IsNullableType()) { return Expression.NotEqual(Expression, Expression.Constant(null, Expression.Type)); } else { return Expression.ReferenceNotEqual(Expression, Expression.Constant(null, Expression.Type)); } } Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(object), Expression.Type), "Expecting reference types only after this point."); // expression is a ByVal parameter. Can safely reevaluate. var parameter = Expression as ParameterExpression; if (parameter != null && !parameter.IsByRef) { return ByValParameterTypeEqual(parameter); } // Create a temp so we only evaluate the left side once parameter = Expression.Parameter(typeof(object)); return Expression.Block( new[] { parameter }, Expression.Assign(parameter, Expression), ByValParameterTypeEqual(parameter) ); } // Helper that is used when re-eval of LHS is safe. private Expression ByValParameterTypeEqual(ParameterExpression value) { Expression getType = Expression.Call(value, typeof(object).GetMethod("GetType")); // In remoting scenarios, obj.GetType() can return an interface. // But JIT32's optimized "obj.GetType() == typeof(ISomething)" codegen, // causing it to always return false. // We workaround this optimization by generating different, less optimal IL // if TypeOperand is an interface. if (_typeOperand.GetTypeInfo().IsInterface) { var temp = Expression.Parameter(typeof(Type)); getType = Expression.Block(new[] { temp }, Expression.Assign(temp, getType), temp); } // We use reference equality when comparing to null for correctness // (don't invoke a user defined operator), and reference equality // on types for performance (so the JIT can optimize the IL). return Expression.AndAlso( Expression.ReferenceNotEqual(value, Expression.Constant(null)), Expression.ReferenceEqual( getType, Expression.Constant(_typeOperand.GetNonNullableType(), typeof(Type)) ) ); } private Expression ReduceConstantTypeEqual() { ConstantExpression ce = Expression as ConstantExpression; //TypeEqual(null, T) always returns false. if (ce.Value == null) { return Expression.Constant(false); } else { return Expression.Constant(_typeOperand.GetNonNullableType() == ce.Value.GetType()); } } #endregion /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitTypeBinary(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expression">The <see cref="Expression" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public TypeBinaryExpression Update(Expression expression) { if (expression == Expression) { return this; } if (NodeType == ExpressionType.TypeIs) { return Expression.TypeIs(expression, TypeOperand); } return Expression.TypeEqual(expression, TypeOperand); } } public partial class Expression { /// <summary> /// Creates a <see cref="TypeBinaryExpression"/>. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeIs"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeIs(Expression expression, Type type) { RequiresCanRead(expression, "expression"); ContractUtils.RequiresNotNull(type, "type"); if (type.IsByRef) throw Error.TypeMustNotBeByRef(); return new TypeBinaryExpression(expression, type, ExpressionType.TypeIs); } /// <summary> /// Creates a <see cref="TypeBinaryExpression"/> that compares run-time type identity. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeEqual"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeEqual(Expression expression, Type type) { RequiresCanRead(expression, "expression"); ContractUtils.RequiresNotNull(type, "type"); if (type.IsByRef) throw Error.TypeMustNotBeByRef(); return new TypeBinaryExpression(expression, type, ExpressionType.TypeEqual); } } }
namespace Cronofy { /// <summary> /// Class for providing URLs. /// </summary> public sealed class UrlProvider { /// <summary> /// The URL format of the OAuth authorization endpoint. /// </summary> private const string AuthorizationUrlFormat = "https://app{0}.cronofy.com/oauth/authorize"; /// <summary> /// The URL format of the Enterprise Connect OAuth authorization endpoint. /// </summary> private const string EnterpriseConnectAuthorizationUrlFormat = "https://app{0}.cronofy.com/enterprise_connect/oauth/authorize"; /// <summary> /// The URL format of the OAuth token endpoint. /// </summary> private const string TokenUrlFormat = "https://app{0}.cronofy.com/oauth/token"; /// <summary> /// The URL format of the OAuth token revocation endpoint. /// </summary> private const string TokenRevocationUrlFormat = "https://app{0}.cronofy.com/oauth/token/revoke"; /// <summary> /// The URL format of the user info endpoint. /// </summary> private const string UserInfoUrlFormat = "https://api{0}.cronofy.com/v1/userinfo"; /// <summary> /// The URL format of the resources endpoint. /// </summary> private const string ResourcesUrlFormat = "https://api{0}.cronofy.com/v1/resources"; /// <summary> /// The URL format of the service account user authorization endpoint. /// </summary> private const string AuthorizeWithServiceAccountUrlFormat = "https://api{0}.cronofy.com/v1/service_account_authorizations"; /// <summary> /// The URL of the account endpoint. /// </summary> private const string AccountUrlFormat = "https://api{0}.cronofy.com/v1/account"; /// <summary> /// The URL of the profiles endpoint. /// </summary> private const string ProfilesUrlFormat = "https://api{0}.cronofy.com/v1/profiles"; /// <summary> /// The URL of the list calendars endpoint. /// </summary> private const string CalendarsUrlFormat = "https://api{0}.cronofy.com/v1/calendars"; /// <summary> /// The URL of the free-busy endpoint. /// </summary> private const string FreeBusyUrlFormat = "https://api{0}.cronofy.com/v1/free_busy"; /// <summary> /// The URL of the read events endpoint. /// </summary> private const string EventsUrlFormat = "https://api{0}.cronofy.com/v1/events"; /// <summary> /// The URL format for the managed event endpoint. /// </summary> private const string ManagedEventUrlFormatFormat = "https://api{0}.cronofy.com/v1/calendars/{{0}}/events"; /// <summary> /// The URL format for the participation status endpoint. /// </summary> private const string ParticipationStatusUrlFormatFormat = "https://api{0}.cronofy.com/v1/calendars/{{0}}/events/{{1}}/participation_status"; /// <summary> /// The URL of the channels endpoint. /// </summary> private const string ChannelsUrlFormat = "https://api{0}.cronofy.com/v1/channels"; /// <summary> /// The URL format for the channel endpoint. /// </summary> private const string ChannelUrlFormatFormat = "https://api{0}.cronofy.com/v1/channels/{{0}}"; /// <summary> /// The URL format for the elevated permissions endpoint. /// </summary> private const string PermissionsUrlFormat = "https://api{0}.cronofy.com/v1/permissions"; /// <summary> /// The URL of the availability endpoint. /// </summary> private const string AvailabilityUrlFormat = "https://api{0}.cronofy.com/v1/availability"; /// <summary> /// The URL for the add to calendar endpoint. /// </summary> private const string AddToCalendarUrlFormat = "https://api{0}.cronofy.com/v1/add_to_calendar"; /// <summary> /// The URL for the real time scheduling endpoint. /// </summary> private const string RealTimeSchedulingUrlFormat = "https://api{0}.cronofy.com/v1/real_time_scheduling"; /// <summary> /// The URL for the real time scheduling endpoint. /// </summary> private const string RealTimeSchedulingByIdUrlFormat = "https://api{0}.cronofy.com/v1/real_time_scheduling/{{0}}"; /// <summary> /// The URL format for the real time scheduling disable endpoint. /// </summary> private const string DisableRealTimeSchedulingUrlFormatFormat = "https://api{0}.cronofy.com/v1/real_time_scheduling/{{0}}/disable"; /// <summary> /// The URL of the link tokens endpoint. /// </summary> private const string LinkTokensUrlFormat = "https://api{0}.cronofy.com/v1/link_tokens"; /// <summary> /// The URL of the revoke profile authorization endpoint. /// </summary> private const string RevokeProfileAuthorizationUrlFormatFormat = "https://api{0}.cronofy.com/v1/profiles/{{0}}/revoke"; /// <summary> /// The URL of the Smart Invite endpoint. /// </summary> private const string SmartInviteUrlFormat = "https://api{0}.cronofy.com/v1/smart_invites"; /// <summary> /// The URL of the batch request endpoint. /// </summary> private const string BatchUrlFormat = "https://api{0}.cronofy.com/v1/batch"; /// <summary> /// The URL of the application calendars endpoint. /// </summary> private const string ApplicationCalendarsUrlFormat = "https://api{0}.cronofy.com/v1/application_calendars"; /// <summary> /// The URL of the real time sequencing endpoint. /// </summary> private const string RealTimeSequencingFormat = "https://api{0}.cronofy.com/v1/real_time_sequencing"; /// <summary> /// The URL of the sequenced availability endpoint. /// </summary> private const string SequencedAvailablityFormat = "https://api{0}.cronofy.com/v1/sequenced_availability"; /// <summary> /// The URL of the application verification submission endpoint. /// </summary> private const string ApplicationVerificationUrlFormat = "https://api{0}.cronofy.com/v1/application_verification"; /// <summary> /// The URL of the application provisioning endpoint. /// </summary> private const string ProvisionApplicationUrlFormat = "https://api{0}.cronofy.com/v1/applications"; /// <summary> /// The URL of the Element Tokens endpoint. /// </summary> private const string ElementTokensUrlFormat = "https://api{0}.cronofy.com/v1/element_tokens"; /// <summary> /// The URL of the Conferencing Services Authorization endpoint. /// </summary> private const string ConferencingServiceAuthorizationUrlFormat = "https://api{0}.cronofy.com/v1/conferencing_service_authorizations"; /// <summary> /// Initializes a new instance of the <see cref="UrlProvider"/> class. /// </summary> /// <param name="dataCenter"> /// The data center the <see cref="UrlProvider"/> is for. /// </param> internal UrlProvider(string dataCenter) { string suffix = string.Empty; if (dataCenter != string.Empty) { suffix = "-" + dataCenter; } this.AuthorizationUrl = string.Format(AuthorizationUrlFormat, suffix); this.EnterpriseConnectAuthorizationUrl = string.Format(EnterpriseConnectAuthorizationUrlFormat, suffix); this.TokenUrl = string.Format(TokenUrlFormat, suffix); this.TokenRevocationUrl = string.Format(TokenRevocationUrlFormat, suffix); this.UserInfoUrl = string.Format(UserInfoUrlFormat, suffix); this.ResourcesUrl = string.Format(ResourcesUrlFormat, suffix); this.AuthorizeWithServiceAccountUrl = string.Format(AuthorizeWithServiceAccountUrlFormat, suffix); this.AccountUrl = string.Format(AccountUrlFormat, suffix); this.ProfilesUrl = string.Format(ProfilesUrlFormat, suffix); this.CalendarsUrl = string.Format(CalendarsUrlFormat, suffix); this.FreeBusyUrl = string.Format(FreeBusyUrlFormat, suffix); this.EventsUrl = string.Format(EventsUrlFormat, suffix); this.ManagedEventUrlFormat = string.Format(ManagedEventUrlFormatFormat, suffix); this.ParticipationStatusUrlFormat = string.Format(ParticipationStatusUrlFormatFormat, suffix); this.ChannelsUrl = string.Format(ChannelsUrlFormat, suffix); this.ChannelUrlFormat = string.Format(ChannelUrlFormatFormat, suffix); this.PermissionsUrl = string.Format(PermissionsUrlFormat, suffix); this.AvailabilityUrl = string.Format(AvailabilityUrlFormat, suffix); this.AddToCalendarUrl = string.Format(AddToCalendarUrlFormat, suffix); this.RealTimeSchedulingUrl = string.Format(RealTimeSchedulingUrlFormat, suffix); this.RealTimeSchedulingByIdUrl = string.Format(RealTimeSchedulingByIdUrlFormat, suffix); this.DisableRealTimeSchedulingUrlFormat = string.Format(DisableRealTimeSchedulingUrlFormatFormat, suffix); this.LinkTokensUrl = string.Format(LinkTokensUrlFormat, suffix); this.SmartInviteUrl = string.Format(SmartInviteUrlFormat, suffix); this.RevokeProfileAuthorizationUrlFormat = string.Format(RevokeProfileAuthorizationUrlFormatFormat, suffix); this.BatchUrl = string.Format(BatchUrlFormat, suffix); this.ApplicationCalendarsUrl = string.Format(ApplicationCalendarsUrlFormat, suffix); this.RealTimeSequencingUrl = string.Format(RealTimeSequencingFormat, suffix); this.SequencedAvailabilityUrl = string.Format(SequencedAvailablityFormat, suffix); this.ApplicationVerificationUrl = string.Format(ApplicationVerificationUrlFormat, suffix); this.ProvisionApplicationUrl = string.Format(ProvisionApplicationUrlFormat, suffix); this.ElementTokensUrl = string.Format(ElementTokensUrlFormat, suffix); this.ConferencingServiceAuthorizationUrl = string.Format(ConferencingServiceAuthorizationUrlFormat, suffix); } /// <summary> /// Gets the authorization URL. /// </summary> /// <value> /// The authorization URL. /// </value> public string AuthorizationUrl { get; private set; } /// <summary> /// Gets the Enterprise Connect authorization URL. /// </summary> /// <value> /// The Enterprise Connect authorization URL. /// </value> public string EnterpriseConnectAuthorizationUrl { get; private set; } /// <summary> /// Gets the OAuth token URL. /// </summary> /// <value> /// The OAuth token URL. /// </value> public string TokenUrl { get; private set; } /// <summary> /// Gets the OAuth token revocation URL. /// </summary> /// <value> /// The OAuth token revocation URL. /// </value> public string TokenRevocationUrl { get; private set; } /// <summary> /// Gets the userinfo URL. /// </summary> /// <value> /// The userinfo URL. /// </value> public string UserInfoUrl { get; private set; } /// <summary> /// Gets the resources URL. /// </summary> /// <value> /// The resources URL. /// </value> public string ResourcesUrl { get; private set; } /// <summary> /// Gets the authorize with service account URL. /// </summary> /// <value> /// The authorize with service account URL. /// </value> public string AuthorizeWithServiceAccountUrl { get; private set; } /// <summary> /// Gets the account URL. /// </summary> /// <value> /// The account URL. /// </value> public string AccountUrl { get; private set; } /// <summary> /// Gets the profiles URL. /// </summary> /// <value> /// The profiles URL. /// </value> public string ProfilesUrl { get; private set; } /// <summary> /// Gets the calendars URL. /// </summary> /// <value> /// The calendars URL. /// </value> public string CalendarsUrl { get; private set; } /// <summary> /// Gets the free busy URL. /// </summary> /// <value> /// The free busy URL. /// </value> public string FreeBusyUrl { get; private set; } /// <summary> /// Gets the events URL. /// </summary> /// <value> /// The events URL. /// </value> public string EventsUrl { get; private set; } /// <summary> /// Gets the managed event URL format. /// </summary> /// <value> /// The managed event URL format. /// </value> public string ManagedEventUrlFormat { get; private set; } /// <summary> /// Gets the participation status URL format. /// </summary> /// <value> /// The participation status URL format. /// </value> public string ParticipationStatusUrlFormat { get; private set; } /// <summary> /// Gets the channels URL. /// </summary> /// <value> /// The channels URL. /// </value> public string ChannelsUrl { get; private set; } /// <summary> /// Gets the channel URL format. /// </summary> /// <value> /// The channel URL format. /// </value> public string ChannelUrlFormat { get; private set; } /// <summary> /// Gets the permissions URL. /// </summary> /// <value> /// The permissions URL. /// </value> public string PermissionsUrl { get; private set; } /// <summary> /// Gets the availability URL. /// </summary> /// <value> /// The availability URL. /// </value> public string AvailabilityUrl { get; private set; } /// <summary> /// Gets the add to calendar URL. /// </summary> /// <value> /// The add to calendar URL. /// </value> public string AddToCalendarUrl { get; private set; } /// <summary> /// Gets the real time scheduling URL. /// </summary> /// <value> /// The real time scheduling URL. /// </value> public string RealTimeSchedulingUrl { get; private set; } /// <summary> /// Gets the real time scheduling by ID URL. /// </summary> /// <value> /// The real time scheduling by ID URL. /// </value> public string RealTimeSchedulingByIdUrl { get; private set; } /// <summary> /// Gets the real time scheduling disable URL format. /// </summary> /// <value> /// The real time scheduling disable URL format. /// </value> public string DisableRealTimeSchedulingUrlFormat { get; private set; } /// <summary> /// Gets the link tokens URL. /// </summary> /// <value> /// The link tokens URL. /// </value> public string LinkTokensUrl { get; private set; } /// <summary> /// Gets the revoke profile authorization URL format. /// </summary> /// <value> /// The revoke profile authorization URL format. /// </value> public string RevokeProfileAuthorizationUrlFormat { get; private set; } /// <summary> /// Gets the Smart Invite URL. /// </summary> /// <value>The Smart Invite url.</value> public string SmartInviteUrl { get; private set; } /// <summary> /// Gets the batch request URL. /// </summary> /// <value> /// The batch request URL. /// </value> public string BatchUrl { get; private set; } /// <summary> /// Gets the application calendars URL. /// </summary> /// <value>The application calendars URL.</value> public string ApplicationCalendarsUrl { get; private set; } /// <summary> /// Gets the real time sequencing URL. /// </summary> /// <value>The real time sequencing URL.</value> public string RealTimeSequencingUrl { get; private set; } /// <summary> /// Gets the sequenced availability URL. /// </summary> /// <value>The sequenced availability URL.</value> public string SequencedAvailabilityUrl { get; private set; } /// <summary> /// Gets the application verification submission URL. /// </summary> /// <value>The application verification submission URL.</value> public string ApplicationVerificationUrl { get; private set; } /// <summary> /// Gets the application provisioning URL. /// </summary> /// <value>The application provisioning URL.</value> public string ProvisionApplicationUrl { get; private set; } /// <summary> /// Gets the element tokens URL. /// </summary> /// <value>The element tokens URL.</value> public string ElementTokensUrl { get; private set; } /// <summary> /// Gets the conferencing service authorization URL. /// </summary> /// <value>The conferencing service authorization URL.</value> public string ConferencingServiceAuthorizationUrl { get; private set; } } }
using System; using System.IO; using System.Security.Cryptography; using ICSharpCode.SharpZipLib.Encryption; namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// A special stream deflating or compressing the bytes that are /// written to it. It uses a Deflater to perform actual deflating.<br/> /// Authors of the original java version : Tom Tromey, Jochen Hoenicke /// </summary> public class DeflaterOutputStream : Stream { #region Constructors /// <summary> /// Creates a new DeflaterOutputStream with a default Deflater and default buffer size. /// </summary> /// <param name="baseOutputStream"> /// the output stream where deflated output should be written. /// </param> public DeflaterOutputStream(Stream baseOutputStream) : this(baseOutputStream, new Deflater(), 512) { } /// <summary> /// Creates a new DeflaterOutputStream with the given Deflater and /// default buffer size. /// </summary> /// <param name="baseOutputStream"> /// the output stream where deflated output should be written. /// </param> /// <param name="deflater"> /// the underlying deflater. /// </param> public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater) : this(baseOutputStream, deflater, 512) { } /// <summary> /// Creates a new DeflaterOutputStream with the given Deflater and /// buffer size. /// </summary> /// <param name="baseOutputStream"> /// The output stream where deflated output is written. /// </param> /// <param name="deflater"> /// The underlying deflater to use /// </param> /// <param name="bufferSize"> /// The buffer size in bytes to use when deflating (minimum value 512) /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// bufsize is less than or equal to zero. /// </exception> /// <exception cref="ArgumentException"> /// baseOutputStream does not support writing /// </exception> /// <exception cref="ArgumentNullException"> /// deflater instance is null /// </exception> public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufferSize) { if (baseOutputStream == null) { throw new ArgumentNullException(nameof(baseOutputStream)); } if (baseOutputStream.CanWrite == false) { throw new ArgumentException("Must support writing", nameof(baseOutputStream)); } if (deflater == null) { throw new ArgumentNullException(nameof(deflater)); } if (bufferSize < 512) { throw new ArgumentOutOfRangeException(nameof(bufferSize)); } baseOutputStream_ = baseOutputStream; buffer_ = new byte[bufferSize]; deflater_ = deflater; } #endregion #region Public API /// <summary> /// Finishes the stream by calling finish() on the deflater. /// </summary> /// <exception cref="SharpZipBaseException"> /// Not all input is deflated /// </exception> public virtual void Finish() { deflater_.Finish(); while (!deflater_.IsFinished) { int len = deflater_.Deflate(buffer_, 0, buffer_.Length); if (len <= 0) { break; } if (cryptoTransform_ != null) { EncryptBlock(buffer_, 0, len); } baseOutputStream_.Write(buffer_, 0, len); } if (!deflater_.IsFinished) { throw new SharpZipBaseException("Can't deflate all input?"); } baseOutputStream_.Flush(); //if (cryptoTransform_ != null) { // if (cryptoTransform_ is ZipAESTransform) { // AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); // } // cryptoTransform_.Dispose(); // cryptoTransform_ = null; //} } /// <summary> /// Gets or sets a flag indicating ownership of underlying stream. /// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also. /// </summary> /// <remarks>The default value is true.</remarks> public bool IsStreamOwner { get; set; } = true; /// <summary> /// Allows client to determine if an entry can be patched after its added /// </summary> public bool CanPatchEntries { get { return baseOutputStream_.CanSeek; } } #endregion #region Encryption string password; ICryptoTransform cryptoTransform_; /// <summary> /// Returns the 10 byte AUTH CODE to be appended immediately following the AES data stream. /// </summary> protected byte[] AESAuthCode; /// <summary> /// Get/set the password used for encryption. /// </summary> /// <remarks>When set to null or if the password is empty no encryption is performed</remarks> public string Password { get { return password; } set { if ((value != null) && (value.Length == 0)) { password = null; } else { password = value; } } } /// <summary> /// Encrypt a block of data /// </summary> /// <param name="buffer"> /// Data to encrypt. NOTE the original contents of the buffer are lost /// </param> /// <param name="offset"> /// Offset of first byte in buffer to encrypt /// </param> /// <param name="length"> /// Number of bytes in buffer to encrypt /// </param> protected void EncryptBlock(byte[] buffer, int offset, int length) { cryptoTransform_.TransformBlock(buffer, 0, length, buffer, 0); } /// <summary> /// Initializes encryption keys based on given <paramref name="password"/>. /// </summary> /// <param name="password">The password.</param> protected void InitializePassword(string password) { var pkManaged = new PkzipClassicManaged(); byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); cryptoTransform_ = pkManaged.CreateEncryptor(key, null); } ///// <summary> ///// Initializes encryption keys based on given password. ///// </summary> //protected void InitializeAESPassword(ZipEntry entry, string rawPassword, // out byte[] salt, out byte[] pwdVerifier) //{ // salt = new byte[entry.AESSaltLen]; // // Salt needs to be cryptographically random, and unique per file // if (_aesRnd == null) // _aesRnd = RandomNumberGenerator.Create(); // _aesRnd.GetBytes(salt); // int blockSize = entry.AESKeySize / 8; // bits to bytes // cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); // pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; //} #endregion #region Deflation Support /// <summary> /// Deflates everything in the input buffers. This will call /// <code>def.deflate()</code> until all bytes from the input buffers /// are processed. /// </summary> protected void Deflate() { while (!deflater_.IsNeedingInput) { int deflateCount = deflater_.Deflate(buffer_, 0, buffer_.Length); if (deflateCount <= 0) { break; } if (cryptoTransform_ != null) { EncryptBlock(buffer_, 0, deflateCount); } baseOutputStream_.Write(buffer_, 0, deflateCount); } if (!deflater_.IsNeedingInput) { throw new SharpZipBaseException("DeflaterOutputStream can't deflate all input?"); } } #endregion #region Stream Overrides /// <summary> /// Gets value indicating stream can be read from /// </summary> public override bool CanRead { get { return false; } } /// <summary> /// Gets a value indicating if seeking is supported for this stream /// This property always returns false /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Get value indicating if this stream supports writing /// </summary> public override bool CanWrite { get { return baseOutputStream_.CanWrite; } } /// <summary> /// Get current length of stream /// </summary> public override long Length { get { return baseOutputStream_.Length; } } /// <summary> /// Gets the current position within the stream. /// </summary> /// <exception cref="NotSupportedException">Any attempt to set position</exception> public override long Position { get { return baseOutputStream_.Position; } set { throw new NotSupportedException("Position property not supported"); } } /// <summary> /// Sets the current position of this stream to the given value. Not supported by this class! /// </summary> /// <param name="offset">The offset relative to the <paramref name="origin"/> to seek.</param> /// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param> /// <returns>The new position in the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("DeflaterOutputStream Seek not supported"); } /// <summary> /// Sets the length of this stream to the given value. Not supported by this class! /// </summary> /// <param name="value">The new stream length.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("DeflaterOutputStream SetLength not supported"); } /// <summary> /// Read a byte from stream advancing position by one /// </summary> /// <returns>The byte read cast to an int. THe value is -1 if at the end of the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override int ReadByte() { throw new NotSupportedException("DeflaterOutputStream ReadByte not supported"); } /// <summary> /// Read a block of bytes from stream /// </summary> /// <param name="buffer">The buffer to store read data in.</param> /// <param name="offset">The offset to start storing at.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The actual number of bytes read. Zero if end of stream is detected.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException("DeflaterOutputStream Read not supported"); } /// <summary> /// Flushes the stream by calling <see cref="DeflaterOutputStream.Flush">Flush</see> on the deflater and then /// on the underlying stream. This ensures that all bytes are flushed. /// </summary> public override void Flush() { deflater_.Flush(); Deflate(); baseOutputStream_.Flush(); } /// <summary> /// Calls <see cref="Finish"/> and closes the underlying /// stream when <see cref="IsStreamOwner"></see> is true. /// </summary> protected override void Dispose(bool disposing) { if (!isClosed_) { isClosed_ = true; try { Finish(); if (cryptoTransform_ != null) { GetAuthCodeIfAES(); cryptoTransform_.Dispose(); cryptoTransform_ = null; } } finally { if (IsStreamOwner) { baseOutputStream_.Dispose(); } } } } private void GetAuthCodeIfAES() { //if (cryptoTransform_ is ZipAESTransform) { // AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); //} } /// <summary> /// Writes a single byte to the compressed output stream. /// </summary> /// <param name="value"> /// The byte value. /// </param> public override void WriteByte(byte value) { byte[] b = new byte[1]; b[0] = value; Write(b, 0, 1); } /// <summary> /// Writes bytes from an array to the compressed stream. /// </summary> /// <param name="buffer"> /// The byte array /// </param> /// <param name="offset"> /// The offset into the byte array where to start. /// </param> /// <param name="count"> /// The number of bytes to write. /// </param> public override void Write(byte[] buffer, int offset, int count) { deflater_.SetInput(buffer, offset, count); Deflate(); } #endregion #region Instance Fields /// <summary> /// This buffer is used temporarily to retrieve the bytes from the /// deflater and write them to the underlying output stream. /// </summary> byte[] buffer_; /// <summary> /// The deflater which is used to deflate the stream. /// </summary> protected Deflater deflater_; /// <summary> /// Base stream the deflater depends on. /// </summary> protected Stream baseOutputStream_; bool isClosed_; #endregion #region Static Fields // Static to help ensure that multiple files within a zip will get different random salt private static RandomNumberGenerator _aesRnd = RandomNumberGenerator.Create(); #endregion } }
using System; using System.Diagnostics; namespace Common { // autogenerated: D:\Scripts\struct_creator2.pl [Serializable] [DebuggerStepThrough] public struct Bank_Record { public Bank_Record(string account_ref, string name, int currency, string bank_account, string bank_name) : this() { this.Account_Ref = account_ref; this.Name = name; this.Currency = currency; this.Bank_Account = bank_account; this.Bank_Name = bank_name; } public string Account_Ref { get; set; } public string Name { get; set; } public int Currency { get; set; } public string Bank_Account { get; set; } public string Bank_Name { get; set; } /* Boilerplate */ public override string ToString() { string ret = ""; const string _null = "[null]"; #pragma warning disable 472 ret += "Account_Ref = " + this.Account_Ref == null ? _null : this.Account_Ref.ToString(); ret += ", "; ret += "Name = " + this.Name == null ? _null : this.Name.ToString(); ret += ", "; ret += "Currency = " + this.Currency == null ? _null : this.Currency.ToString(); ret += ", "; ret += "Bank_Account = " + this.Bank_Account == null ? _null : this.Bank_Account.ToString(); ret += ", "; ret += "Bank_Name = " + this.Bank_Name == null ? _null : this.Bank_Name.ToString(); #pragma warning restore ret = "{Bank_Record: " + ret + "}"; return ret; } public bool Equals(Bank_Record obj2) { #pragma warning disable 472 if (this.Account_Ref == null) { if (obj2.Account_Ref != null) return false; } else if (!this.Account_Ref.Equals(obj2.Account_Ref)) { return false; } if (this.Name == null) { if (obj2.Name != null) return false; } else if (!this.Name.Equals(obj2.Name)) { return false; } if (this.Currency == null) { if (obj2.Currency != null) return false; } else if (!this.Currency.Equals(obj2.Currency)) { return false; } if (this.Bank_Account == null) { if (obj2.Bank_Account != null) return false; } else if (!this.Bank_Account.Equals(obj2.Bank_Account)) { return false; } if (this.Bank_Name == null) { if (obj2.Bank_Name != null) return false; } else if (!this.Bank_Name.Equals(obj2.Bank_Name)) { return false; } #pragma warning restore return true; } public override bool Equals(object obj2) { if (obj2 == null) return false; if (!(obj2 is Bank_Record)) return false; var ret = this.Equals((Bank_Record)obj2); return ret; } public static bool operator ==(Bank_Record left, Bank_Record right) { var ret = left.Equals(right); return ret; } public static bool operator !=(Bank_Record left, Bank_Record right) { var ret = !left.Equals(right); return ret; } public override int GetHashCode() { #pragma warning disable 472 unchecked { int ret = 23; int temp; if (this.Account_Ref != null) { ret *= 31; temp = this.Account_Ref.GetHashCode(); ret += temp; } if (this.Name != null) { ret *= 31; temp = this.Name.GetHashCode(); ret += temp; } if (this.Currency != null) { ret *= 31; temp = this.Currency.GetHashCode(); ret += temp; } if (this.Bank_Account != null) { ret *= 31; temp = this.Bank_Account.GetHashCode(); ret += temp; } if (this.Bank_Name != null) { ret *= 31; temp = this.Bank_Name.GetHashCode(); ret += temp; } return ret; } // unchecked block #pragma warning restore } // method } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; namespace Org.Mentalis.Network.ProxySocket { sealed class HttpHandler : SocksHandler { public HttpHandler(ProxySocket server, string user, string pass) : base(server, user) { m_Password = pass; } public override void Negotiate(IPEndPoint remoteEP) { Negotiate(remoteEP.Address.ToString(), remoteEP.Port); } public override void Negotiate(string host, int port) { Server.Send(ConnectCommand(host, port)); byte[] buffer = new byte[4096]; // 4K ought to be enough for anyone int received = 0; while (true) { received += Server.Receive(buffer, received, buffer.Length - received, SocketFlags.None); if (ResponseReady(buffer, received)) { // end of the header break; } if (received == buffer.Length) { throw new ProxyException("Unexpected HTTP proxy response"); } } ParseResponse(buffer, received); } public override IAsyncProxyResult BeginNegotiate(IPEndPoint remoteEP, HandShakeComplete callback, IPEndPoint proxyEndPoint) { return BeginNegotiate(remoteEP.Address.ToString(), remoteEP.Port, callback, proxyEndPoint); } public override IAsyncProxyResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint) { // ProtocolComplete = callback; // Buffer = GetHostPortBytes(host, port); Server.BeginConnect(proxyEndPoint, delegate(IAsyncResult ar) { this.OnConnect(ar, callback, host, port); }, Server); IAsyncProxyResult AsyncResult = new IAsyncProxyResult(); return AsyncResult; } private byte[] ConnectCommand(string host, int port) { if (String.IsNullOrEmpty(host)) throw new ArgumentNullException("Null host"); if (port <= 0 || port > 65535) throw new ArgumentOutOfRangeException("Bad port"); string template = "CONNECT {0}:{1} HTTP/1.0\r\n" + "Host: {0}:{1}\r\n"; string command = String.Format(template, host, port); if (!String.IsNullOrEmpty(Username) && !String.IsNullOrEmpty(Password)) { command += "Proxy-Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Username + ":" + Password)) + "\r\n"; } command += "\r\n"; byte[] request = Encoding.ASCII.GetBytes(command); return request; } private bool ResponseReady(byte[] buffer, int received) { return received >= 4 && buffer[received - 4] == '\r' && buffer[received - 3] == '\n' && buffer[received - 2] == '\r' && buffer[received - 1] == '\n'; } private void ParseResponse(byte[] buffer, int received) { // parse the response String response = Encoding.UTF8.GetString(buffer, 0, received); String[] responseTokens = response.Split(new char[] { ' ' }, 3); if (responseTokens.Length != 3) { throw new ProxyException("Unexpected HTTP proxy response"); } if (!responseTokens[0].StartsWith("HTTP")) { throw new ProxyException("Unexpected HTTP proxy response"); } int responseCode = int.Parse(responseTokens[1]); HttpStatusCode code = (HttpStatusCode)Enum.ToObject(typeof(HttpStatusCode), responseCode); switch (code) { case HttpStatusCode.OK: return; default: throw new ProxyException(String.Format("HTTP proxy error: {0}", code)); } } private void OnConnect(IAsyncResult ar, HandShakeComplete ProtocolComplete, string host, int port) { try { Server.EndConnect(ar); } catch (Exception e) { ProtocolComplete(e); return; } try { byte[] command = ConnectCommand(host, port); Server.BeginSend(command, 0, command.Length, SocketFlags.None, delegate(IAsyncResult ar2) { this.OnSent(ar2, ProtocolComplete); }, Server); } catch (Exception e) { ProtocolComplete(e); } } private void OnSent(IAsyncResult ar, HandShakeComplete ProtocolComplete) { try { Server.EndSend(ar); } catch (Exception e) { ProtocolComplete(e); return; } try { byte[] buffer = new byte[4096]; // 4K ought to be enough for anyone int received = 0; Server.BeginReceive(buffer, received, buffer.Length - received, SocketFlags.None, delegate(IAsyncResult ar2) { this.OnReceive(ar2, ProtocolComplete, buffer, received); }, Server); } catch (Exception e) { ProtocolComplete(e); } } private void OnReceive(IAsyncResult ar, HandShakeComplete ProtocolComplete, byte[] buffer, int received) { try { int newlyReceived = Server.EndReceive(ar); if (newlyReceived <= 0) { ProtocolComplete(new SocketException()); return; } received += newlyReceived; if (ResponseReady(buffer, received)) { // end of the header ParseResponse(buffer, received); // if no exception was thrown, then.. ProtocolComplete(null); } else if (received == buffer.Length) { throw new ProxyException("Unexpected HTTP proxy response"); } else { Server.BeginReceive(buffer, received, buffer.Length - received, SocketFlags.None, delegate(IAsyncResult ar2) { this.OnReceive(ar2, ProtocolComplete, buffer, received); }, Server); } } catch (Exception e) { ProtocolComplete(e); } } #region Properties private string Password { get { return m_Password; } set { if (value == null) throw new ArgumentNullException(); m_Password = value; } } private string m_Password; #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Microsoft.Xna.Framework.Input; namespace Cocos2D { internal enum CCNodeTag { Invalid = -1, }; /** @brief CCNode is the main element. Anything thats gets drawn or contains things that get drawn is a CCNode. The most popular CCNodes are: CCScene, CCLayer, CCSprite, CCMenu. The main features of a CCNode are: - They can contain other CCNode nodes (addChild, getChildByTag, removeChild, etc) - They can schedule periodic callback (schedule, unschedule, etc) - They can execute actions (runAction, stopAction, etc) Some CCNode nodes provide extra functionality for them or their children. Subclassing a CCNode usually means (one/all) of: - overriding init to initialize resources and schedule callbacks - create callbacks to handle the advancement of time - overriding draw to render the node Features of CCNode: - position - scale (x, y) - rotation (in degrees, clockwise) - CCCamera (an interface to gluLookAt ) - CCGridBase (to do mesh transformations) - anchor point - size - visible - z-order - openGL z position Default values: - rotation: 0 - position: (x=0,y=0) - scale: (x=1,y=1) - contentSize: (x=0,y=0) - anchorPoint: (x=0,y=0) Limitations: - A CCNode is a "void" object. It doesn't have a texture Order in transformations with grid disabled -# The node will be translated (position) -# The node will be rotated (rotation) -# The node will be scaled (scale) -# The node will be moved according to the camera values (camera) Order in transformations with grid enabled -# The node will be translated (position) -# The node will be rotated (rotation) -# The node will be scaled (scale) -# The grid will capture the screen -# The node will be moved according to the camera values (camera) -# The grid will render the captured screen Camera: - Each node has a camera. By default it points to the center of the CCNode. */ public class CCNode : ICCSelectorProtocol, ICCFocusable, ICCTargetedTouchDelegate, ICCStandardTouchDelegate, ICCKeypadDelegate, ICCKeyboardDelegate, IComparer<CCNode> { /// <summary> /// Use this to determine if a tag has been set on the node. /// </summary> public const int kCCNodeTagInvalid = -1; private static uint s_globalOrderOfArrival = 1; protected bool m_bIgnoreAnchorPointForPosition; // transform public CCAffineTransform m_sTransform; protected bool m_bInverseDirty; protected bool m_bRunning; public bool m_bTransformDirty; protected bool m_bVisible; protected bool m_bReorderChildDirty; protected float m_fRotationX; protected float m_fRotationY; protected float m_fScaleX; protected float m_fScaleY; //protected int m_nScriptHandler; protected float m_fSkewX; protected float m_fSkewY; protected float m_fVertexZ; internal protected uint m_uOrderOfArrival; private int m_nTag; internal int m_nZOrder; protected CCActionManager m_pActionManager; protected CCCamera m_pCamera; protected CCRawList<CCNode> m_pChildren; protected Dictionary<int, List<CCNode>> m_pChildrenByTag; protected CCGridBase m_pGrid; protected CCNode m_pParent; protected CCScheduler m_pScheduler; protected object m_pUserData; protected CCPoint m_obAnchorPoint; protected CCPoint m_obAnchorPointInPoints; protected CCSize m_obContentSize; private CCAffineTransform m_sInverse; protected CCPoint m_obPosition; private bool m_bHasFocus = false; private bool m_bAdditionalTransformDirty; private CCAffineTransform m_sAdditionalTransform; private string m_sName; // input variables private bool m_bKeypadEnabled; private bool m_bKeyboardEnabled; private bool m_bGamePadEnabled; private bool m_bTouchEnabled; private CCTouchMode m_eTouchMode = CCTouchMode.OneByOne; private CCKeyboardMode m_eKeyboardMode = CCKeyboardMode.All; private int m_nTouchPriority; private bool m_bGamePadDelegatesInited; public enum CCTouchMode { AllAtOnce, OneByOne } public CCNode() { m_fScaleX = 1.0f; m_fScaleY = 1.0f; m_bVisible = true; m_nTag = kCCNodeTagInvalid; m_sTransform = CCAffineTransform.Identity; m_bInverseDirty = true; // set default scheduler and actionManager CCDirector director = CCDirector.SharedDirector; m_pActionManager = director.ActionManager; m_pScheduler = director.Scheduler; } public virtual bool Init() { return true; } #region Game State Management /// <summary> /// Gets whether or not this scene is serializable. If this is true, /// the screen will be recorded into the director's state and /// its Serialize and Deserialize methods will be called as appropriate. /// If this is false, the screen will be ignored during serialization. /// By default, all screens are assumed to be serializable. /// </summary> public virtual bool IsSerializable { get { return m_isSerializable; } protected set { m_isSerializable = value; } } private bool m_isSerializable = true; /// <summary> /// Tells the screen to serialize its state into the given stream. /// </summary> public virtual void Serialize(Stream stream) { StreamWriter sw = new StreamWriter(stream); CCSerialization.SerializeData(m_bVisible, sw); CCSerialization.SerializeData(m_fRotationX, sw); CCSerialization.SerializeData(m_fRotationY, sw); CCSerialization.SerializeData(m_fScaleX, sw); CCSerialization.SerializeData(m_fScaleY, sw); CCSerialization.SerializeData(m_fSkewX, sw); CCSerialization.SerializeData(m_fSkewY, sw); CCSerialization.SerializeData(m_fVertexZ, sw); CCSerialization.SerializeData(m_bIgnoreAnchorPointForPosition, sw); CCSerialization.SerializeData(m_bInverseDirty, sw); CCSerialization.SerializeData(m_bRunning, sw); CCSerialization.SerializeData(m_bTransformDirty, sw); CCSerialization.SerializeData(m_bReorderChildDirty, sw); CCSerialization.SerializeData(m_uOrderOfArrival, sw); CCSerialization.SerializeData(m_nTag, sw); CCSerialization.SerializeData(m_nZOrder, sw); CCSerialization.SerializeData(m_obAnchorPoint, sw); CCSerialization.SerializeData(m_obContentSize, sw); CCSerialization.SerializeData(Position, sw); if (m_pChildren != null) { CCSerialization.SerializeData(m_pChildren.Count, sw); foreach (CCNode child in m_pChildren) { sw.WriteLine(child.GetType().AssemblyQualifiedName); } foreach (CCNode child in m_pChildren) { child.Serialize(stream); } } else { CCSerialization.SerializeData(0, sw); // No children } } /// <summary> /// Tells the screen to deserialize its state from the given stream. /// </summary> public virtual void Deserialize(Stream stream) { StreamReader sr = new StreamReader(stream); m_bVisible = CCSerialization.DeSerializeBool(sr); m_fRotationX = CCSerialization.DeSerializeFloat(sr); m_fRotationY = CCSerialization.DeSerializeFloat(sr); m_fScaleX = CCSerialization.DeSerializeFloat(sr); m_fScaleY = CCSerialization.DeSerializeFloat(sr); m_fSkewX = CCSerialization.DeSerializeFloat(sr); m_fSkewY = CCSerialization.DeSerializeFloat(sr); m_fVertexZ = CCSerialization.DeSerializeFloat(sr); m_bIgnoreAnchorPointForPosition = CCSerialization.DeSerializeBool(sr); m_bInverseDirty = CCSerialization.DeSerializeBool(sr); m_bRunning = CCSerialization.DeSerializeBool(sr); m_bTransformDirty = CCSerialization.DeSerializeBool(sr); m_bReorderChildDirty = CCSerialization.DeSerializeBool(sr); m_uOrderOfArrival = (uint)CCSerialization.DeSerializeInt(sr); m_nTag = CCSerialization.DeSerializeInt(sr); m_nZOrder = CCSerialization.DeSerializeInt(sr); AnchorPoint = CCSerialization.DeSerializePoint(sr); ContentSize = CCSerialization.DeSerializeSize(sr); Position = CCSerialization.DeSerializePoint(sr); // m_UserData is handled by the specialized class. // TODO: Serializze the action manager // TODO :Serialize the grid // TODO: Serialize the camera string s; int count = CCSerialization.DeSerializeInt(sr); for (int i = 0; i < count; i++) { s = sr.ReadLine(); Type screenType = Type.GetType(s); CCNode scene = Activator.CreateInstance(screenType) as CCNode; AddChild(scene); scene.Deserialize(stream); } } #endregion #region CCIFocusable public virtual bool HasFocus { get { return (m_bHasFocus); } set { m_bHasFocus = value; } } public virtual bool CanReceiveFocus { get { return (Visible); } } #endregion public int Tag { get { return m_nTag; } set { if (m_nTag != value) { if (Parent != null) { Parent.ChangedChildTag(this, m_nTag, value); } m_nTag = value; } } } public object UserData { get { return m_pUserData; } set { m_pUserData = value; } } public object UserObject { get; set; } public virtual float SkewX { get { return m_fSkewX; } set { m_fSkewX = value; m_bTransformDirty = m_bInverseDirty = true; } } public virtual float SkewY { get { return m_fSkewY; } set { m_fSkewY = value; m_bTransformDirty = m_bInverseDirty = true; } } public int ZOrder { get { return m_nZOrder; } set { m_nZOrder = value; if (m_pParent != null) { m_pParent.ReorderChild(this, value); } } } public virtual float VertexZ { get { return m_fVertexZ; } set { m_fVertexZ = value; } } /// <summary> /// 2D rotation of the node relative to the 0,1 vector in a clock-wise orientation. /// </summary> public virtual float Rotation { get { Debug.Assert(m_fRotationX == m_fRotationY, "CCNode#rotation. RotationX != RotationY. Don't know which one to return"); return m_fRotationX; } set { m_fRotationX = m_fRotationY = value; m_bTransformDirty = m_bInverseDirty = true; } } public virtual float RotationX { get { return m_fRotationX; } set { m_fRotationX = value; m_bTransformDirty = m_bInverseDirty = true; } } public virtual float RotationY { get { return m_fRotationY; } set { m_fRotationY = value; m_bTransformDirty = m_bInverseDirty = true; } } /// <summary> /// The general scale that applies to both X and Y directions. /// </summary> public virtual float Scale { get { Debug.Assert(m_fScaleX == m_fScaleY, "CCNode#scale. ScaleX != ScaleY. Don't know which one to return"); return m_fScaleX; } set { m_fScaleX = m_fScaleY = value; m_bTransformDirty = m_bInverseDirty = true; } } /// <summary> /// Scale of the node in the X direction (left to right) /// </summary> public virtual float ScaleX { get { return m_fScaleX; } set { m_fScaleX = value; m_bTransformDirty = m_bInverseDirty = true; } } /// <summary> /// Scale of the node in the Y direction (top to bottom) /// </summary> public virtual float ScaleY { get { return m_fScaleY; } set { m_fScaleY = value; m_bTransformDirty = m_bInverseDirty = true; } } /// <summary> /// Sets and gets the position of the node. For Menus, this is the center of the menu. For layers, /// this is the lower left corner of the layer. /// </summary> public virtual CCPoint Position { get { return m_obPosition; } set { m_obPosition = value; m_bTransformDirty = m_bInverseDirty = true; } } public float PositionX { get { return m_obPosition.X; } set { SetPosition(value, m_obPosition.Y); } } public float PositionY { get { return m_obPosition.Y; } set { SetPosition(m_obPosition.X, value); } } public CCRawList<CCNode> Children { get { return m_pChildren; } } public int ChildrenCount { get { return m_pChildren == null ? 0 : m_pChildren.count; } } public CCCamera Camera { get { return m_pCamera ?? (m_pCamera = new CCCamera()); } } public CCGridBase Grid { get { return m_pGrid; } set { m_pGrid = value; } } public virtual bool Visible { get { return m_bVisible; } set { m_bVisible = value; } } /// <summary> /// Returns the anchor point in pixels, AnchorPoint * ContentSize. This does not use /// the scale factor of the node. /// </summary> public virtual CCPoint AnchorPointInPoints { get { return m_obAnchorPointInPoints; } } /// <summary> /// returns the Anchor Point of the node as a value [0,1], where 1 is 100% of the dimension and 0 is 0%. /// </summary> public virtual CCPoint AnchorPoint { get { return m_obAnchorPoint; } set { if (!value.Equals(m_obAnchorPoint)) { m_obAnchorPoint = value; m_obAnchorPointInPoints = new CCPoint(m_obContentSize.Width * m_obAnchorPoint.X, m_obContentSize.Height * m_obAnchorPoint.Y); m_bTransformDirty = m_bInverseDirty = true; } } } /// <summary> /// Returns the content size with the scale applied. /// </summary> public virtual CCSize ContentSizeInPixels { get { CCSize size = new CCSize(ContentSize.Width * ScaleX, ContentSize.Height * ScaleY); return (size); } } public virtual CCSize ContentSize { get { return m_obContentSize; } set { if (!CCSize.Equal(ref value, ref m_obContentSize)) { m_obContentSize = value; m_obAnchorPointInPoints = new CCPoint(m_obContentSize.Width * m_obAnchorPoint.X, m_obContentSize.Height * m_obAnchorPoint.Y); m_bTransformDirty = m_bInverseDirty = true; } } } public bool IsRunning { // read only get { return m_bRunning; } } public CCNode Parent { get { return m_pParent; } set { m_pParent = value; } } public virtual bool IgnoreAnchorPointForPosition { get { return m_bIgnoreAnchorPointForPosition; } set { if (value != m_bIgnoreAnchorPointForPosition) { m_bIgnoreAnchorPointForPosition = value; m_bTransformDirty = m_bInverseDirty = true; } } } public CCRect BoundingBox { get { var rect = new CCRect(0, 0, m_obContentSize.Width, m_obContentSize.Height); return CCAffineTransform.Transform(rect, NodeToParentTransform()); } } public CCRect BoundingBoxInPixels { get { var rect = new CCRect(0, 0, ContentSizeInPixels.Width, ContentSizeInPixels.Height); return CCAffineTransform.Transform(rect, NodeToParentTransform()); } } public uint OrderOfArrival { get { return m_uOrderOfArrival; } } public CCAffineTransform AdditionalTransform { get { return m_sAdditionalTransform; } set { m_sAdditionalTransform = value; m_bTransformDirty = true; m_bAdditionalTransformDirty = true; } } public string Name { get { return m_sName; } set { m_sName = value; } } #region SelectorProtocol Members public virtual void Update(float dt) { /* if (m_nUpdateScriptHandler) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeSchedule(m_nUpdateScriptHandler, fDelta, this); } if (m_pComponentContainer && !m_pComponentContainer->isEmpty()) { m_pComponentContainer->visit(fDelta); } */ } #endregion private bool m_bCleaned = false; ~CCNode() { //unregisterScriptHandler(); Cleanup(); if(m_pChildren != null) m_pChildren.Clear(); if(m_pChildrenByTag != null) m_pChildrenByTag.Clear(); } public void GetPosition(out float x, out float y) { x = m_obPosition.X; y = m_obPosition.Y; } public void SetPosition(float x, float y) { m_obPosition.X = x; m_obPosition.Y = y; m_bTransformDirty = m_bInverseDirty = true; } protected virtual void ResetCleanState() { m_bCleaned = false; if (m_pChildren != null && m_pChildren.count > 0) { CCNode[] elements = m_pChildren.Elements; for (int i = 0, count = m_pChildren.count; i < count; i++) { elements[i].ResetCleanState(); } } } public virtual void Cleanup() { if (m_bCleaned == true) { return; } // actions StopAllActions(); // timers UnscheduleAllSelectors(); if (m_pChildren != null && m_pChildren.count > 0) { CCNode[] elements = m_pChildren.Elements; for (int i = 0, count = m_pChildren.count; i < count; i++) { elements[i].Cleanup(); } } m_bCleaned = true; } public CCNode GetChildByTag(int tag) { Debug.Assert(tag != (int) CCNodeTag.Invalid, "Invalid tag"); if (m_pChildrenByTag != null && m_pChildrenByTag.Count > 0) { Debug.Assert(m_pChildren != null && m_pChildren.count > 0); List<CCNode> list; if (m_pChildrenByTag.TryGetValue(tag, out list)) { if (list.Count > 0) { return list[0]; } } } return null; } public void AddChild(CCNode child) { Debug.Assert(child != null, "Argument must be no-null"); AddChild(child, child.ZOrder, child.Tag); } public void AddChild(CCNode child, int zOrder) { Debug.Assert(child != null, "Argument must be no-null"); AddChild(child, zOrder, child.Tag); } public virtual void AddChild(CCNode child, int zOrder, int tag) { Debug.Assert(child != null, "Argument must be non-null"); Debug.Assert(child.m_pParent == null, "child already added. It can't be added again"); Debug.Assert(child != this, "Can not add myself to myself."); if (m_pChildren == null) { m_pChildren = new CCRawList<CCNode>(); } InsertChild(child, zOrder, tag); child.Parent = this; child.m_nTag = tag; child.m_uOrderOfArrival = s_globalOrderOfArrival++; if (child.m_bCleaned) { child.ResetCleanState(); } if (m_bRunning) { child.OnEnter(); child.OnEnterTransitionDidFinish(); } } public void RemoveFromParent() { RemoveFromParentAndCleanup(true); } public void RemoveFromParentAndCleanup(bool cleanup) { if (m_pParent != null) { m_pParent.RemoveChild(this, cleanup); } } public void RemoveChild(CCNode child) { RemoveChild(child, true); } public virtual void RemoveChild(CCNode child, bool cleanup) { // explicit nil handling if (m_pChildren == null || child == null) { return; } ChangedChildTag(child, child.Tag, kCCNodeTagInvalid); if (m_pChildren.Contains(child)) { DetachChild(child, cleanup); } } public void RemoveChildByTag(int tag) { RemoveChildByTag(tag, true); } public void RemoveChildByTag(int tag, bool cleanup) { Debug.Assert(tag != (int) CCNodeTag.Invalid, "Invalid tag"); CCNode child = GetChildByTag(tag); if (child == null) { CCLog.Log("cocos2d: removeChildByTag: child not found!"); } else { RemoveChild(child, cleanup); } } public virtual void RemoveAllChildren() { RemoveAllChildrenWithCleanup(true); } public virtual void RemoveAllChildrenWithCleanup(bool cleanup) { // not using detachChild improves speed here if (m_pChildren != null && m_pChildren.Count > 0) { if (m_pChildrenByTag != null) { m_pChildrenByTag.Clear(); } CCNode[] elements = m_pChildren.Elements; for (int i = 0, count = m_pChildren.count; i < count; i++) { CCNode node = elements[i]; // IMPORTANT: // -1st do onExit // -2nd cleanup if (m_bRunning) { node.OnExitTransitionDidStart(); node.OnExit(); } if (cleanup) { node.Cleanup(); } // set parent nil at the end node.Parent = null; } m_pChildren.Clear(); } } private void DetachChild(CCNode child, bool doCleanup) { // IMPORTANT: // -1st do onExit // -2nd cleanup if (m_bRunning) { child.OnExitTransitionDidStart(); child.OnExit(); } // If you don't do cleanup, the child's actions will not get removed and the // its scheduledSelectors_ dict will not get released! if (doCleanup) { child.Cleanup(); } // set parent nil at the end child.Parent = null; m_pChildren.Remove(child); } private void ChangedChildTag(CCNode child, int oldTag, int newTag) { List<CCNode> list; if (m_pChildrenByTag != null && oldTag != kCCNodeTagInvalid) { if (m_pChildrenByTag.TryGetValue(oldTag, out list)) { list.Remove(child); } } if (newTag != kCCNodeTagInvalid) { if (m_pChildrenByTag == null) { m_pChildrenByTag = new Dictionary<int, List<CCNode>>(); } if (!m_pChildrenByTag.TryGetValue(newTag, out list)) { list = new List<CCNode>(); m_pChildrenByTag.Add(newTag, list); } list.Add(child); } } private void InsertChild(CCNode child, int z, int tag) { m_bReorderChildDirty = true; m_pChildren.Add(child); ChangedChildTag(child, kCCNodeTagInvalid, tag); child.m_nZOrder = z; } public virtual void ReorderChild(CCNode child, int zOrder) { Debug.Assert(child != null, "Child must be non-null"); m_bReorderChildDirty = true; child.m_uOrderOfArrival = s_globalOrderOfArrival++; child.m_nZOrder = zOrder; } #region Child Sorting int IComparer<CCNode>.Compare(CCNode n1, CCNode n2) { if (n1.m_nZOrder < n2.m_nZOrder || (n1.m_nZOrder == n2.m_nZOrder && n1.m_uOrderOfArrival < n2.m_uOrderOfArrival)) { return -1; } if (n1 == n2) { return 0; } return 1; } public virtual void SortAllChildren() { if (m_bReorderChildDirty) { Array.Sort(m_pChildren.Elements, 0, m_pChildren.count, this); m_bReorderChildDirty = false; } } #endregion /// <summary> /// This is called from the Visit() method. This is where you DRAW your node. Only /// draw stuff from this method call. /// </summary> public virtual void Draw() { // Does nothing in the root node class. } /// <summary> /// This is called with every call to the MainLoop on the CCDirector class. In XNA, this is the same as the Draw() call. /// </summary> public virtual void Visit() { // quick return if not visible. children won't be drawn. if (!m_bVisible) { return; } CCDrawManager.PushMatrix(); if (m_pGrid != null && m_pGrid.Active) { m_pGrid.BeforeDraw(); //TransformAncestors(); } else { Transform(); } int i = 0; if ((m_pChildren != null) && (m_pChildren.count > 0)) { SortAllChildren(); CCNode[] elements = m_pChildren.Elements; int count = m_pChildren.count; // draw children zOrder < 0 for (; i < count; ++i) { if (elements[i].Visible && elements[i].m_nZOrder < 0) { elements[i].Visit(); } else { break; } } // self draw Draw(); // draw the children for (; i < count; ++i) { // Draw the z >= 0 order children next. if (elements[i].Visible/* && elements[i].m_nZOrder >= 0*/) { elements[i].Visit(); } } } else { // self draw Draw(); } //m_uOrderOfArrival = 0; if (m_pGrid != null && m_pGrid.Active) { m_pGrid.AfterDraw(this); Transform(); m_pGrid.Blit(); } //kmGLPopMatrix(); CCDrawManager.PopMatrix(); } public void TransformAncestors() { if (m_pParent != null) { m_pParent.TransformAncestors(); m_pParent.Transform(); } } public void Transform() { CCDrawManager.MultMatrix(NodeToParentTransform(), m_fVertexZ); // XXX: Expensive calls. Camera should be integrated into the cached affine matrix if (m_pCamera != null && !(m_pGrid != null && m_pGrid.Active)) { bool translate = (m_obAnchorPointInPoints.X != 0.0f || m_obAnchorPointInPoints.Y != 0.0f); if (translate) { CCDrawManager.Translate(m_obAnchorPointInPoints.X, m_obAnchorPointInPoints.Y, 0); } m_pCamera.Locate(); if (translate) { CCDrawManager.Translate(-m_obAnchorPointInPoints.X, -m_obAnchorPointInPoints.Y, 0); } } } public virtual void OnEnter() { // register 'parent' nodes first // since events are propagated in reverse order if (m_bTouchEnabled) { RegisterWithTouchDispatcher(); } if (m_pChildren != null && m_pChildren.count > 0) { CCNode[] elements = m_pChildren.Elements; for (int i = 0, count = m_pChildren.count; i < count; i++) { elements[i].OnEnter(); } } ResumeSchedulerAndActions(); m_bRunning = true; CCDirector director = CCDirector.SharedDirector; // add this node to concern the kaypad msg if (m_bKeypadEnabled) { director.KeypadDispatcher.AddDelegate(this); } // tell the director that this node is interested in Keyboard message if (m_bKeyboardEnabled) { director.KeyboardDispatcher.AddDelegate(this); } if (GamePadEnabled && director.GamePadEnabled) { if (!m_bGamePadDelegatesInited) { m_OnGamePadButtonUpdateDelegate = new CCGamePadButtonDelegate(OnGamePadButtonUpdate); m_OnGamePadConnectionUpdateDelegate = new CCGamePadConnectionDelegate(OnGamePadConnectionUpdate); m_OnGamePadDPadUpdateDelegate = new CCGamePadDPadDelegate(OnGamePadDPadUpdate); m_OnGamePadStickUpdateDelegate = new CCGamePadStickUpdateDelegate(OnGamePadStickUpdate); m_OnGamePadTriggerUpdateDelegate = new CCGamePadTriggerDelegate(OnGamePadTriggerUpdate); m_bGamePadDelegatesInited = true; } CCApplication application = CCApplication.SharedApplication; application.GamePadButtonUpdate += m_OnGamePadButtonUpdateDelegate; application.GamePadConnectionUpdate += m_OnGamePadConnectionUpdateDelegate; application.GamePadDPadUpdate += m_OnGamePadDPadUpdateDelegate; application.GamePadStickUpdate += m_OnGamePadStickUpdateDelegate; application.GamePadTriggerUpdate += m_OnGamePadTriggerUpdateDelegate; } /* if (m_nScriptHandler) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeFunctionWithIntegerData(m_nScriptHandler, kCCNodeOnEnter); } */ } public virtual void OnEnterTransitionDidFinish() { if (m_pChildren != null && m_pChildren.count > 0) { CCNode[] elements = m_pChildren.Elements; for (int i = 0, count = m_pChildren.count; i < count; i++) { elements[i].OnEnterTransitionDidFinish(); } } } public virtual void OnExitTransitionDidStart() { if (m_pChildren != null && m_pChildren.count > 0) { CCNode[] elements = m_pChildren.Elements; for (int i = 0, count = m_pChildren.count; i < count; i++) { elements[i].OnExitTransitionDidStart(); } } } public virtual void OnExit() { CCDirector director = CCDirector.SharedDirector; if (m_bTouchEnabled) { director.TouchDispatcher.RemoveDelegate(this); //unregisterScriptTouchHandler(); } if (m_bKeypadEnabled) { director.KeypadDispatcher.RemoveDelegate(this); } if (m_bKeyboardEnabled) { director.KeyboardDispatcher.RemoveDelegate(this); } if (GamePadEnabled && director.GamePadEnabled) { CCApplication application = CCApplication.SharedApplication; application.GamePadButtonUpdate -= m_OnGamePadButtonUpdateDelegate; application.GamePadConnectionUpdate -= m_OnGamePadConnectionUpdateDelegate; application.GamePadDPadUpdate -= m_OnGamePadDPadUpdateDelegate; application.GamePadStickUpdate -= m_OnGamePadStickUpdateDelegate; application.GamePadTriggerUpdate -= m_OnGamePadTriggerUpdateDelegate; } PauseSchedulerAndActions(); m_bRunning = false; /* if (m_nScriptHandler) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeFunctionWithIntegerData(m_nScriptHandler, kCCNodeOnExit); } */ if (m_pChildren != null && m_pChildren.count > 0) { CCNode[] elements = m_pChildren.Elements; for (int i = 0, count = m_pChildren.count; i < count; i++) { elements[i].OnExit(); } } } #region Actions public CCActionManager ActionManager { get { return m_pActionManager; } set { if (value != m_pActionManager) { StopAllActions(); m_pActionManager = value; } } } public CCAction RunAction(CCAction action) { Debug.Assert(action != null, "Argument must be non-nil"); m_pActionManager.AddAction(action, this, !m_bRunning); return action; } public void StopAllActions() { m_pActionManager.RemoveAllActionsFromTarget(this); } public void StopAction(CCAction action) { m_pActionManager.RemoveAction(action); } public void StopActionByTag(int tag) { Debug.Assert(tag != (int) CCNodeTag.Invalid, "Invalid tag"); m_pActionManager.RemoveActionByTag(tag, this); } public CCAction GetActionByTag(int tag) { Debug.Assert(tag != (int) CCNodeTag.Invalid, "Invalid tag"); return m_pActionManager.GetActionByTag(tag, this); } public int NumberOfRunningActions() { return m_pActionManager.NumberOfRunningActionsInTarget(this); } #endregion #region CCNode - Callbacks public CCScheduler Scheduler { get { return m_pScheduler; } set { if (value != m_pScheduler) { UnscheduleAllSelectors(); m_pScheduler = value; } } } public void ScheduleUpdate() { ScheduleUpdateWithPriority(0); } public void ScheduleUpdateWithPriority(int priority) { m_pScheduler.ScheduleUpdateForTarget(this, priority, !m_bRunning); } public void UnscheduleUpdate() { m_pScheduler.UnscheduleUpdateForTarget(this); } public void Schedule(Action<float> selector) { Schedule(selector, 0.0f, CCScheduler.kCCRepeatForever, 0.0f); } public void Schedule(Action<float> selector, float interval) { Schedule(selector, interval, CCScheduler.kCCRepeatForever, 0.0f); } public void Schedule(Action<float> selector, float interval, uint repeat, float delay) { Debug.Assert(selector != null, "Argument must be non-nil"); Debug.Assert(interval >= 0, "Argument must be positive"); m_pScheduler.ScheduleSelector(selector, this, interval, repeat, delay, !m_bRunning); } public void ScheduleOnce(Action<float> selector, float delay) { Schedule(selector, 0.0f, 0, delay); } public void Unschedule(Action<float> selector) { // explicit nil handling if (selector == null) return; m_pScheduler.UnscheduleSelector(selector, this); } public void UnscheduleAllSelectors() { m_pScheduler.UnscheduleAllForTarget(this); } public void ResumeSchedulerAndActions() { m_pScheduler.ResumeTarget(this); m_pActionManager.ResumeTarget(this); } public void PauseSchedulerAndActions() { m_pScheduler.PauseTarget(this); m_pActionManager.PauseTarget(this); } #endregion #region Transformations public virtual CCAffineTransform NodeToParentTransform() { if (m_bTransformDirty) { // Translate values float x = m_obPosition.X; float y = m_obPosition.Y; if (m_bIgnoreAnchorPointForPosition) { x += m_obAnchorPointInPoints.X; y += m_obAnchorPointInPoints.Y; } // Rotation values // Change rotation code to handle X and Y // If we skew with the exact same value for both x and y then we're simply just rotating float cx = 1, sx = 0, cy = 1, sy = 0; if (m_fRotationX != 0 || m_fRotationY != 0) { float radiansX = -CCMacros.CCDegreesToRadians(m_fRotationX); float radiansY = -CCMacros.CCDegreesToRadians(m_fRotationY); cx = (float)Math.Cos(radiansX); sx = (float)Math.Sin(radiansX); cy = (float)Math.Cos(radiansY); sy = (float)Math.Sin(radiansY); } bool needsSkewMatrix = (m_fSkewX != 0f || m_fSkewY != 0f); // optimization: // inline anchor point calculation if skew is not needed if (!needsSkewMatrix && !m_obAnchorPointInPoints.Equals(CCPoint.Zero)) { x += cy * -m_obAnchorPointInPoints.X * m_fScaleX + -sx * -m_obAnchorPointInPoints.Y * m_fScaleY; y += sy * -m_obAnchorPointInPoints.X * m_fScaleX + cx * -m_obAnchorPointInPoints.Y * m_fScaleY; } // Build Transform Matrix // Adjusted transform calculation for rotational skew m_sTransform.a = cy * m_fScaleX; m_sTransform.b = sy * m_fScaleX; m_sTransform.c = -sx * m_fScaleY; m_sTransform.d = cx * m_fScaleY; m_sTransform.tx = x; m_sTransform.ty = y; // XXX: Try to inline skew // If skew is needed, apply skew and then anchor point if (needsSkewMatrix) { var skewMatrix = new CCAffineTransform( 1.0f, (float) Math.Tan(CCMacros.CCDegreesToRadians(m_fSkewY)), (float) Math.Tan(CCMacros.CCDegreesToRadians(m_fSkewX)), 1.0f, 0.0f, 0.0f); m_sTransform = CCAffineTransform.Concat(skewMatrix, m_sTransform); // adjust anchor point if (!m_obAnchorPointInPoints.Equals(CCPoint.Zero)) { m_sTransform = CCAffineTransform.Translate(m_sTransform, -m_obAnchorPointInPoints.X, -m_obAnchorPointInPoints.Y); } } if (m_bAdditionalTransformDirty) { m_sTransform.Concat(ref m_sAdditionalTransform); m_bAdditionalTransformDirty = false; } m_bTransformDirty = false; } return m_sTransform; } public virtual void UpdateTransform() { // Recursively iterate over children if (m_pChildren != null && m_pChildren.count > 0) { CCNode[] elements = m_pChildren.Elements; for (int i = 0, count = m_pChildren.count; i < count; i++) { elements[i].UpdateTransform(); } } } public CCAffineTransform ParentToNodeTransform() { if (m_bInverseDirty) { m_sInverse = CCAffineTransform.Invert(NodeToParentTransform()); m_bInverseDirty = false; } return m_sInverse; } public CCAffineTransform NodeToWorldTransform() { CCAffineTransform t = NodeToParentTransform(); CCNode p = m_pParent; while (p != null) { t.Concat(p.NodeToParentTransform()); p = p.Parent; } return t; } public CCAffineTransform WorldToNodeTransform() { return CCAffineTransform.Invert(NodeToWorldTransform()); } #endregion #region ConvertToSpace public CCPoint ConvertToNodeSpace(CCPoint worldPoint) { return CCAffineTransform.Transform(worldPoint, WorldToNodeTransform()); } public CCPoint ConvertToWorldSpace(CCPoint nodePoint) { return CCAffineTransform.Transform(nodePoint, NodeToWorldTransform()); } public CCPoint ConvertToNodeSpaceAr(CCPoint worldPoint) { CCPoint nodePoint = ConvertToNodeSpace(worldPoint); return nodePoint - m_obAnchorPointInPoints; } public CCPoint ConvertToWorldSpaceAr(CCPoint nodePoint) { CCPoint pt = nodePoint + m_obAnchorPointInPoints; return ConvertToWorldSpace(pt); } public CCPoint ConvertToWindowSpace(CCPoint nodePoint) { CCPoint worldPoint = ConvertToWorldSpace(nodePoint); return CCDirector.SharedDirector.ConvertToUi(worldPoint); } public CCPoint ConvertTouchToNodeSpace(CCTouch touch) { var point = touch.Location; return ConvertToNodeSpace(point); } public CCPoint ConvertTouchToNodeSpaceAr(CCTouch touch) { var point = touch.Location; return ConvertToNodeSpaceAr(point); } #endregion /* void registerScriptHandler(int nHandler) { unregisterScriptHandler(); m_nScriptHandler = nHandler; LUALOG("[LUA] Add CCNode event handler: %d", m_nScriptHandler); } void unregisterScriptHandler(void) { if (m_nScriptHandler) { CCScriptEngineManager::sharedManager().getScriptEngine().removeLuaHandler(m_nScriptHandler); LUALOG("[LUA] Remove CCNode event handler: %d", m_nScriptHandler); m_nScriptHandler = 0; } } */ public virtual void RegisterWithTouchDispatcher() { CCTouchDispatcher pDispatcher = CCDirector.SharedDirector.TouchDispatcher; /* if (m_pScriptHandlerEntry) { if (m_pScriptHandlerEntry->isMultiTouches()) { pDispatcher->addStandardDelegate(this, 0); LUALOG("[LUA] Add multi-touches event handler: %d", m_pScriptHandlerEntry->getHandler()); } else { pDispatcher->addTargetedDelegate(this, m_pScriptHandlerEntry->getPriority(), m_pScriptHandlerEntry->getSwallowsTouches()); LUALOG("[LUA] Add touch event handler: %d", m_pScriptHandlerEntry->getHandler()); } return; } */ if (m_eTouchMode == CCTouchMode.AllAtOnce) { pDispatcher.AddStandardDelegate(this, 0); } else { pDispatcher.AddTargetedDelegate(this, m_nTouchPriority, true); } } public CCTouchMode TouchMode { get { return m_eTouchMode; } set { if (m_eTouchMode != value) { m_eTouchMode = value; if (m_bTouchEnabled) { TouchEnabled = false; TouchEnabled = true; } } } } public virtual bool TouchEnabled { get { return m_bTouchEnabled; } set { if (m_bTouchEnabled != value) { m_bTouchEnabled = value; if (m_bRunning) { if (value) { RegisterWithTouchDispatcher(); } else { CCDirector.SharedDirector.TouchDispatcher.RemoveDelegate(this); } } } } } public virtual int TouchPriority { get { return m_nTouchPriority; } set { if (m_nTouchPriority != value) { m_nTouchPriority = value; if (m_bRunning) { TouchEnabled = false; TouchEnabled = true; } } } } public virtual bool KeypadEnabled { get { return m_bKeypadEnabled; } set { if (value != m_bKeypadEnabled) { m_bKeypadEnabled = value; if (m_bRunning) { if (value) { CCDirector.SharedDirector.KeypadDispatcher.AddDelegate(this); } else { CCDirector.SharedDirector.KeypadDispatcher.RemoveDelegate(this); } } } } } public virtual bool KeyboardEnabled { get { return m_bKeyboardEnabled; } set { if (value != m_bKeyboardEnabled) { m_bKeyboardEnabled = value; if (m_bRunning) { if (value) { CCDirector.SharedDirector.KeyboardDispatcher.AddDelegate(this); } else { CCDirector.SharedDirector.KeyboardDispatcher.RemoveDelegate(this); } } } } } public virtual CCKeyboardMode KeyboardMode { get { return m_eKeyboardMode; } set { if (m_eKeyboardMode != value) { m_eKeyboardMode = value; } } } public virtual bool GamePadEnabled { get { return (m_bGamePadEnabled); } set { if (value != m_bGamePadEnabled) { m_bGamePadEnabled = value; } if (value && !CCDirector.SharedDirector.GamePadEnabled) { CCDirector.SharedDirector.GamePadEnabled = true; } } } #region touches #region ICCStandardTouchDelegate Members public virtual void TouchesBegan(List<CCTouch> touches) { } public virtual void TouchesMoved(List<CCTouch> touches) { } public virtual void TouchesEnded(List<CCTouch> touches) { } public virtual void TouchesCancelled(List<CCTouch> touches) { } #endregion #region ICCTargetedTouchDelegate Members public virtual bool TouchBegan(CCTouch touch) { return true; } public virtual void TouchMoved(CCTouch touch) { } public virtual void TouchEnded(CCTouch touch) { } public virtual void TouchCancelled(CCTouch touch) { } #endregion #endregion public virtual void KeyBackClicked() { } public virtual void KeyMenuClicked() { } #region Keyboard Support public virtual void KeyPressed (Keys key) { } public virtual void KeyReleased (Keys key) { } public virtual void KeyboardCurrentState (KeyboardState currentState) { } #endregion #region GamePad Support private CCGamePadButtonDelegate m_OnGamePadButtonUpdateDelegate; private CCGamePadConnectionDelegate m_OnGamePadConnectionUpdateDelegate; private CCGamePadDPadDelegate m_OnGamePadDPadUpdateDelegate; private CCGamePadStickUpdateDelegate m_OnGamePadStickUpdateDelegate; private CCGamePadTriggerDelegate m_OnGamePadTriggerUpdateDelegate; protected virtual void OnGamePadTriggerUpdate(float leftTriggerStrength, float rightTriggerStrength, Microsoft.Xna.Framework.PlayerIndex player) { } protected virtual void OnGamePadStickUpdate(CCGameStickStatus leftStick, CCGameStickStatus rightStick, Microsoft.Xna.Framework.PlayerIndex player) { } protected virtual void OnGamePadDPadUpdate(CCGamePadButtonStatus leftButton, CCGamePadButtonStatus upButton, CCGamePadButtonStatus rightButton, CCGamePadButtonStatus downButton, Microsoft.Xna.Framework.PlayerIndex player) { if (!HasFocus) { return; } } protected virtual void OnGamePadConnectionUpdate(Microsoft.Xna.Framework.PlayerIndex player, bool IsConnected) { } protected virtual void OnGamePadButtonUpdate(CCGamePadButtonStatus backButton, CCGamePadButtonStatus startButton, CCGamePadButtonStatus systemButton, CCGamePadButtonStatus aButton, CCGamePadButtonStatus bButton, CCGamePadButtonStatus xButton, CCGamePadButtonStatus yButton, CCGamePadButtonStatus leftShoulder, CCGamePadButtonStatus rightShoulder, Microsoft.Xna.Framework.PlayerIndex player) { } #endregion } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Diagnostics; using dnlib.IO; using dnlib.PE; using dnlib.Threading; namespace dnlib.DotNet.MD { /// <summary> /// Used when a #- stream is present in the metadata /// </summary> sealed class ENCMetadata : MetadataBase { static readonly UTF8String DeletedName = "_Deleted"; bool hasMethodPtr, hasFieldPtr, hasParamPtr, hasEventPtr, hasPropertyPtr; bool hasDeletedFields; bool hasDeletedNonFields; readonly CLRRuntimeReaderKind runtime; readonly Dictionary<Table, SortedTable> sortedTables = new Dictionary<Table, SortedTable>(); #if THREAD_SAFE readonly Lock theLock = Lock.Create(); #endif /// <inheritdoc/> public override bool IsCompressed => false; /// <inheritdoc/> public ENCMetadata(IPEImage peImage, ImageCor20Header cor20Header, MetadataHeader mdHeader, CLRRuntimeReaderKind runtime) : base(peImage, cor20Header, mdHeader) { this.runtime = runtime; } /// <inheritdoc/> internal ENCMetadata(MetadataHeader mdHeader, bool isStandalonePortablePdb, CLRRuntimeReaderKind runtime) : base(mdHeader, isStandalonePortablePdb) { this.runtime = runtime; } /// <inheritdoc/> protected override void InitializeInternal(DataReaderFactory mdReaderFactory, uint metadataBaseOffset) { DotNetStream dns = null; bool forceAllBig = false; try { if (runtime == CLRRuntimeReaderKind.Mono) { var newAllStreams = new List<DotNetStream>(allStreams); for (int i = mdHeader.StreamHeaders.Count - 1; i >= 0; i--) { var sh = mdHeader.StreamHeaders[i]; switch (sh.Name) { case "#Strings": if (stringsStream is null) { stringsStream = new StringsStream(mdReaderFactory, metadataBaseOffset, sh); newAllStreams.Add(stringsStream); continue; } break; case "#US": if (usStream is null) { usStream = new USStream(mdReaderFactory, metadataBaseOffset, sh); newAllStreams.Add(usStream); continue; } break; case "#Blob": if (blobStream is null) { blobStream = new BlobStream(mdReaderFactory, metadataBaseOffset, sh); newAllStreams.Add(blobStream); continue; } break; case "#GUID": if (guidStream is null) { guidStream = new GuidStream(mdReaderFactory, metadataBaseOffset, sh); newAllStreams.Add(guidStream); continue; } break; case "#~": case "#-": if (tablesStream is null) { tablesStream = new TablesStream(mdReaderFactory, metadataBaseOffset, sh, runtime); newAllStreams.Add(tablesStream); continue; } break; case "#Pdb": if (isStandalonePortablePdb && pdbStream is null) { pdbStream = new PdbStream(mdReaderFactory, metadataBaseOffset, sh); newAllStreams.Add(pdbStream); continue; } break; case "#JTD": forceAllBig = true; continue; } dns = new CustomDotNetStream(mdReaderFactory, metadataBaseOffset, sh); newAllStreams.Add(dns); dns = null; } newAllStreams.Reverse(); allStreams = newAllStreams; } else { Debug.Assert(runtime == CLRRuntimeReaderKind.CLR); foreach (var sh in mdHeader.StreamHeaders) { switch (sh.Name.ToUpperInvariant()) { case "#STRINGS": if (stringsStream is null) { stringsStream = new StringsStream(mdReaderFactory, metadataBaseOffset, sh); allStreams.Add(stringsStream); continue; } break; case "#US": if (usStream is null) { usStream = new USStream(mdReaderFactory, metadataBaseOffset, sh); allStreams.Add(usStream); continue; } break; case "#BLOB": if (blobStream is null) { blobStream = new BlobStream(mdReaderFactory, metadataBaseOffset, sh); allStreams.Add(blobStream); continue; } break; case "#GUID": if (guidStream is null) { guidStream = new GuidStream(mdReaderFactory, metadataBaseOffset, sh); allStreams.Add(guidStream); continue; } break; case "#~": // Only if #Schema is used case "#-": if (tablesStream is null) { tablesStream = new TablesStream(mdReaderFactory, metadataBaseOffset, sh, runtime); allStreams.Add(tablesStream); continue; } break; case "#PDB": // Case sensitive comparison since it's a stream that's not read by the CLR, // only by other libraries eg. System.Reflection.Metadata. if (isStandalonePortablePdb && pdbStream is null && sh.Name == "#Pdb") { pdbStream = new PdbStream(mdReaderFactory, metadataBaseOffset, sh); allStreams.Add(pdbStream); continue; } break; case "#JTD": forceAllBig = true; continue; } dns = new CustomDotNetStream(mdReaderFactory, metadataBaseOffset, sh); allStreams.Add(dns); dns = null; } } } finally { dns?.Dispose(); } if (tablesStream is null) throw new BadImageFormatException("Missing MD stream"); if (pdbStream is not null) tablesStream.Initialize(pdbStream.TypeSystemTableRows, forceAllBig); else tablesStream.Initialize(null, forceAllBig); // The pointer tables are used iff row count != 0 hasFieldPtr = !tablesStream.FieldPtrTable.IsEmpty; hasMethodPtr = !tablesStream.MethodPtrTable.IsEmpty; hasParamPtr = !tablesStream.ParamPtrTable.IsEmpty; hasEventPtr = !tablesStream.EventPtrTable.IsEmpty; hasPropertyPtr = !tablesStream.PropertyPtrTable.IsEmpty; switch (runtime) { case CLRRuntimeReaderKind.CLR: hasDeletedFields = tablesStream.HasDelete; hasDeletedNonFields = tablesStream.HasDelete; break; case CLRRuntimeReaderKind.Mono: hasDeletedFields = true; hasDeletedNonFields = false; break; default: throw new InvalidOperationException(); } } /// <inheritdoc/> public override RidList GetTypeDefRidList() { if (!hasDeletedNonFields) return base.GetTypeDefRidList(); uint rows = tablesStream.TypeDefTable.Rows; var list = new List<uint>((int)rows); for (uint rid = 1; rid <= rows; rid++) { if (!tablesStream.TryReadTypeDefRow(rid, out var row)) continue; // Should never happen since rid is valid // RTSpecialName is ignored by the CLR. It's only the name that indicates // whether it's been deleted. // It's not possible to delete the global type (<Module>) if (rid != 1 && stringsStream.ReadNoNull(row.Name).StartsWith(DeletedName)) continue; // ignore this deleted row list.Add(rid); } return RidList.Create(list); } /// <inheritdoc/> public override RidList GetExportedTypeRidList() { if (!hasDeletedNonFields) return base.GetExportedTypeRidList(); uint rows = tablesStream.ExportedTypeTable.Rows; var list = new List<uint>((int)rows); for (uint rid = 1; rid <= rows; rid++) { if (!tablesStream.TryReadExportedTypeRow(rid, out var row)) continue; // Should never happen since rid is valid // RTSpecialName is ignored by the CLR. It's only the name that indicates // whether it's been deleted. if (stringsStream.ReadNoNull(row.TypeName).StartsWith(DeletedName)) continue; // ignore this deleted row list.Add(rid); } return RidList.Create(list); } /// <summary> /// Converts a logical <c>Field</c> rid to a physical <c>Field</c> rid /// </summary> /// <param name="listRid">A valid rid</param> /// <returns>Converted rid or any invalid rid value if <paramref name="listRid"/> is invalid</returns> uint ToFieldRid(uint listRid) { if (!hasFieldPtr) return listRid; return tablesStream.TryReadColumn24(tablesStream.FieldPtrTable, listRid, 0, out uint listValue) ? listValue : 0; } /// <summary> /// Converts a logical <c>Method</c> rid to a physical <c>Method</c> rid /// </summary> /// <param name="listRid">A valid rid</param> /// <returns>Converted rid or any invalid rid value if <paramref name="listRid"/> is invalid</returns> uint ToMethodRid(uint listRid) { if (!hasMethodPtr) return listRid; return tablesStream.TryReadColumn24(tablesStream.MethodPtrTable, listRid, 0, out uint listValue) ? listValue : 0; } /// <summary> /// Converts a logical <c>Param</c> rid to a physical <c>Param</c> rid /// </summary> /// <param name="listRid">A valid rid</param> /// <returns>Converted rid or any invalid rid value if <paramref name="listRid"/> is invalid</returns> uint ToParamRid(uint listRid) { if (!hasParamPtr) return listRid; return tablesStream.TryReadColumn24(tablesStream.ParamPtrTable, listRid, 0, out uint listValue) ? listValue : 0; } /// <summary> /// Converts a logical <c>Event</c> rid to a physical <c>Event</c> rid /// </summary> /// <param name="listRid">A valid rid</param> /// <returns>Converted rid or any invalid rid value if <paramref name="listRid"/> is invalid</returns> uint ToEventRid(uint listRid) { if (!hasEventPtr) return listRid; return tablesStream.TryReadColumn24(tablesStream.EventPtrTable, listRid, 0, out uint listValue) ? listValue : 0; } /// <summary> /// Converts a logical <c>Property</c> rid to a physical <c>Property</c> rid /// </summary> /// <param name="listRid">A valid rid</param> /// <returns>Converted rid or any invalid rid value if <paramref name="listRid"/> is invalid</returns> uint ToPropertyRid(uint listRid) { if (!hasPropertyPtr) return listRid; return tablesStream.TryReadColumn24(tablesStream.PropertyPtrTable, listRid, 0, out uint listValue) ? listValue : 0; } /// <inheritdoc/> public override RidList GetFieldRidList(uint typeDefRid) { var list = GetRidList(tablesStream.TypeDefTable, typeDefRid, 4, tablesStream.FieldTable); if (list.Count == 0 || (!hasFieldPtr && !hasDeletedFields)) return list; var destTable = tablesStream.FieldTable; var newList = new List<uint>(list.Count); for (int i = 0; i < list.Count; i++) { var rid = ToFieldRid(list[i]); if (destTable.IsInvalidRID(rid)) continue; if (hasDeletedFields) { // It's a deleted row if RTSpecialName is set and name is "_Deleted" if (!tablesStream.TryReadFieldRow(rid, out var row)) continue; // Should never happen since rid is valid if (runtime == CLRRuntimeReaderKind.CLR) { if ((row.Flags & (uint)FieldAttributes.RTSpecialName) != 0) { if (stringsStream.ReadNoNull(row.Name).StartsWith(DeletedName)) continue; // ignore this deleted row } } else { if ((row.Flags & (uint)(FieldAttributes.SpecialName | FieldAttributes.RTSpecialName)) == (uint)(FieldAttributes.SpecialName | FieldAttributes.RTSpecialName)) { if (stringsStream.ReadNoNull(row.Name) == DeletedName) continue; // ignore this deleted row } } } // It's a valid non-deleted rid so add it newList.Add(rid); } return RidList.Create(newList); } /// <inheritdoc/> public override RidList GetMethodRidList(uint typeDefRid) { var list = GetRidList(tablesStream.TypeDefTable, typeDefRid, 5, tablesStream.MethodTable); if (list.Count == 0 || (!hasMethodPtr && !hasDeletedNonFields)) return list; var destTable = tablesStream.MethodTable; var newList = new List<uint>(list.Count); for (int i = 0; i < list.Count; i++) { var rid = ToMethodRid(list[i]); if (destTable.IsInvalidRID(rid)) continue; if (hasDeletedNonFields) { // It's a deleted row if RTSpecialName is set and name is "_Deleted" if (!tablesStream.TryReadMethodRow(rid, out var row)) continue; // Should never happen since rid is valid if ((row.Flags & (uint)MethodAttributes.RTSpecialName) != 0) { if (stringsStream.ReadNoNull(row.Name).StartsWith(DeletedName)) continue; // ignore this deleted row } } // It's a valid non-deleted rid so add it newList.Add(rid); } return RidList.Create(newList); } /// <inheritdoc/> public override RidList GetParamRidList(uint methodRid) { var list = GetRidList(tablesStream.MethodTable, methodRid, 5, tablesStream.ParamTable); if (list.Count == 0 || !hasParamPtr) return list; var destTable = tablesStream.ParamTable; var newList = new List<uint>(list.Count); for (int i = 0; i < list.Count; i++) { var rid = ToParamRid(list[i]); if (destTable.IsInvalidRID(rid)) continue; newList.Add(rid); } return RidList.Create(newList); } /// <inheritdoc/> public override RidList GetEventRidList(uint eventMapRid) { var list = GetRidList(tablesStream.EventMapTable, eventMapRid, 1, tablesStream.EventTable); if (list.Count == 0 || (!hasEventPtr && !hasDeletedNonFields)) return list; var destTable = tablesStream.EventTable; var newList = new List<uint>(list.Count); for (int i = 0; i < list.Count; i++) { var rid = ToEventRid(list[i]); if (destTable.IsInvalidRID(rid)) continue; if (hasDeletedNonFields) { // It's a deleted row if RTSpecialName is set and name is "_Deleted" if (!tablesStream.TryReadEventRow(rid, out var row)) continue; // Should never happen since rid is valid if ((row.EventFlags & (uint)EventAttributes.RTSpecialName) != 0) { if (stringsStream.ReadNoNull(row.Name).StartsWith(DeletedName)) continue; // ignore this deleted row } } // It's a valid non-deleted rid so add it newList.Add(rid); } return RidList.Create(newList); } /// <inheritdoc/> public override RidList GetPropertyRidList(uint propertyMapRid) { var list = GetRidList(tablesStream.PropertyMapTable, propertyMapRid, 1, tablesStream.PropertyTable); if (list.Count == 0 || (!hasPropertyPtr && !hasDeletedNonFields)) return list; var destTable = tablesStream.PropertyTable; var newList = new List<uint>(list.Count); for (int i = 0; i < list.Count; i++) { var rid = ToPropertyRid(list[i]); if (destTable.IsInvalidRID(rid)) continue; if (hasDeletedNonFields) { // It's a deleted row if RTSpecialName is set and name is "_Deleted" if (!tablesStream.TryReadPropertyRow(rid, out var row)) continue; // Should never happen since rid is valid if ((row.PropFlags & (uint)PropertyAttributes.RTSpecialName) != 0) { if (stringsStream.ReadNoNull(row.Name).StartsWith(DeletedName)) continue; // ignore this deleted row } } // It's a valid non-deleted rid so add it newList.Add(rid); } return RidList.Create(newList); } /// <inheritdoc/> public override RidList GetLocalVariableRidList(uint localScopeRid) => GetRidList(tablesStream.LocalScopeTable, localScopeRid, 2, tablesStream.LocalVariableTable); /// <inheritdoc/> public override RidList GetLocalConstantRidList(uint localScopeRid) => GetRidList(tablesStream.LocalScopeTable, localScopeRid, 3, tablesStream.LocalConstantTable); /// <summary> /// Gets a rid list (eg. field list) /// </summary> /// <param name="tableSource">Source table, eg. <c>TypeDef</c></param> /// <param name="tableSourceRid">Row ID in <paramref name="tableSource"/></param> /// <param name="colIndex">Column index in <paramref name="tableSource"/>, eg. 4 for <c>TypeDef.FieldList</c></param> /// <param name="tableDest">Destination table, eg. <c>Field</c></param> /// <returns>A new <see cref="RidList"/> instance</returns> RidList GetRidList(MDTable tableSource, uint tableSourceRid, int colIndex, MDTable tableDest) { var column = tableSource.TableInfo.Columns[colIndex]; if (!tablesStream.TryReadColumn24(tableSource, tableSourceRid, column, out uint startRid)) return RidList.Empty; bool hasNext = tablesStream.TryReadColumn24(tableSource, tableSourceRid + 1, column, out uint nextListRid); uint lastRid = tableDest.Rows + 1; if (startRid == 0 || startRid >= lastRid) return RidList.Empty; uint endRid = hasNext && nextListRid != 0 ? nextListRid : lastRid; if (endRid < startRid) endRid = startRid; if (endRid > lastRid) endRid = lastRid; return RidList.Create(startRid, endRid - startRid); } /// <inheritdoc/> protected override uint BinarySearch(MDTable tableSource, int keyColIndex, uint key) { var keyColumn = tableSource.TableInfo.Columns[keyColIndex]; uint ridLo = 1, ridHi = tableSource.Rows; while (ridLo <= ridHi) { uint rid = (ridLo + ridHi) / 2; if (!tablesStream.TryReadColumn24(tableSource, rid, keyColumn, out uint key2)) break; // Never happens since rid is valid if (key == key2) return rid; if (key2 > key) ridHi = rid - 1; else ridLo = rid + 1; } if (tableSource.Table == Table.GenericParam && !tablesStream.IsSorted(tableSource)) return LinearSearch(tableSource, keyColIndex, key); return 0; } uint LinearSearch(MDTable tableSource, int keyColIndex, uint key) { if (tableSource is null) return 0; var keyColumn = tableSource.TableInfo.Columns[keyColIndex]; for (uint rid = 1; rid <= tableSource.Rows; rid++) { if (!tablesStream.TryReadColumn24(tableSource, rid, keyColumn, out uint key2)) break; // Never happens since rid is valid if (key == key2) return rid; } return 0; } /// <inheritdoc/> protected override RidList FindAllRowsUnsorted(MDTable tableSource, int keyColIndex, uint key) { if (tablesStream.IsSorted(tableSource)) return FindAllRows(tableSource, keyColIndex, key); SortedTable sortedTable; #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (!sortedTables.TryGetValue(tableSource.Table, out sortedTable)) sortedTables[tableSource.Table] = sortedTable = new SortedTable(tableSource, keyColIndex); #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif return sortedTable.FindAllRows(key); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native interface manager. /// </summary> internal static unsafe class IgniteManager { /** Environment variable: IGNITE_HOME. */ internal const string EnvIgniteHome = "IGNITE_HOME"; /** Environment variable: whether to set test classpath or not. */ internal const string EnvIgniteNativeTestClasspath = "IGNITE_NATIVE_TEST_CLASSPATH"; /** Classpath prefix. */ private const string ClasspathPrefix = "-Djava.class.path="; /** Java Command line argument: Xms. Case sensitive. */ private const string CmdJvmMinMemJava = "-Xms"; /** Java Command line argument: Xmx. Case sensitive. */ private const string CmdJvmMaxMemJava = "-Xmx"; /** Monitor for DLL load synchronization. */ private static readonly object SyncRoot = new object(); /** First created context. */ private static void* _ctx; /** Configuration used on JVM start. */ private static JvmConfiguration _jvmCfg; /** Memory manager. */ private static PlatformMemoryManager _mem; /// <summary> /// Static initializer. /// </summary> static IgniteManager() { // No-op. } /// <summary> /// Create JVM. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs">Callbacks.</param> /// <returns>Context.</returns> internal static void* GetContext(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { lock (SyncRoot) { // 1. Warn about possible configuration inconsistency. JvmConfiguration jvmCfg = JvmConfig(cfg); if (!cfg.SuppressWarnings && _jvmCfg != null) { if (!_jvmCfg.Equals(jvmCfg)) { Console.WriteLine("Attempting to start Ignite node with different Java " + "configuration; current Java configuration will be ignored (consider " + "starting node in separate process) [oldConfig=" + _jvmCfg + ", newConfig=" + jvmCfg + ']'); } } // 2. Create unmanaged pointer. void* ctx = CreateJvm(cfg, cbs); cbs.SetContext(ctx); // 3. If this is the first JVM created, preserve it. if (_ctx == null) { _ctx = ctx; _jvmCfg = jvmCfg; _mem = new PlatformMemoryManager(1024); } return ctx; } } /// <summary> /// Memory manager attached to currently running JVM. /// </summary> internal static PlatformMemoryManager Memory { get { return _mem; } } /// <summary> /// Destroy JVM. /// </summary> public static void DestroyJvm() { lock (SyncRoot) { if (_ctx != null) { UU.DestroyJvm(_ctx); _ctx = null; } } } /// <summary> /// Create JVM. /// </summary> /// <returns>JVM.</returns> private static void* CreateJvm(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { var ggHome = GetIgniteHome(cfg); var cp = CreateClasspath(ggHome, cfg, false); var jvmOpts = GetMergedJvmOptions(cfg); var hasGgHome = !string.IsNullOrWhiteSpace(ggHome); var opts = new sbyte*[1 + jvmOpts.Count + (hasGgHome ? 1 : 0)]; int idx = 0; opts[idx++] = IgniteUtils.StringToUtf8Unmanaged(cp); if (hasGgHome) opts[idx++] = IgniteUtils.StringToUtf8Unmanaged("-DIGNITE_HOME=" + ggHome); foreach (string cfgOpt in jvmOpts) opts[idx++] = IgniteUtils.StringToUtf8Unmanaged(cfgOpt); try { IntPtr mem = Marshal.AllocHGlobal(opts.Length * 8); fixed (sbyte** opts0 = opts) { PlatformMemoryUtils.CopyMemory(opts0, mem.ToPointer(), opts.Length * 8); } try { return UU.CreateContext(mem.ToPointer(), opts.Length, cbs.CallbacksPointer); } finally { Marshal.FreeHGlobal(mem); } } finally { foreach (sbyte* opt in opts) Marshal.FreeHGlobal((IntPtr)opt); } } /// <summary> /// Gets JvmOptions collection merged with individual properties (Min/Max mem, etc) according to priority. /// </summary> private static IList<string> GetMergedJvmOptions(IgniteConfiguration cfg) { var jvmOpts = cfg.JvmOptions == null ? new List<string>() : cfg.JvmOptions.ToList(); // JvmInitialMemoryMB / JvmMaxMemoryMB have lower priority than CMD_JVM_OPT if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMinMemJava, StringComparison.OrdinalIgnoreCase))) jvmOpts.Add(string.Format("{0}{1}m", CmdJvmMinMemJava, cfg.JvmInitialMemoryMb)); if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMaxMemJava, StringComparison.OrdinalIgnoreCase))) jvmOpts.Add(string.Format("{0}{1}m", CmdJvmMaxMemJava, cfg.JvmMaxMemoryMb)); return jvmOpts; } /// <summary> /// Create JVM configuration value object. /// </summary> /// <param name="cfg">Configuration.</param> /// <returns>JVM configuration.</returns> private static JvmConfiguration JvmConfig(IgniteConfiguration cfg) { return new JvmConfiguration { Home = cfg.IgniteHome, Dll = cfg.JvmDllPath, Classpath = cfg.JvmClasspath, Options = cfg.JvmOptions }; } /// <summary> /// Append jars from the given path. /// </summary> /// <param name="path">Path.</param> /// <param name="cpStr">Classpath string builder.</param> private static void AppendJars(string path, StringBuilder cpStr) { if (Directory.Exists(path)) { foreach (string jar in Directory.EnumerateFiles(path, "*.jar")) { cpStr.Append(jar); cpStr.Append(';'); } } } /// <summary> /// Calculate Ignite home. /// </summary> /// <param name="cfg">Configuration.</param> /// <returns></returns> internal static string GetIgniteHome(IgniteConfiguration cfg) { var home = cfg == null ? null : cfg.IgniteHome; if (string.IsNullOrWhiteSpace(home)) home = Environment.GetEnvironmentVariable(EnvIgniteHome); else if (!IsIgniteHome(new DirectoryInfo(home))) throw new IgniteException(string.Format("IgniteConfiguration.IgniteHome is not valid: '{0}'", home)); if (string.IsNullOrWhiteSpace(home)) home = ResolveIgniteHome(); else if (!IsIgniteHome(new DirectoryInfo(home))) throw new IgniteException(string.Format("{0} is not valid: '{1}'", EnvIgniteHome, home)); return home; } /// <summary> /// Automatically resolve Ignite home directory. /// </summary> /// <returns>Ignite home directory.</returns> private static string ResolveIgniteHome() { var probeDirs = new[] { Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Directory.GetCurrentDirectory() }; foreach (var probeDir in probeDirs.Where(x => !string.IsNullOrEmpty(x))) { var dir = new DirectoryInfo(probeDir); while (dir != null) { if (IsIgniteHome(dir)) return dir.FullName; dir = dir.Parent; } } return null; } /// <summary> /// Determines whether specified dir looks like a Ignite home. /// </summary> /// <param name="dir">Directory.</param> /// <returns>Value indicating whether specified dir looks like a Ignite home.</returns> private static bool IsIgniteHome(DirectoryInfo dir) { return dir.Exists && dir.EnumerateDirectories().Count(x => x.Name == "examples" || x.Name == "bin") == 2; } /// <summary> /// Creates classpath from the given configuration, or default classpath if given config is null. /// </summary> /// <param name="cfg">The configuration.</param> /// <param name="forceTestClasspath">Append test directories even if <see cref="EnvIgniteNativeTestClasspath" /> is not set.</param> /// <returns> /// Classpath string. /// </returns> internal static string CreateClasspath(IgniteConfiguration cfg = null, bool forceTestClasspath = false) { return CreateClasspath(GetIgniteHome(cfg), cfg, forceTestClasspath); } /// <summary> /// Creates classpath from the given configuration, or default classpath if given config is null. /// </summary> /// <param name="ggHome">The home dir.</param> /// <param name="cfg">The configuration.</param> /// <param name="forceTestClasspath">Append test directories even if /// <see cref="EnvIgniteNativeTestClasspath" /> is not set.</param> /// <returns> /// Classpath string. /// </returns> private static string CreateClasspath(string ggHome, IgniteConfiguration cfg, bool forceTestClasspath) { var cpStr = new StringBuilder(); if (cfg != null && cfg.JvmClasspath != null) { cpStr.Append(cfg.JvmClasspath); if (!cfg.JvmClasspath.EndsWith(";")) cpStr.Append(';'); } if (!string.IsNullOrWhiteSpace(ggHome)) AppendHomeClasspath(ggHome, forceTestClasspath, cpStr); return ClasspathPrefix + cpStr; } /// <summary> /// Appends classpath from home directory, if it is defined. /// </summary> /// <param name="ggHome">The home dir.</param> /// <param name="forceTestClasspath">Append test directories even if /// <see cref="EnvIgniteNativeTestClasspath"/> is not set.</param> /// <param name="cpStr">The classpath string.</param> private static void AppendHomeClasspath(string ggHome, bool forceTestClasspath, StringBuilder cpStr) { // Append test directories (if needed) first, because otherwise build *.jar will be picked first. if (forceTestClasspath || "true".Equals(Environment.GetEnvironmentVariable(EnvIgniteNativeTestClasspath))) { AppendTestClasses(ggHome + "\\examples", cpStr); AppendTestClasses(ggHome + "\\modules", cpStr); } string ggLibs = ggHome + "\\libs"; AppendJars(ggLibs, cpStr); if (Directory.Exists(ggLibs)) { foreach (string dir in Directory.EnumerateDirectories(ggLibs)) { if (!dir.EndsWith("optional")) AppendJars(dir, cpStr); } } } /// <summary> /// Append target (compile) directories to classpath (for testing purposes only). /// </summary> /// <param name="path">Path</param> /// <param name="cp">Classpath builder.</param> private static void AppendTestClasses(string path, StringBuilder cp) { if (Directory.Exists(path)) { AppendTestClasses0(path, cp); foreach (string moduleDir in Directory.EnumerateDirectories(path)) AppendTestClasses0(moduleDir, cp); } } /// <summary> /// Internal routine to append classes and jars from eploded directory. /// </summary> /// <param name="path">Path.</param> /// <param name="cp">Classpath builder.</param> private static void AppendTestClasses0(string path, StringBuilder cp) { if (path.EndsWith("rest-http", StringComparison.OrdinalIgnoreCase)) return; if (Directory.Exists(path + "\\target\\classes")) cp.Append(path + "\\target\\classes;"); if (Directory.Exists(path + "\\target\\test-classes")) cp.Append(path + "\\target\\test-classes;"); if (Directory.Exists(path + "\\target\\libs")) AppendJars(path + "\\target\\libs", cp); } /// <summary> /// JVM configuration. /// </summary> private class JvmConfiguration { /// <summary> /// Gets or sets the home. /// </summary> public string Home { get; set; } /// <summary> /// Gets or sets the DLL. /// </summary> public string Dll { get; set; } /// <summary> /// Gets or sets the cp. /// </summary> public string Classpath { get; set; } /// <summary> /// Gets or sets the options. /// </summary> public ICollection<string> Options { get; set; } /** <inheritDoc /> */ public override int GetHashCode() { return 0; } /** <inheritDoc /> */ [SuppressMessage("ReSharper", "FunctionComplexityOverflow")] public override bool Equals(object obj) { JvmConfiguration other = obj as JvmConfiguration; if (other == null) return false; if (!string.Equals(Home, other.Home, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(Classpath, other.Classpath, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(Dll, other.Dll, StringComparison.OrdinalIgnoreCase)) return false; return (Options == null && other.Options == null) || (Options != null && other.Options != null && Options.Count == other.Options.Count && !Options.Except(other.Options).Any()); } /** <inheritDoc /> */ public override string ToString() { var sb = new StringBuilder("[IgniteHome=" + Home + ", JvmDllPath=" + Dll); if (Options != null && Options.Count > 0) { sb.Append(", JvmOptions=["); bool first = true; foreach (string opt in Options) { if (first) first = false; else sb.Append(", "); sb.Append(opt); } sb.Append(']'); } sb.Append(", Classpath=" + Classpath + ']'); return sb.ToString(); } } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonEditor.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH // </copyright> // <summary> // MenuItems and in-Editor scripts for PhotonNetwork. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Reflection; using ExitGames.Client.Photon; using UnityEditor; using UnityEngine; namespace Photon.Pun { public class PunWizardText { public string WindowTitle = "PUN Wizard"; public string SetupWizardWarningTitle = "Warning"; public string SetupWizardWarningMessage = "You have not yet run the Photon setup wizard! Your game won't be able to connect. See Windows -> Photon Unity Networking."; public string MainMenuButton = "Main Menu"; public string SetupWizardTitle = "PUN Setup"; public string SetupWizardInfo = "Thanks for importing Photon Unity Networking.\nThis window should set you up.\n\n<b>-</b> To use an existing Photon Cloud App, enter your AppId.\n<b>-</b> To register an account or access an existing one, enter the account's mail address.\n<b>-</b> To use Photon OnPremise, skip this step."; public string EmailOrAppIdLabel = "AppId or Email"; public string AlreadyRegisteredInfo = "The email is registered so we can't fetch your AppId (without password).\n\nPlease login online to get your AppId and paste it above."; public string SkipRegistrationInfo = "Skipping? No problem:\nEdit your server settings in the PhotonServerSettings file."; public string RegisteredNewAccountInfo = "We created a (free) account and fetched you an AppId.\nWelcome. Your PUN project is setup."; public string AppliedToSettingsInfo = "Your AppId is now applied to this project."; public string SetupCompleteInfo = "<b>Done!</b>\nAll connection settings can be edited in the <b>PhotonServerSettings</b> now.\nHave a look."; public string CloseWindowButton = "Close"; public string SkipButton = "Skip"; public string SetupButton = "Setup Project"; public string CancelButton = "Cancel"; public string PUNWizardLabel = "PUN Wizard"; public string SettingsButton = "Settings"; public string SetupServerCloudLabel = "Setup wizard for setting up your own server or the cloud."; public string WarningPhotonDisconnect = ""; public string StartButton = "Start"; public string LocateSettingsButton = "Locate PhotonServerSettings"; public string SettingsHighlightLabel = "Highlights the used photon settings file in the project."; public string DocumentationLabel = "Documentation"; public string OpenPDFText = "Reference PDF"; public string OpenPDFTooltip = "Opens the local documentation pdf."; public string OpenDevNetText = "Doc Pages / Manual"; public string OpenDevNetTooltip = "Online documentation for Photon."; public string OpenCloudDashboardText = "Cloud Dashboard Login"; public string OpenCloudDashboardTooltip = "Review Cloud App information and statistics."; public string OpenForumText = "Open Forum"; public string OpenForumTooltip = "Online support for Photon."; public string OkButton = "Ok"; public string OwnHostCloudCompareLabel = "I am not quite sure how 'my own host' compares to 'cloud'."; public string ComparisonPageButton = "Cloud versus OnPremise"; public string ConnectionTitle = "Connecting"; public string ConnectionInfo = "Connecting to the account service..."; public string ErrorTextTitle = "Error"; public string IncorrectRPCListTitle = "Warning: RPC-list becoming incompatible!"; public string IncorrectRPCListLabel = "Your project's RPC-list is full, so we can't add some RPCs just compiled.\n\nBy removing outdated RPCs, the list will be long enough but incompatible with older client builds!\n\nMake sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string RemoveOutdatedRPCsLabel = "Remove outdated RPCs"; public string FullRPCListTitle = "Warning: RPC-list is full!"; public string FullRPCListLabel = "Your project's RPC-list is too long for PUN.\n\nYou can change PUN's source to use short-typed RPC index. Look for comments 'LIMITS RPC COUNT'\n\nAlternatively, remove some RPC methods (use more parameters per RPC maybe).\n\nAfter a RPC-list refresh, make sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string SkipRPCListUpdateLabel = "Skip RPC-list update"; public string PUNNameReplaceTitle = "Warning: RPC-list Compatibility"; public string PUNNameReplaceLabel = "PUN replaces RPC names with numbers by using the RPC-list. All clients must use the same list for that.\n\nClearing it most likely makes your client incompatible with previous versions! Change your game version or make sure the RPC-list matches other clients."; public string RPCListCleared = "Clear RPC-list"; public string ServerSettingsCleanedWarning = "Cleared the PhotonServerSettings.RpcList! This makes new builds incompatible with older ones. Better change game version in PhotonNetwork.ConnectUsingSettings()."; public string WizardMainWindowInfo = "This window should help you find important settings for PUN, as well as documentation."; } [InitializeOnLoad] public class PhotonEditor : EditorWindow { protected static Type WindowType = typeof(PhotonEditor); protected Vector2 scrollPos = Vector2.zero; private readonly Vector2 preferredSize = new Vector2(350, 400); private static Texture2D BackgroundImage; public static PunWizardText CurrentLang = new PunWizardText(); protected static AccountService.Origin RegisterOrigin = AccountService.Origin.Pun; protected static string DocumentationLocation = "Assets/Photon/PhotonNetworking-Documentation.pdf"; protected static string UrlFreeLicense = "https://dashboard.photonengine.com/en-US/SelfHosted"; public const string UrlDevNet = "https://doc.photonengine.com/en-us/pun/v2"; protected static string UrlForum = "https://forum.photonengine.com"; protected static string UrlCompare = "https://doc.photonengine.com/en-us/realtime/current/getting-started/onpremise-or-saas"; protected static string UrlHowToSetup = "https://doc.photonengine.com/en-us/onpremise/current/getting-started/photon-server-in-5min"; protected static string UrlAppIDExplained = "https://doc.photonengine.com/en-us/realtime/current/getting-started/obtain-your-app-id"; public const string UrlCloudDashboard = "https://dashboard.photonengine.com/en-US/account/signin?email="; public const string UrlPunSettings = "https://doc.photonengine.com/en-us/pun/v2/getting-started/initial-setup"; // the SeverSettings class has this url directly in it's HelpURL attribute. private enum PhotonSetupStates { MainUi, RegisterForPhotonCloud, EmailAlreadyRegistered, GoEditPhotonServerSettings } private bool isSetupWizard = false; private PhotonSetupStates photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; private bool minimumInput = false; private bool useMail = false; private bool useAppId = false; private bool useSkip = false; private bool highlightedSettings = false; private bool close = false; private string mailOrAppId = string.Empty; private static double lastWarning = 0; private static bool postCompileActionsDone; // setup once on load static PhotonEditor() { #if UNITY_2017_2_OR_NEWER EditorApplication.playModeStateChanged += PlaymodeStateChanged; #else EditorApplication.playmodeStateChanged += PlaymodeStateChanged; #endif #if UNITY_2018 EditorApplication.projectChanged += EditorUpdate; EditorApplication.hierarchyChanged += EditorUpdate; #else EditorApplication.projectWindowChanged += EditorUpdate; EditorApplication.hierarchyWindowChanged += EditorUpdate; #endif EditorApplication.update += OnUpdate; } // setup per window public PhotonEditor() { this.minSize = this.preferredSize; } [MenuItem("Window/Photon Unity Networking/PUN Wizard &p", false, 0)] protected static void MenuItemOpenWizard() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; if (win == null) { return; } win.photonSetupState = PhotonSetupStates.MainUi; win.isSetupWizard = false; } [MenuItem("Window/Photon Unity Networking/Highlight Server Settings %#&p", false, 1)] protected static void MenuItemHighlightSettings() { HighlightSettings(); } /// <summary>Creates an Editor window, showing the cloud-registration wizard for Photon (entry point to setup PUN).</summary> protected static void ShowRegistrationWizard() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; if (win == null) { return; } win.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; win.isSetupWizard = true; } // called 100 times / sec private static void OnUpdate() { // after a compile, check RPCs to create a cache-list if (!postCompileActionsDone && !EditorApplication.isCompiling && !EditorApplication.isPlayingOrWillChangePlaymode && PhotonNetwork.PhotonServerSettings != null) { if (EditorApplication.isUpdating) { return; } PhotonEditor.UpdateRpcList(); postCompileActionsDone = true; // on compile, this falls back to false (without actively doing anything) } } // called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues) private static void EditorUpdate() { if (PhotonNetwork.PhotonServerSettings == null) { PhotonNetwork.CreateSettings(); } if (PhotonNetwork.PhotonServerSettings == null) { return; } // serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set if (!PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard) { ShowRegistrationWizard(); PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard = true; PhotonEditor.SaveSettings(); } // Workaround for TCP crash. Plus this surpresses any other recompile errors. if (EditorApplication.isCompiling) { if (PhotonNetwork.IsConnected) { if (lastWarning > EditorApplication.timeSinceStartup - 3) { // Prevent error spam Debug.LogWarning(CurrentLang.WarningPhotonDisconnect); lastWarning = EditorApplication.timeSinceStartup; } PhotonNetwork.Disconnect(); } } } // called in editor on change of play-mode (used to show a message popup that connection settings are incomplete) #if UNITY_2017_2_OR_NEWER private static void PlaymodeStateChanged(PlayModeStateChange state) #else private static void PlaymodeStateChanged() #endif { if (EditorApplication.isPlaying || !EditorApplication.isPlayingOrWillChangePlaymode) { return; } if (string.IsNullOrEmpty(PhotonNetwork.PhotonServerSettings.AppSettings.AppIdRealtime) && !PhotonNetwork.PhotonServerSettings.AppSettings.IsMasterServerAddress) { EditorUtility.DisplayDialog(CurrentLang.SetupWizardWarningTitle, CurrentLang.SetupWizardWarningMessage, CurrentLang.OkButton); } } #region GUI and Wizard // Window Update() callback. On-demand, when Window is open protected void Update() { if (this.close) { this.Close(); } } protected virtual void OnGUI() { if (BackgroundImage == null) { string[] paths = AssetDatabase.FindAssets("PunGradient t:Texture2D"); if (paths != null && paths.Length > 0) { BackgroundImage = AssetDatabase.LoadAssetAtPath<Texture2D>(AssetDatabase.GUIDToAssetPath(paths[0])); } } PhotonSetupStates oldGuiState = this.photonSetupState; // used to fix an annoying Editor input field issue: wont refresh until focus is changed. GUI.SetNextControlName(""); this.scrollPos = GUILayout.BeginScrollView(this.scrollPos); if (this.photonSetupState == PhotonSetupStates.MainUi) { this.UiMainWizard(); } else { this.UiSetupApp(); } GUILayout.EndScrollView(); if (oldGuiState != this.photonSetupState) { GUI.FocusControl(""); } } protected virtual void UiSetupApp() { GUI.skin.label.wordWrap = true; if (!this.isSetupWizard) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.MainMenuButton, GUILayout.ExpandWidth(false))) { this.photonSetupState = PhotonSetupStates.MainUi; } GUILayout.EndHorizontal(); } // setup header this.UiTitleBox(CurrentLang.SetupWizardTitle, BackgroundImage); // setup info text GUI.skin.label.richText = true; GUILayout.Label(CurrentLang.SetupWizardInfo); // input of appid or mail EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.EmailOrAppIdLabel); this.mailOrAppId = EditorGUILayout.TextField(this.mailOrAppId).Trim(); // note: we trim all input if (this.mailOrAppId.Contains("@")) { // this should be a mail address this.minimumInput = (this.mailOrAppId.Length >= 5 && this.mailOrAppId.Contains(".")); this.useMail = this.minimumInput; this.useAppId = false; } else { // this should be an appId this.minimumInput = ServerSettings.IsAppId(this.mailOrAppId); this.useMail = false; this.useAppId = this.minimumInput; } // button to skip setup GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.SkipButton, GUILayout.Width(100))) { this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; this.useSkip = true; this.useMail = false; this.useAppId = false; } // SETUP button EditorGUI.BeginDisabledGroup(!this.minimumInput); if (GUILayout.Button(CurrentLang.SetupButton, GUILayout.Width(100))) { this.useSkip = false; GUIUtility.keyboardControl = 0; if (this.useMail) { this.RegisterWithEmail(this.mailOrAppId); // sets state } if (this.useAppId) { this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PhotonServerSettings for PUN"); PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId); PhotonEditor.SaveSettings(); } } EditorGUI.EndDisabledGroup(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); // existing account needs to fetch AppId online if (this.photonSetupState == PhotonSetupStates.EmailAlreadyRegistered) { // button to open dashboard and get the AppId GUILayout.Space(15); GUILayout.Label(CurrentLang.AlreadyRegisteredInfo); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip), GUILayout.Width(205))) { Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId)); this.mailOrAppId = ""; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } if (this.photonSetupState == PhotonSetupStates.GoEditPhotonServerSettings) { if (!this.highlightedSettings) { this.highlightedSettings = true; HighlightSettings(); } GUILayout.Space(15); if (this.useSkip) { GUILayout.Label(CurrentLang.SkipRegistrationInfo); } else if (this.useMail) { GUILayout.Label(CurrentLang.RegisteredNewAccountInfo); } else if (this.useAppId) { GUILayout.Label(CurrentLang.AppliedToSettingsInfo); } // setup-complete info GUILayout.Space(15); GUILayout.Label(CurrentLang.SetupCompleteInfo); // close window (done) GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.CloseWindowButton, GUILayout.Width(205))) { this.close = true; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } GUI.skin.label.richText = false; } private void UiTitleBox(string title, Texture2D bgIcon) { GUIStyle bgStyle = new GUIStyle(GUI.skin.GetStyle("Label")); bgStyle.normal.background = bgIcon; bgStyle.fontSize = 22; bgStyle.fontStyle = FontStyle.Bold; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); Rect scale = GUILayoutUtility.GetLastRect(); scale.height = 30; GUI.Label(scale, title, bgStyle); GUILayout.Space(scale.height + 5); } protected virtual void UiMainWizard() { GUILayout.Space(15); // title this.UiTitleBox(CurrentLang.PUNWizardLabel, BackgroundImage); // wizard info text GUILayout.Label(CurrentLang.WizardMainWindowInfo); GUILayout.Space(15); // settings button GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.SettingsButton, EditorStyles.boldLabel, GUILayout.Width(100)); GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent(CurrentLang.LocateSettingsButton, CurrentLang.SettingsHighlightLabel))) { HighlightSettings(); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip))) { Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId)); } if (GUILayout.Button(new GUIContent(CurrentLang.SetupButton, CurrentLang.SetupServerCloudLabel))) { this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.Space(15); EditorGUILayout.Separator(); // documentation GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.DocumentationLabel, EditorStyles.boldLabel, GUILayout.Width(100)); GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent(CurrentLang.OpenPDFText, CurrentLang.OpenPDFTooltip))) { EditorUtility.OpenWithDefaultApp(DocumentationLocation); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenDevNetText, CurrentLang.OpenDevNetTooltip))) { Application.OpenURL(UrlDevNet); } GUI.skin.label.wordWrap = true; GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel); if (GUILayout.Button(CurrentLang.ComparisonPageButton)) { Application.OpenURL(UrlCompare); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenForumText, CurrentLang.OpenForumTooltip))) { Application.OpenURL(UrlForum); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } #endregion protected virtual void RegisterWithEmail(string email) { EditorUtility.DisplayProgressBar(CurrentLang.ConnectionTitle, CurrentLang.ConnectionInfo, 0.5f); string accountServiceType = string.Empty; if (PhotonEditorUtils.HasVoice) { accountServiceType = "voice"; } AccountService client = new AccountService(); client.RegisterByEmail(email, RegisterOrigin, accountServiceType); // this is the synchronous variant using the static RegisterOrigin. "result" is in the client EditorUtility.ClearProgressBar(); if (client.ReturnCode == 0) { this.mailOrAppId = client.AppId; PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId, null); if (PhotonEditorUtils.HasVoice) { PhotonNetwork.PhotonServerSettings.AppSettings.AppIdVoice = client.AppId2; } PhotonEditor.SaveSettings(); this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; } else { PhotonEditor.SaveSettings(); Debug.LogWarning(client.Message + " ReturnCode: " + client.ReturnCode); if (client.Message.Contains("registered")) { this.photonSetupState = PhotonSetupStates.EmailAlreadyRegistered; } else { EditorUtility.DisplayDialog(CurrentLang.ErrorTextTitle, client.Message, CurrentLang.OkButton); this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } } } // Pings PhotonServerSettings and makes it selected (show in Inspector) private static void HighlightSettings() { Selection.objects = new UnityEngine.Object[] {PhotonNetwork.PhotonServerSettings}; EditorGUIUtility.PingObject(PhotonNetwork.PhotonServerSettings); } // Marks settings object as dirty, so it gets saved. // unity 5.3 changes the usecase for SetDirty(). but here we don't modify a scene object! so it's ok to use private static void SaveSettings() { EditorUtility.SetDirty(PhotonNetwork.PhotonServerSettings); } #region RPC List Handling public static void UpdateRpcList() { List<string> additionalRpcs = new List<string>(); HashSet<string> currentRpcs = new HashSet<string>(); var types = GetAllSubTypesInScripts(typeof(MonoBehaviour)); foreach (var mono in types) { MethodInfo[] methods = mono.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (MethodInfo method in methods) { if (method.IsDefined(typeof(PunRPC), false)) { currentRpcs.Add(method.Name); if (!additionalRpcs.Contains(method.Name) && !PhotonNetwork.PhotonServerSettings.RpcList.Contains(method.Name)) { additionalRpcs.Add(method.Name); } } } } if (additionalRpcs.Count > 0) { // LIMITS RPC COUNT if (additionalRpcs.Count + PhotonNetwork.PhotonServerSettings.RpcList.Count >= byte.MaxValue) { if (currentRpcs.Count <= byte.MaxValue) { bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListTitle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton); if (clearList) { PhotonNetwork.PhotonServerSettings.RpcList.Clear(); PhotonNetwork.PhotonServerSettings.RpcList.AddRange(currentRpcs); } else { return; } } else { EditorUtility.DisplayDialog(CurrentLang.FullRPCListTitle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel); return; } } additionalRpcs.Sort(); Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PUN RPC-list"); PhotonNetwork.PhotonServerSettings.RpcList.AddRange(additionalRpcs); PhotonEditor.SaveSettings(); } } public static void ClearRpcList() { bool clearList = EditorUtility.DisplayDialog(CurrentLang.PUNNameReplaceTitle, CurrentLang.PUNNameReplaceLabel, CurrentLang.RPCListCleared, CurrentLang.CancelButton); if (clearList) { PhotonNetwork.PhotonServerSettings.RpcList.Clear(); Debug.LogWarning(CurrentLang.ServerSettingsCleanedWarning); } } public static System.Type[] GetAllSubTypesInScripts(System.Type aBaseClass) { var result = new System.Collections.Generic.List<System.Type>(); System.Reflection.Assembly[] AS = System.AppDomain.CurrentDomain.GetAssemblies(); foreach (var A in AS) { // this skips all but the Unity-scripted assemblies for RPC-list creation. You could remove this to search all assemblies in project if (!A.FullName.StartsWith("Assembly-")) { // Debug.Log("Skipping Assembly: " + A); continue; } //Debug.Log("Assembly: " + A.FullName); System.Type[] types = A.GetTypes(); foreach (var T in types) { if (T.IsSubclassOf(aBaseClass)) { result.Add(T); } } } return result.ToArray(); } #endregion } }
// 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! namespace Google.Apis.Verifiedaccess.v1 { /// <summary>The Verifiedaccess Service.</summary> public class VerifiedaccessService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public VerifiedaccessService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public VerifiedaccessService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Challenge = new ChallengeResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "verifiedaccess"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://verifiedaccess.googleapis.com/"; #else "https://verifiedaccess.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://verifiedaccess.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Chrome Verified Access API.</summary> public class Scope { /// <summary>Verify your enterprise credentials</summary> public static string Verifiedaccess = "https://www.googleapis.com/auth/verifiedaccess"; } /// <summary>Available OAuth 2.0 scope constants for use with the Chrome Verified Access API.</summary> public static class ScopeConstants { /// <summary>Verify your enterprise credentials</summary> public const string Verifiedaccess = "https://www.googleapis.com/auth/verifiedaccess"; } /// <summary>Gets the Challenge resource.</summary> public virtual ChallengeResource Challenge { get; } } /// <summary>A base abstract class for Verifiedaccess requests.</summary> public abstract class VerifiedaccessBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new VerifiedaccessBaseServiceRequest instance.</summary> protected VerifiedaccessBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Verifiedaccess parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "challenge" collection of methods.</summary> public class ChallengeResource { private const string Resource = "challenge"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ChallengeResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>CreateChallenge API</summary> /// <param name="body">The body of the request.</param> public virtual CreateRequest Create(Google.Apis.Verifiedaccess.v1.Data.Empty body) { return new CreateRequest(service, body); } /// <summary>CreateChallenge API</summary> public class CreateRequest : VerifiedaccessBaseServiceRequest<Google.Apis.Verifiedaccess.v1.Data.Challenge> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Verifiedaccess.v1.Data.Empty body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Verifiedaccess.v1.Data.Empty Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "create"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/challenge"; /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>VerifyChallengeResponse API</summary> /// <param name="body">The body of the request.</param> public virtual VerifyRequest Verify(Google.Apis.Verifiedaccess.v1.Data.VerifyChallengeResponseRequest body) { return new VerifyRequest(service, body); } /// <summary>VerifyChallengeResponse API</summary> public class VerifyRequest : VerifiedaccessBaseServiceRequest<Google.Apis.Verifiedaccess.v1.Data.VerifyChallengeResponseResult> { /// <summary>Constructs a new Verify request.</summary> public VerifyRequest(Google.Apis.Services.IClientService service, Google.Apis.Verifiedaccess.v1.Data.VerifyChallengeResponseRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Verifiedaccess.v1.Data.VerifyChallengeResponseRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "verify"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/challenge:verify"; /// <summary>Initializes Verify parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.Verifiedaccess.v1.Data { /// <summary>Result message for VerifiedAccess.CreateChallenge.</summary> public class Challenge : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Challenge generated with the old signing key (this will only be present during key rotation) /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("alternativeChallenge")] public virtual SignedData AlternativeChallenge { get; set; } /// <summary>Generated challenge</summary> [Newtonsoft.Json.JsonPropertyAttribute("challenge")] public virtual SignedData ChallengeValue { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical /// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc /// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON /// object `{}`. /// </summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The wrapper message of any data and its signature.</summary> public class SignedData : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The data to be signed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("data")] public virtual string Data { get; set; } /// <summary>The signature of the data field.</summary> [Newtonsoft.Json.JsonPropertyAttribute("signature")] public virtual string Signature { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>signed ChallengeResponse</summary> public class VerifyChallengeResponseRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The generated response to the challenge</summary> [Newtonsoft.Json.JsonPropertyAttribute("challengeResponse")] public virtual SignedData ChallengeResponse { get; set; } /// <summary> /// Service can optionally provide identity information about the device or user associated with the key. For an /// EMK, this value is the enrolled domain. For an EUK, this value is the user's email address. If present, this /// value will be checked against contents of the response, and verification will fail if there is no match. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("expectedIdentity")] public virtual string ExpectedIdentity { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Result message for VerifiedAccess.VerifyChallengeResponse.</summary> public class VerifyChallengeResponseResult : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Device enrollment id is returned in this field (for the machine response only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("deviceEnrollmentId")] public virtual string DeviceEnrollmentId { get; set; } /// <summary>Device permanent id is returned in this field (for the machine response only).</summary> [Newtonsoft.Json.JsonPropertyAttribute("devicePermanentId")] public virtual string DevicePermanentId { get; set; } /// <summary> /// Certificate Signing Request (in the SPKAC format, base64 encoded) is returned in this field. This field will /// be set only if device has included CSR in its challenge response. (the option to include CSR is now /// available for both user and machine responses) /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("signedPublicKeyAndChallenge")] public virtual string SignedPublicKeyAndChallenge { get; set; } /// <summary> /// For EMCert check, device permanent id is returned here. For EUCert check, signed_public_key_and_challenge /// [base64 encoded] is returned if present, otherwise empty string is returned. This field is deprecated, /// please use device_permanent_id or signed_public_key_and_challenge fields. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("verificationOutput")] public virtual string VerificationOutput { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.IO; using System.Management.Automation; using System.Xml; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell { /// <summary> /// /// Wraps Hitesh's xml serializer in such a way that it will select the proper serializer based on the data /// format. /// /// </summary> internal class Serialization { /// <summary> /// /// Describes the format of the data streamed between minishells, e.g. the allowed arguments to the minishell /// -outputformat and -inputformat command line parameters. /// /// </summary> internal enum DataFormat { /// <summary> /// /// text format -- i.e. stream text just as out-default would display it. /// /// </summary> Text = 0, /// <summary> /// /// XML-serialized format /// /// </summary> XML = 1, /// <summary> /// /// Indicates that the data should be discarded instead of processed. /// /// </summary> None = 2 } protected Serialization(DataFormat dataFormat, string streamName) { Dbg.Assert(!string.IsNullOrEmpty(streamName), "stream needs a name"); format = dataFormat; this.streamName = streamName; } protected static string XmlCliTag = "#< CLIXML"; protected string streamName; protected DataFormat format; } internal class WrappedSerializer : Serialization { internal WrappedSerializer(DataFormat dataFormat, string streamName, TextWriter output) : base(dataFormat, streamName) { Dbg.Assert(output != null, "output should have a value"); textWriter = output; switch (format) { case DataFormat.XML: XmlWriterSettings settings = new XmlWriterSettings(); settings.CheckCharacters = false; settings.OmitXmlDeclaration = true; _xmlWriter = XmlWriter.Create(textWriter, settings); _xmlSerializer = new Serializer(_xmlWriter); break; case DataFormat.Text: default: // do nothing; we'll just write to the TextWriter // or discard it. break; } } internal void Serialize(object o) { Serialize(o, this.streamName); } internal void Serialize(object o, string streamName) { switch (format) { case DataFormat.None: break; case DataFormat.XML: if (_firstCall) { _firstCall = false; textWriter.WriteLine(Serialization.XmlCliTag); } _xmlSerializer.Serialize(o, streamName); break; case DataFormat.Text: default: textWriter.Write(o.ToString()); break; } } internal void End() { switch (format) { case DataFormat.None: // do nothing break; case DataFormat.XML: _xmlSerializer.Done(); _xmlSerializer = null; break; case DataFormat.Text: default: // do nothing break; } } internal TextWriter textWriter; private XmlWriter _xmlWriter; private Serializer _xmlSerializer; private bool _firstCall = true; } internal class WrappedDeserializer : Serialization { internal WrappedDeserializer(DataFormat dataFormat, string streamName, TextReader input) : base(dataFormat, streamName) { Dbg.Assert(input != null, "input should have a value"); // If the data format is none - do nothing... if (dataFormat == DataFormat.None) return; textReader = input; _firstLine = textReader.ReadLine(); if (String.Compare(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase) == 0) { // format should be XML dataFormat = DataFormat.XML; } switch (format) { case DataFormat.XML: _xmlReader = XmlReader.Create(textReader); _xmlDeserializer = new Deserializer(_xmlReader); break; case DataFormat.Text: default: // do nothing; we'll just read from the TextReader break; } } internal object Deserialize() { object o; switch (format) { case DataFormat.None: _atEnd = true; return null; case DataFormat.XML: string unused; o = _xmlDeserializer.Deserialize(out unused); break; case DataFormat.Text: default: if (_atEnd) { return null; } if (_firstLine != null) { o = _firstLine; _firstLine = null; } else { o = textReader.ReadLine(); if (o == null) { _atEnd = true; } } break; } return o; } internal bool AtEnd { get { bool result = false; switch (format) { case DataFormat.None: _atEnd = true; result = true; break; case DataFormat.XML: result = _xmlDeserializer.Done(); break; case DataFormat.Text: default: result = _atEnd; break; } return result; } } internal void End() { switch (format) { case DataFormat.None: case DataFormat.XML: case DataFormat.Text: default: // do nothing break; } } internal TextReader textReader; private XmlReader _xmlReader; private Deserializer _xmlDeserializer; private string _firstLine; private bool _atEnd; } } // namespace
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Globalization; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Specialized; namespace System.Diagnostics { /// <devdoc> /// <para>Provides the <see langword='abstract '/>base class for the listeners who /// monitor trace and debug output.</para> /// </devdoc> public abstract class TraceListener : MarshalByRefObject, IDisposable { private int _indentLevel; private int _indentSize = 4; private TraceOptions _traceOptions = TraceOptions.None; private bool _needIndent = true; private StringDictionary _attributes; private string _listenerName; private TraceFilter _filter = null; /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Diagnostics.TraceListener'/> class.</para> /// </devdoc> protected TraceListener() { } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Diagnostics.TraceListener'/> class using the specified name as the /// listener.</para> /// </devdoc> protected TraceListener(string name) { _listenerName = name; } public StringDictionary Attributes { get { if (_attributes == null) _attributes = new StringDictionary(); return _attributes; } } /// <devdoc> /// <para> Gets or sets a name for this <see cref='System.Diagnostics.TraceListener'/>.</para> /// </devdoc> public virtual string Name { get { return (_listenerName == null) ? "" : _listenerName; } set { _listenerName = value; } } public virtual bool IsThreadSafe { get { return false; } } /// <devdoc> /// </devdoc> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <devdoc> /// </devdoc> protected virtual void Dispose(bool disposing) { return; } /// <devdoc> /// <para>When overridden in a derived class, flushes the output buffer.</para> /// </devdoc> public virtual void Flush() { return; } /// <devdoc> /// <para>Gets or sets the indent level.</para> /// </devdoc> public int IndentLevel { get { return _indentLevel; } set { _indentLevel = (value < 0) ? 0 : value; } } /// <devdoc> /// <para>Gets or sets the number of spaces in an indent.</para> /// </devdoc> public int IndentSize { get { return _indentSize; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(IndentSize), value, SR.TraceListenerIndentSize); _indentSize = value; } } public TraceFilter Filter { get { return _filter; } set { _filter = value; } } /// <devdoc> /// <para>Gets or sets a value indicating whether an indent is needed.</para> /// </devdoc> protected bool NeedIndent { get { return _needIndent; } set { _needIndent = value; } } public TraceOptions TraceOutputOptions { get { return _traceOptions; } set { if (((int)value >> 6) != 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _traceOptions = value; } } /// <devdoc> /// <para>When overridden in a derived class, closes the output stream /// so that it no longer receives tracing or debugging output.</para> /// </devdoc> public virtual void Close() { return; } protected internal virtual string[] GetSupportedAttributes() { return null; } public virtual void TraceTransfer(TraceEventCache eventCache, String source, int id, string message, Guid relatedActivityId) { TraceEvent(eventCache, source, TraceEventType.Transfer, id, message + ", relatedActivityId=" + relatedActivityId.ToString()); } /// <devdoc> /// <para>Emits or displays a message for an assertion that always fails.</para> /// </devdoc> public virtual void Fail(string message) { Fail(message, null); } /// <devdoc> /// <para>Emits or displays messages for an assertion that always fails.</para> /// </devdoc> public virtual void Fail(string message, string detailMessage) { StringBuilder failMessage = new StringBuilder(); failMessage.Append(SR.TraceListenerFail); failMessage.Append(" "); failMessage.Append(message); if (detailMessage != null) { failMessage.Append(" "); failMessage.Append(detailMessage); } WriteLine(failMessage.ToString()); } /// <devdoc> /// <para>When overridden in a derived class, writes the specified /// message to the listener you specify in the derived class.</para> /// </devdoc> public abstract void Write(string message); /// <devdoc> /// <para>Writes the name of the <paramref name="o"/> parameter to the listener you specify when you inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class.</para> /// </devdoc> public virtual void Write(object o) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) return; if (o == null) return; Write(o.ToString()); } /// <devdoc> /// <para>Writes a category name and a message to the listener you specify when you /// inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class.</para> /// </devdoc> public virtual void Write(string message, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) return; if (category == null) Write(message); else Write(category + ": " + ((message == null) ? string.Empty : message)); } /// <devdoc> /// <para>Writes a category name and the name of the <paramref name="o"/> parameter to the listener you /// specify when you inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class.</para> /// </devdoc> public virtual void Write(object o, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) return; if (category == null) Write(o); else Write(o == null ? "" : o.ToString(), category); } /// <devdoc> /// <para>Writes the indent to the listener you specify when you /// inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class, and resets the <see cref='TraceListener.NeedIndent'/> property to <see langword='false'/>.</para> /// </devdoc> protected virtual void WriteIndent() { NeedIndent = false; for (int i = 0; i < _indentLevel; i++) { if (_indentSize == 4) Write(" "); else { for (int j = 0; j < _indentSize; j++) { Write(" "); } } } } /// <devdoc> /// <para>When overridden in a derived class, writes a message to the listener you specify in /// the derived class, followed by a line terminator. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> public abstract void WriteLine(string message); /// <devdoc> /// <para>Writes the name of the <paramref name="o"/> parameter to the listener you specify when you inherit from the <see cref='System.Diagnostics.TraceListener'/> class, followed by a line terminator. The default line terminator is a /// carriage return followed by a line feed /// (\r\n).</para> /// </devdoc> public virtual void WriteLine(object o) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) return; WriteLine(o == null ? "" : o.ToString()); } /// <devdoc> /// <para>Writes a category name and a message to the listener you specify when you /// inherit from the <see cref='System.Diagnostics.TraceListener'/> class, /// followed by a line terminator. The default line terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> public virtual void WriteLine(string message, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) return; if (category == null) WriteLine(message); else WriteLine(category + ": " + ((message == null) ? string.Empty : message)); } /// <devdoc> /// <para>Writes a category /// name and the name of the <paramref name="o"/>parameter to the listener you /// specify when you inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class, followed by a line terminator. The default line terminator is a carriage /// return followed by a line feed (\r\n).</para> /// </devdoc> public virtual void WriteLine(object o, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) return; WriteLine(o == null ? "" : o.ToString(), category); } // new write methods used by TraceSource public virtual void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, object data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data)) return; WriteHeader(source, eventType, id); string datastring = String.Empty; if (data != null) datastring = data.ToString(); WriteLine(datastring); WriteFooter(eventCache); } public virtual void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) return; WriteHeader(source, eventType, id); StringBuilder sb = new StringBuilder(); if (data != null) { for (int i = 0; i < data.Length; i++) { if (i != 0) sb.Append(", "); if (data[i] != null) sb.Append(data[i].ToString()); } } WriteLine(sb.ToString()); WriteFooter(eventCache); } public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id) { TraceEvent(eventCache, source, eventType, id, String.Empty); } // All other TraceEvent methods come through this one. public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message)) return; WriteHeader(source, eventType, id); WriteLine(message); WriteFooter(eventCache); } public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string format, params object[] args) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args)) return; WriteHeader(source, eventType, id); if (args != null) WriteLine(String.Format(CultureInfo.InvariantCulture, format, args)); else WriteLine(format); WriteFooter(eventCache); } private void WriteHeader(String source, TraceEventType eventType, int id) { Write(String.Format(CultureInfo.InvariantCulture, "{0} {1}: {2} : ", source, eventType.ToString(), id.ToString(CultureInfo.InvariantCulture))); } private void WriteFooter(TraceEventCache eventCache) { if (eventCache == null) return; _indentLevel++; if (IsEnabled(TraceOptions.ProcessId)) WriteLine("ProcessId=" + eventCache.ProcessId); if (IsEnabled(TraceOptions.ThreadId)) WriteLine("ThreadId=" + eventCache.ThreadId); if (IsEnabled(TraceOptions.DateTime)) WriteLine("DateTime=" + eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture)); if (IsEnabled(TraceOptions.Timestamp)) WriteLine("Timestamp=" + eventCache.Timestamp); _indentLevel--; } internal bool IsEnabled(TraceOptions opts) { return (opts & TraceOutputOptions) != 0; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Chat { // An instance of this class exists for every active region internal class RegionState { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // This computation is not the real region center if the region is larger than 256. // This computation isn't fixed because there is not a handle back to the region. private static readonly OpenMetaverse.Vector3 CenterOfRegion = new OpenMetaverse.Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 20); private const int DEBUG_CHANNEL = 2147483647; private static int _idk_ = 0; // Runtime variables; these values are assigned when the // IrcState is created and remain constant thereafter. internal string Region = String.Empty; internal string Host = String.Empty; internal string LocX = String.Empty; internal string LocY = String.Empty; internal string IDK = String.Empty; // System values - used only be the IRC classes themselves internal ChannelState cs = null; // associated IRC configuration internal Scene scene = null; // associated scene internal IConfig config = null; // configuration file reference internal bool enabled = true; //AgentAlert internal bool showAlert = false; internal string alertMessage = String.Empty; internal IDialogModule dialogModule = null; // This list is used to keep track of who is here, and by // implication, who is not. internal List<IClientAPI> clients = new List<IClientAPI>(); // Setup runtime variable values public RegionState(Scene p_scene, IConfig p_config) { scene = p_scene; config = p_config; Region = scene.RegionInfo.RegionName; Host = scene.RegionInfo.ExternalHostName; LocX = Convert.ToString(scene.RegionInfo.RegionLocX); LocY = Convert.ToString(scene.RegionInfo.RegionLocY); IDK = Convert.ToString(_idk_++); showAlert = config.GetBoolean("alert_show", false); string alertServerInfo = String.Empty; if (showAlert) { bool showAlertServerInfo = config.GetBoolean("alert_show_serverinfo", true); if (showAlertServerInfo) alertServerInfo = String.Format("\nServer: {0}\nPort: {1}\nChannel: {2}\n\n", config.GetString("server", ""), config.GetString("port", ""), config.GetString("channel", "")); string alertPreMessage = config.GetString("alert_msg_pre", "This region is linked to Irc."); string alertPostMessage = config.GetString("alert_msg_post", "Everything you say in public chat can be listened."); alertMessage = String.Format("{0}\n{1}{2}", alertPreMessage, alertServerInfo, alertPostMessage); dialogModule = scene.RequestModuleInterface<IDialogModule>(); } // OpenChannel conditionally establishes a connection to the // IRC server. The request will either succeed, or it will // throw an exception. ChannelState.OpenChannel(this, config); // Connect channel to world events scene.EventManager.OnChatFromWorld += OnSimChat; scene.EventManager.OnChatFromClient += OnSimChat; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; m_log.InfoFormat("[IRC-Region {0}] Initialization complete", Region); } // Auto cleanup when abandoned ~RegionState() { if (cs != null) cs.RemoveRegion(this); } // Called by PostInitialize after all regions have been created public void Open() { cs.Open(this); enabled = true; } // Called by IRCBridgeModule.Close immediately prior to unload // of the module for this region. This happens when the region // is being removed or the server is terminating. The IRC // BridgeModule will remove the region from the region list // when control returns. public void Close() { enabled = false; cs.Close(this); } // The agent has disconnected, cleanup associated resources private void OnClientLoggedOut(IClientAPI client) { try { if (clients.Contains(client)) { if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { m_log.InfoFormat("[IRC-Region {0}]: {1} has left", Region, client.Name); //Check if this person is excluded from IRC if (!cs.ExcludeList.Contains(client.Name.ToLower())) { cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", client.Name)); } } client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; clients.Remove(client); } } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: ClientLoggedOut exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // This event indicates that the agent has left the building. We should treat that the same // as if the agent has logged out (we don't want cross-region noise - or do we?) private void OnMakeChildAgent(ScenePresence presence) { IClientAPI client = presence.ControllingClient; try { if (clients.Contains(client)) { if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname); m_log.DebugFormat("[IRC-Region {0}] {1} has left", Region, clientName); cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", clientName)); } client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; clients.Remove(client); } } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: MakeChildAgent exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // An agent has entered the region (from another region). Add the client to the locally // known clients list private void OnMakeRootAgent(ScenePresence presence) { IClientAPI client = presence.ControllingClient; try { if (!clients.Contains(client)) { client.OnLogout += OnClientLoggedOut; client.OnConnectionClosed += OnClientLoggedOut; clients.Add(client); if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname); m_log.DebugFormat("[IRC-Region {0}] {1} has arrived", Region, clientName); //Check if this person is excluded from IRC if (!cs.ExcludeList.Contains(clientName.ToLower())) { cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has arrived", clientName)); } } } if (dialogModule != null && showAlert) dialogModule.SendAlertToUser(client, alertMessage, true); } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: MakeRootAgent exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // This handler detects chat events int he virtual world. public void OnSimChat(Object sender, OSChatMessage msg) { // early return if this comes from the IRC forwarder if (cs.irc.Equals(sender)) return; // early return if nothing to forward if (msg.Message.Length == 0) return; // check for commands coming from avatars or in-world // object (if commands are enabled) if (cs.CommandsEnabled && msg.Channel == cs.CommandChannel) { m_log.DebugFormat("[IRC-Region {0}] command on channel {1}: {2}", Region, msg.Channel, msg.Message); string[] messages = msg.Message.Split(' '); string command = messages[0].ToLower(); try { switch (command) { // These commands potentially require a change in the // underlying ChannelState. case "server": cs.Close(this); cs = cs.UpdateServer(this, messages[1]); cs.Open(this); break; case "port": cs.Close(this); cs = cs.UpdatePort(this, messages[1]); cs.Open(this); break; case "channel": cs.Close(this); cs = cs.UpdateChannel(this, messages[1]); cs.Open(this); break; case "nick": cs.Close(this); cs = cs.UpdateNickname(this, messages[1]); cs.Open(this); break; // These may also (but are less likely) to require a // change in ChannelState. case "client-reporting": cs = cs.UpdateClientReporting(this, messages[1]); break; case "in-channel": cs = cs.UpdateRelayIn(this, messages[1]); break; case "out-channel": cs = cs.UpdateRelayOut(this, messages[1]); break; // These are all taken to be temporary changes in state // so the underlying connector remains intact. But note // that with regions sharing a connector, there could // be interference. case "close": enabled = false; cs.Close(this); break; case "connect": enabled = true; cs.Open(this); break; case "reconnect": enabled = true; cs.Close(this); cs.Open(this); break; // This one is harmless as far as we can judge from here. // If it is not, then the complaints will eventually make // that evident. default: m_log.DebugFormat("[IRC-Region {0}] Forwarding unrecognized command to IRC : {1}", Region, msg.Message); cs.irc.Send(msg.Message); break; } } catch (Exception ex) { m_log.WarnFormat("[IRC-Region {0}] error processing in-world command channel input: {1}", Region, ex.Message); m_log.Debug(ex); } return; } // The command channel remains enabled, even if we have otherwise disabled the IRC // interface. if (!enabled) return; // drop messages unless they are on a valid in-world // channel as configured in the ChannelState if (!cs.ValidInWorldChannels.Contains(msg.Channel)) { m_log.DebugFormat("[IRC-Region {0}] dropping message {1} on channel {2}", Region, msg, msg.Channel); return; } ScenePresence avatar = null; string fromName = msg.From; if (msg.Sender != null) { avatar = scene.GetScenePresence(msg.Sender.AgentId); if (avatar != null) fromName = avatar.Name; } if (!cs.irc.Connected) { m_log.WarnFormat("[IRC-Region {0}] IRCConnector not connected: dropping message from {1}", Region, fromName); return; } m_log.DebugFormat("[IRC-Region {0}] heard on channel {1} : {2}", Region, msg.Channel, msg.Message); if (null != avatar && cs.RelayChat && (msg.Channel == 0 || msg.Channel == DEBUG_CHANNEL)) { string txt = msg.Message; if (txt.StartsWith("/me ")) txt = String.Format("{0} {1}", fromName, msg.Message.Substring(4)); cs.irc.PrivMsg(cs.PrivateMessageFormat, fromName, Region, txt); return; } if (null == avatar && cs.RelayPrivateChannels && null != cs.AccessPassword && msg.Channel == cs.RelayChannelOut) { Match m = cs.AccessPasswordRegex.Match(msg.Message); if (null != m) { m_log.DebugFormat("[IRC] relaying message from {0}: {1}", m.Groups["avatar"].ToString(), m.Groups["message"].ToString()); cs.irc.PrivMsg(cs.PrivateMessageFormat, m.Groups["avatar"].ToString(), scene.RegionInfo.RegionName, m.Groups["message"].ToString()); } } } // This method gives the region an opportunity to interfere with // message delivery. For now we just enforce the enable/disable // flag. internal void OSChat(Object irc, OSChatMessage msg) { if (enabled) { // m_log.DebugFormat("[IRC-OSCHAT] Region {0} being sent message", region.Region); msg.Scene = scene; scene.EventManager.TriggerOnChatBroadcast(irc, msg); } } // This supports any local message traffic that might be needed in // support of command processing. At present there is none. internal void LocalChat(string msg) { if (enabled) { OSChatMessage osm = new OSChatMessage(); osm.From = "IRC Agent"; osm.Message = msg; osm.Type = ChatTypeEnum.Region; osm.Position = CenterOfRegion; osm.Sender = null; osm.SenderUUID = OpenMetaverse.UUID.Zero; // Hmph! Still? osm.Channel = 0; OSChat(this, osm); } } } }
/* * This file is part of AceQL C# Client SDK. * AceQL C# Client SDK: Remote SQL access over HTTP with AceQL HTTP. * Copyright (C) 2020, KawanSoft SAS * (http://www.kawansoft.com). All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AceQL.Client.Api.File; using AceQL.Client.Api.Metadata; using AceQL.Client.Api.Metadata.Dto; using AceQL.Client.Api.Util; using AceQL.Client.Src.Api.Http; using AceQL.Client.Src.Api.Util; using Newtonsoft.Json; using PCLStorage; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace AceQL.Client.Api.Http { /// <summary> /// Class <see cref="AceQLHttpApi"/>. Allows to create a Connection to the remote server /// </summary> internal class AceQLHttpApi { internal static readonly bool DEBUG; /// <summary> /// The server URL /// </summary> private String server ; private string username; /// <summary> /// The database /// </summary> private String database ; private char[] password ; /// <summary> /// The Web Proxy Uri /// </summary> private string proxyUri ; /// <summary> /// The credentials /// </summary> private ICredentials proxyCredentials ; private bool useCredentialCache; /// <summary> /// The timeout in milliseconds /// </summary> private int timeout; private bool enableDefaultSystemAuthentication; /// <summary> /// The request headers added by the user /// </summary> private Dictionary<string, string> requestHeaders = new Dictionary<string, string>(); /// <summary> /// The pretty printing /// </summary> const bool prettyPrinting = true; /// <summary> /// The gzip result /// </summary> bool gzipResult = true; /// <summary> /// The URL /// </summary> private string url; private string connectionString; private AceQLProgressIndicator progressIndicator; private AceQLCredential credential ; private CancellationToken cancellationToken; private bool useCancellationToken; internal SimpleTracer simpleTracer = new SimpleTracer(); // The HttpManager that contains the HtttClient to use internal HttpManager httpManager; /// <summary> /// Initializes a new instance of the <see cref="AceQLHttpApi"/> class. /// </summary> internal AceQLHttpApi() { } /// <summary> /// Initializes a new instance of the <see cref="AceQLHttpApi"/> class. /// </summary> /// <param name="connectionString">The connection string. /// </param>" /// <exception cref="System.ArgumentException">connectionString token does not contain a = separator: " + line</exception> internal AceQLHttpApi(String connectionString) { if (connectionString == null) { throw new ArgumentNullException("connectionString is null!"); } this.connectionString = connectionString; } internal AceQLHttpApi(string connectionString, AceQLCredential credential) : this(connectionString) { if (connectionString == null) { throw new ArgumentNullException("connectionString is null!"); } this.credential = credential ?? throw new ArgumentNullException("credential is null!"); } /// <summary> /// Resets the request headers. /// </summary> internal void ResetRequestHeaders() { requestHeaders = new Dictionary<string, string>(); } /// <summary> /// Adds A request header. This will be added at each server call. /// </summary> /// <param name="name">The header name.</param> /// <param name="value">The header value.</param> internal void AddRequestHeader(string name, string value) { requestHeaders.Add(name, value); } /// <summary> /// Opens this instance. /// </summary> /// <exception cref="ArgumentNullException"> if a required parameter extracted from connection string is missing. /// </exception> /// <exception cref="AceQLException"> if any other Exception occurs. /// </exception> internal async Task OpenAsync() { string sessionId; try { ConnectionStringDecoder connectionStringDecoder = new ConnectionStringDecoder(); connectionStringDecoder.Decode(connectionString); this.server = connectionStringDecoder.Server; this.database = connectionStringDecoder.Database; this.username = connectionStringDecoder.Username; this.password = connectionStringDecoder.Password; sessionId = connectionStringDecoder.SessionId; this.proxyUri = connectionStringDecoder.ProxyUri; this.proxyCredentials = connectionStringDecoder.ProxyCredentials; this.useCredentialCache = connectionStringDecoder.UseCredentialCache; this.timeout = connectionStringDecoder.Timeout; this.enableDefaultSystemAuthentication = connectionStringDecoder.EnableDefaultSystemAuthentication; if (connectionStringDecoder.EnableTrace) { simpleTracer.SetTraceOn(true); } await simpleTracer.TraceAsync("connectionString: " + connectionString).ConfigureAwait(false); await simpleTracer.TraceAsync("DecodeConnectionString() done!").ConfigureAwait(false); if (credential != null) { username = credential.Username; if (credential.Password != null) { password = credential.Password; } if (credential.SessionId != null) { sessionId = credential.SessionId; } } if (server == null) { throw new ArgumentNullException("Server keyword not found in connection string."); } if (password == null && sessionId == null) { throw new ArgumentNullException("Password keyword or SessionId keyword not found in connection string or AceQLCredential not set"); } if (database == null) { throw new ArgumentNullException("Database keyword not found in connection string."); } this.username = username ?? throw new ArgumentNullException("Username keyword not found in connection string or AceQLCredential not set."); // Create the HttpManager instance this.httpManager = new HttpManager(proxyUri, proxyCredentials, timeout, enableDefaultSystemAuthentication, requestHeaders); this.httpManager.SetSimpleTracer(simpleTracer); Debug("httpManager.Proxy: " + httpManager.Proxy); UserLoginStore userLoginStore = new UserLoginStore(server, username, database); if (sessionId != null) { userLoginStore.SetSessionId(sessionId); } if (userLoginStore.IsAlreadyLogged()) { await simpleTracer.TraceAsync("Get a new connection with get_connection").ConfigureAwait(false); sessionId = userLoginStore.GetSessionId(); String theUrl = server + "/session/" + sessionId + "/get_connection"; String result = await httpManager.CallWithGetAsync(theUrl).ConfigureAwait(false); await simpleTracer.TraceAsync("result: " + result).ConfigureAwait(false); ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), HttpStatusCode); } String connectionId = resultAnalyzer.GetValue("connection_id"); await simpleTracer.TraceAsync("Ok. New Connection created: " + connectionId).ConfigureAwait(false); this.url = server + "/session/" + sessionId + "/connection/" + connectionId + "/"; } else { await DummyGetCallForProxyAuthentication().ConfigureAwait(false); String theUrl = server + "/database/" + database + "/username/" + username + "/login"; ConsoleEmul.WriteLine("theUrl: " + theUrl); Dictionary<string, string> parametersMap = new Dictionary<string, string> { { "password", new String(password) }, { "client_version", VersionValues.VERSION} }; await simpleTracer.TraceAsync("Before CallWithPostAsyncReturnString: " + theUrl); String result = await httpManager.CallWithPostAsyncReturnString(new Uri(theUrl), parametersMap).ConfigureAwait(false); ConsoleEmul.WriteLine("result: " + result); await simpleTracer.TraceAsync("result: " + result).ConfigureAwait(false); ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), HttpStatusCode); } String theSessionId = resultAnalyzer.GetValue("session_id"); String theConnectionId = resultAnalyzer.GetValue("connection_id"); this.url = server + "/session/" + theSessionId + "/connection/" + theConnectionId + "/"; userLoginStore.SetSessionId(theSessionId); await simpleTracer.TraceAsync("OpenAsync url: " + this.url).ConfigureAwait(false); } } catch (Exception exception) { await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false); if (exception.GetType() == typeof(AceQLException)) { throw; } else { throw new AceQLException(exception.Message, 0, exception, HttpStatusCode); } } } /// <summary> /// Dummies the get call for proxy authentication. /// Hack to force a first GET on just aceql servlet if we are with a proxy, just to avoid system failure /// Because of a bug in C#, if a POST is done first to detect a 407 (proxy auth asked), HttpClient throws an Exception /// </summary> private async Task DummyGetCallForProxyAuthentication() { if ((this.httpManager.Proxy != null && proxyCredentials != null) || useCredentialCache) { String getResult = await httpManager.CallWithGetAsync(server).ConfigureAwait(false); ConsoleEmul.WriteLine(server + " - getResult: " + getResult); } } /// <summary> /// Gets a value indicating whether [gzip result] is on or off. /// </summary> /// <value><c>true</c> if [gzip result]; otherwise, <c>false</c>.</value> internal bool GzipResult { get { return gzipResult; } set { gzipResult = value; } } internal string Database { get { return database; } } /// <summary> /// The timeout in milliseconds /// </summary> internal int Timeout { get => timeout; } public AceQLCredential Credential { get { return credential; } set { credential = value; } } public string ConnectionString { get => connectionString; set => connectionString = value; } /// <summary> /// Says it use has passed a CancellationToken /// </summary> public bool UseCancellationToken { get => useCancellationToken; } /// <summary> /// Gets the HTTP status code of hte latsexecuted HTTP call /// </summary> /// <value>The HTTP status code.</value> public HttpStatusCode HttpStatusCode { get => httpManager.HttpStatusCode; } internal string GetDatabase() { return database; } internal string GetUsername() { return username; } internal string GetServer() { return server; } /// <summary> /// Calls the API no result. /// </summary> /// <param name="commandName">Name of the command.</param> /// <param name="commandOption">The command option.</param> /// <exception cref="System.ArgumentNullException">commandName is null!</exception> /// <exception cref="AceQLException"> /// HTTP_FAILURE" + " " + httpStatusDescription - 0 /// or /// or /// 0 /// </exception> internal async Task CallApiNoResultAsync(String commandName, String commandOption) { try { if (commandName == null) { throw new ArgumentNullException("commandName is null!"); } String result = await CallWithGetAsync(commandName, commandOption).ConfigureAwait(false); ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, httpManager.HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), httpManager.HttpStatusCode); } } catch (Exception exception) { await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false); if (exception.GetType() == typeof(AceQLException)) { throw; } else { throw new AceQLException(exception.Message, 0, exception, httpManager.HttpStatusCode); } } } /// <summary> /// Calls the API with result. /// </summary> /// <param name="commandName">Name of the command.</param> /// <param name="commandOption">The command option.</param> /// <exception cref="System.ArgumentNullException">commandName is null!</exception> /// <exception cref="AceQLException"> /// HTTP_FAILURE" + " " + httpStatusDescription - 0 /// or /// or /// 0 /// </exception> internal async Task<string> CallApiWithResultAsync(String commandName, String commandOption) { try { if (commandName == null) { throw new ArgumentNullException("commandName is null!"); } String result = await CallWithGetAsync(commandName, commandOption).ConfigureAwait(false); ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, httpManager.HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), httpManager.HttpStatusCode); } return resultAnalyzer.GetResult(); } catch (Exception exception) { await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false); if (exception.GetType() == typeof(AceQLException)) { throw; } else { throw new AceQLException(exception.Message, 0, exception, httpManager.HttpStatusCode); } } } /// <summary> /// Calls the with get. /// </summary> /// <param name="action">The action.</param> /// <param name="actionParameter">The action parameter.</param> /// <returns>String.</returns> private async Task<string> CallWithGetAsync(String action, String actionParameter) { String urlWithaction = this.url + action; if (actionParameter != null && actionParameter.Length != 0) { urlWithaction += "/" + actionParameter; } return await httpManager.CallWithGetAsync(urlWithaction).ConfigureAwait(false); } internal async Task<Stream> ExecuteQueryAsync(string cmdText, AceQLParameterCollection Parameters, bool isStoredProcedure, bool isPreparedStatement, Dictionary<string, string> statementParameters) { String action = "execute_query"; Dictionary<string, string> parametersMap = new Dictionary<string, string> { { "sql", cmdText }, { "prepared_statement", isPreparedStatement.ToString() }, { "stored_procedure", isStoredProcedure.ToString() }, { "column_types", "true" }, // Force column_types, mandatory for C# AceQLDataReader { "gzip_result", gzipResult.ToString() }, { "pretty_printing", prettyPrinting.ToString() } }; if (statementParameters != null) { List<string> keyList = new List<string>(statementParameters.Keys); foreach (string key in keyList) { parametersMap.Add(key, statementParameters[key]); } } Uri urlWithaction = new Uri(url + action); Stream input = await httpManager.CallWithPostAsync(urlWithaction, parametersMap).ConfigureAwait(false); return input; } internal async Task<int> ExecuteUpdateAsync(string sql, AceQLParameterCollection Parameters, bool isStoredProcedure, bool isPreparedStatement, Dictionary<string, string> statementParameters) { String action = "execute_update"; // Call raw execute if non query/select stored procedure. (Dirty!! To be corrected.) if (isStoredProcedure) { action = "execute"; } Dictionary<string, string> parametersMap = new Dictionary<string, string> { { "sql", sql }, { "prepared_statement", isPreparedStatement.ToString() }, { "stored_procedure", isStoredProcedure.ToString() } }; if (statementParameters != null) { List<string> keyList = new List<string>(statementParameters.Keys); foreach (string key in keyList) { parametersMap.Add(key, statementParameters[key]); } } Uri urlWithaction = new Uri(url + action); await simpleTracer.TraceAsync("url: " + url + action); foreach (KeyValuePair<String, String> p in parametersMap) { await simpleTracer.TraceAsync("parm: " + p.Key + " / " + p.Value); } string result = await httpManager.CallWithPostAsyncReturnString(urlWithaction, parametersMap).ConfigureAwait(false); Debug("result: " + result); ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, httpManager.HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), httpManager.HttpStatusCode); } int rowCount = resultAnalyzer.GetIntvalue("row_count"); if (isStoredProcedure) { UpdateOutParametersValues(result, Parameters); } return rowCount; } /// <summary> /// Update the OUT parameters values /// </summary> /// <param name="result"></param> /// <param name="parameters"></param> private static void UpdateOutParametersValues(string result, AceQLParameterCollection parameters) { //1) Build outParametersDict Dict of (paramerer names, values) dynamic xj = JsonConvert.DeserializeObject(result); dynamic xjParametersOutPername = xj.parameters_out_per_name; if (xjParametersOutPername == null) { return; } String dictStr = xjParametersOutPername.ToString(); Dictionary<string, string> outParametersDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(dictStr); //2) Scan foreach AceQLParameterCollection parameters and modify value if parameter name is in outParametersDict foreach (AceQLParameter parameter in parameters) { string parameterName = parameter.ParameterName; if (outParametersDict.ContainsKey(parameterName)) { parameter.Value = outParametersDict[parameterName]; } } } /// <summary> /// Uploads a Blob/Clob on the server. /// </summary> /// <param name="blobId">the Blob/Clob Id</param> /// <param name="stream">the stream of the Blob/Clob</param> /// <param name="totalLength">the total length of all BLOBs to upload</param> /// <returns>The result as JSON format.</returns> /// <exception cref="System.ArgumentNullException"> /// blobId is null! /// or /// file is null! /// </exception> /// <exception cref="System.IO.FileNotFoundException">file does not exist: " + file</exception> /// <exception cref="AceQLException">HTTP_FAILURE" + " " + httpStatusDescription - 0</exception> internal async Task<String> BlobUploadAsync(String blobId, Stream stream, long totalLength) { if (blobId == null) { throw new ArgumentNullException("blobId is null!"); } if (stream == null) { throw new ArgumentNullException("stream is null!"); } String theUrl = url + "blob_upload"; FormUploadStream formUploadStream = new FormUploadStream(); HttpResponseMessage response = null; response = await formUploadStream.UploadAsync(theUrl, proxyUri, proxyCredentials, timeout, enableDefaultSystemAuthentication, blobId, stream, totalLength, progressIndicator, cancellationToken, useCancellationToken, requestHeaders).ConfigureAwait(false); httpManager.HttpStatusCode = response.StatusCode; Stream streamResult = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); String result = null; if (streamResult != null) { result = new StreamReader(streamResult).ReadToEnd(); } return result; } /// <summary> /// Returns the server Blob/Clob length. /// </summary> /// <param name="blobId">the Blob/Clob Id.</param> /// <returns>the server Blob/Clob length.</returns> internal async Task<long> GetBlobLengthAsync(String blobId) { if (blobId == null) { throw new ArgumentNullException("blobId is null!"); } String action = "get_blob_length"; Dictionary<string, string> parametersMap = new Dictionary<string, string> { { "blob_id", blobId } }; String result = null; Uri urlWithaction = new Uri(url + action); using (Stream input = await httpManager.CallWithPostAsync(urlWithaction, parametersMap).ConfigureAwait(false)) { if (input != null) { result = new StreamReader(input).ReadToEnd(); } } ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), HttpStatusCode); } String lengthStr = resultAnalyzer.GetValue("length"); long length = Convert.ToInt64(lengthStr); return length; } /// <summary> /// Downloads a Blob/Clob from the server. /// </summary> /// <param name="blobId">the Blob/Clob Id</param> /// /// <returns>the Blob input stream</returns> internal async Task<Stream> BlobDownloadAsync(String blobId) { if (blobId == null) { throw new ArgumentNullException("blobId is null!"); } try { String theUrl = this.url + "/blob_download?blob_id=" + blobId; Stream input = await httpManager.CallWithGetReturnStreamAsync(theUrl); return input; } catch (Exception exception) { await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false); if (exception.GetType() == typeof(AceQLException)) { throw; } else { throw new AceQLException(exception.Message, 0, exception, HttpStatusCode); } } } /// <summary> /// Databases the schema download. /// </summary> /// <param name="format">The format.</param> /// <param name="tableName">Name of the table.</param> /// <returns>Task&lt;Stream&gt;.</returns> /// <exception cref="ArgumentNullException">format is null!</exception> /// <exception cref="AceQLException">0</exception> /// internal async Task<Stream> DbSchemaDownloadAsync(String format, String tableName) { if (format == null) { throw new ArgumentNullException("format is null!"); } try { String theUrl = this.url + "/metadata_query/db_schema_download?format=" + format; if (tableName != null) { tableName = tableName.ToLowerInvariant(); theUrl += "&table_name=" + tableName; } Stream input = await httpManager.CallWithGetReturnStreamAsync(theUrl); return input; } catch (Exception exception) { await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false); if (exception.GetType() == typeof(AceQLException)) { throw; } else { throw new AceQLException(exception.Message, 0, exception, HttpStatusCode); } } } /// <summary> /// Gets the database metadata. /// </summary> /// <returns>Task&lt;System.String&gt;.</returns> /// <exception cref="AceQLException"> /// 0 /// </exception> internal async Task<JdbcDatabaseMetaDataDto> GetDbMetadataAsync() { try { String commandName = "metadata_query/get_db_metadata"; String result = await CallWithGetAsync(commandName, null).ConfigureAwait(false); ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), HttpStatusCode); } JdbcDatabaseMetaDataDto jdbcDatabaseMetaDataDto = JsonConvert.DeserializeObject<JdbcDatabaseMetaDataDto>(result); return jdbcDatabaseMetaDataDto; } catch (Exception exception) { await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false); if (exception.GetType() == typeof(AceQLException)) { throw; } else { throw new AceQLException(exception.Message, 0, exception, HttpStatusCode); } } } /// <summary> /// Gets the table names. /// </summary> /// <param name="tableType">Type of the table.</param> /// <returns>Task&lt;TableNamesDto&gt;.</returns> /// <exception cref="AceQLException"> /// 0 /// </exception> internal async Task<TableNamesDto> GetTableNamesAsync(String tableType) { try { String action = "metadata_query/get_table_names"; Dictionary<string, string> parametersMap = new Dictionary<string, string>(); if (tableType != null) { parametersMap.Add("table_type", tableType); } String result = null; Uri urlWithaction = new Uri(url + action); using (Stream input = await httpManager.CallWithPostAsync(urlWithaction, parametersMap).ConfigureAwait(false)) { if (input != null) { result = new StreamReader(input).ReadToEnd(); } } ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), HttpStatusCode); } TableNamesDto tableNamesDto = JsonConvert.DeserializeObject<TableNamesDto>(result); return tableNamesDto; } catch (Exception exception) { await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false); if (exception.GetType() == typeof(AceQLException)) { throw; } else { throw new AceQLException(exception.Message, 0, exception, HttpStatusCode); } } } /// <summary> /// Gets the table. /// </summary> /// <param name="tableName">Name of the table.</param> /// <returns>Task&lt;TableDto&gt;.</returns> /// <exception cref="AceQLException"> /// 0 /// </exception> internal async Task<TableDto> GetTableAsync(String tableName) { try { String action = "metadata_query/get_table"; Dictionary<string, string> parametersMap = new Dictionary<string, string>(); parametersMap.Add("table_name", tableName); String result = null; Uri urlWithaction = new Uri(url + action); using (Stream input = await httpManager.CallWithPostAsync(urlWithaction, parametersMap).ConfigureAwait(false)) { if (input != null) { result = new StreamReader(input).ReadToEnd(); } } ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, HttpStatusCode); if (!resultAnalyzer.IsStatusOk()) { throw new AceQLException(resultAnalyzer.GetErrorMessage(), resultAnalyzer.GetErrorId(), resultAnalyzer.GetStackTrace(), HttpStatusCode); } TableDto tableDto = JsonConvert.DeserializeObject<TableDto>(result); return tableDto; } catch (Exception exception) { await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false); if (exception.GetType() == typeof(AceQLException)) { throw; } else { throw new AceQLException(exception.Message, 0, exception, HttpStatusCode); } } } /// <summary> /// To be call at end of each of each public aysnc(CancellationToken) calls to reset to false the usage of a CancellationToken with http calls /// and some reader calls. /// </summary> internal void ResetCancellationToken() { this.useCancellationToken = false; } /// <summary> /// Sets the CancellationToken asked by user to pass for the current public xxxAsync() call api. /// </summary> /// <param name="cancellationToken">CancellationToken asked by user to pass for the current public xxxAsync() call api.</param> internal void SetCancellationToken(CancellationToken cancellationToken) { this.useCancellationToken = true; this.cancellationToken = cancellationToken; } /// <summary> /// Returns the progress indicator variable that will store Blob/Clob upload or download progress between 0 and 100. /// </summary> /// <returns>The progress indicator variable that will store Blob/Clob upload or download progress between 0 and 100.</returns> internal AceQLProgressIndicator GetProgressIndicator() { return progressIndicator; } /// <summary> /// Sets the progress indicator variable that will store Blob/Clob upload or download progress between 0 and 100. Will be used by progress indicators to show the progress. /// </summary> /// <param name="progressIndicator">The progress variable.</param> internal void SetProgressIndicator(AceQLProgressIndicator progressIndicator) { this.progressIndicator = progressIndicator; } /// <summary> /// Returns the SDK current Version. /// </summary> /// <returns>the SDK current Version.</returns> internal static String GetVersion() { return Util.Version.GetVersion(); } /// <summary> /// Closes the connection to the remote database and closes the http session. /// </summary> public async Task CloseAsync() { await CallApiNoResultAsync("disconnect", null).ConfigureAwait(false); if (httpManager != null) { httpManager.Dispose(); } } internal static void Debug(string s) { if (DEBUG) { ConsoleEmul.WriteLine(DateTime.Now + " " + s); } } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class RadioGroup : android.widget.LinearLayout { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected RadioGroup(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public new partial class LayoutParams : android.widget.LinearLayout.LayoutParams { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; protected override void setBaseAttributes(android.content.res.TypedArray arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RadioGroup.LayoutParams.staticClass, "setBaseAttributes", "(Landroid/content/res/TypedArray;II)V", ref global::android.widget.RadioGroup.LayoutParams._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m1; public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RadioGroup.LayoutParams._m1.native == global::System.IntPtr.Zero) global::android.widget.RadioGroup.LayoutParams._m1 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m2; public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RadioGroup.LayoutParams._m2.native == global::System.IntPtr.Zero) global::android.widget.RadioGroup.LayoutParams._m2 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(II)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m3; public LayoutParams(int arg0, int arg1, float arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RadioGroup.LayoutParams._m3.native == global::System.IntPtr.Zero) global::android.widget.RadioGroup.LayoutParams._m3 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(IIF)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m4; public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RadioGroup.LayoutParams._m4.native == global::System.IntPtr.Zero) global::android.widget.RadioGroup.LayoutParams._m4 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m5; public LayoutParams(android.view.ViewGroup.MarginLayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RadioGroup.LayoutParams._m5.native == global::System.IntPtr.Zero) global::android.widget.RadioGroup.LayoutParams._m5 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$MarginLayoutParams;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static LayoutParams() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RadioGroup.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RadioGroup$LayoutParams")); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.RadioGroup.OnCheckedChangeListener_))] public partial interface OnCheckedChangeListener : global::MonoJavaBridge.IJavaObject { void onCheckedChanged(android.widget.RadioGroup arg0, int arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.RadioGroup.OnCheckedChangeListener))] internal sealed partial class OnCheckedChangeListener_ : java.lang.Object, OnCheckedChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnCheckedChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.widget.RadioGroup.OnCheckedChangeListener.onCheckedChanged(android.widget.RadioGroup arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RadioGroup.OnCheckedChangeListener_.staticClass, "onCheckedChanged", "(Landroid/widget/RadioGroup;I)V", ref global::android.widget.RadioGroup.OnCheckedChangeListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } static OnCheckedChangeListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RadioGroup.OnCheckedChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RadioGroup$OnCheckedChangeListener")); } } public delegate void OnCheckedChangeListenerDelegate(android.widget.RadioGroup arg0, int arg1); internal partial class OnCheckedChangeListenerDelegateWrapper : java.lang.Object, OnCheckedChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnCheckedChangeListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnCheckedChangeListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper.staticClass, global::android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper._m0); Init(@__env, handle); } static OnCheckedChangeListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RadioGroup_OnCheckedChangeListenerDelegateWrapper")); } } internal partial class OnCheckedChangeListenerDelegateWrapper { private OnCheckedChangeListenerDelegate myDelegate; public void onCheckedChanged(android.widget.RadioGroup arg0, int arg1) { myDelegate(arg0, arg1); } public static implicit operator OnCheckedChangeListenerDelegateWrapper(OnCheckedChangeListenerDelegate d) { global::android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper ret = new global::android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } private static global::MonoJavaBridge.MethodId _m0; public virtual void check(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RadioGroup.staticClass, "check", "(I)V", ref global::android.widget.RadioGroup._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public override void addView(android.view.View arg0, int arg1, android.view.ViewGroup.LayoutParams arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RadioGroup.staticClass, "addView", "(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V", ref global::android.widget.RadioGroup._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m2; protected override void onFinishInflate() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RadioGroup.staticClass, "onFinishInflate", "()V", ref global::android.widget.RadioGroup._m2); } private static global::MonoJavaBridge.MethodId _m3; protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.RadioGroup.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z", ref global::android.widget.RadioGroup._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.view.ViewGroup.OnHierarchyChangeListener OnHierarchyChangeListener { set { setOnHierarchyChangeListener(value); } } private static global::MonoJavaBridge.MethodId _m4; public override void setOnHierarchyChangeListener(android.view.ViewGroup.OnHierarchyChangeListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RadioGroup.staticClass, "setOnHierarchyChangeListener", "(Landroid/view/ViewGroup$OnHierarchyChangeListener;)V", ref global::android.widget.RadioGroup._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public virtual global::android.widget.RadioGroup.LayoutParams generateLayoutParams(android.util.AttributeSet arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.RadioGroup.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/widget/RadioGroup$LayoutParams;", ref global::android.widget.RadioGroup._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.RadioGroup.LayoutParams; } private static global::MonoJavaBridge.MethodId _m6; protected override global::android.widget.LinearLayout.LayoutParams generateDefaultLayoutParams() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.RadioGroup.staticClass, "generateDefaultLayoutParams", "()Landroid/widget/LinearLayout$LayoutParams;", ref global::android.widget.RadioGroup._m6) as android.widget.LinearLayout.LayoutParams; } private static global::MonoJavaBridge.MethodId _m7; public virtual void setOnCheckedChangeListener(android.widget.RadioGroup.OnCheckedChangeListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RadioGroup.staticClass, "setOnCheckedChangeListener", "(Landroid/widget/RadioGroup$OnCheckedChangeListener;)V", ref global::android.widget.RadioGroup._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnCheckedChangeListener(global::android.widget.RadioGroup.OnCheckedChangeListenerDelegate arg0) { setOnCheckedChangeListener((global::android.widget.RadioGroup.OnCheckedChangeListenerDelegateWrapper)arg0); } public new int CheckedRadioButtonId { get { return getCheckedRadioButtonId(); } } private static global::MonoJavaBridge.MethodId _m8; public virtual int getCheckedRadioButtonId() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.RadioGroup.staticClass, "getCheckedRadioButtonId", "()I", ref global::android.widget.RadioGroup._m8); } private static global::MonoJavaBridge.MethodId _m9; public virtual void clearCheck() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RadioGroup.staticClass, "clearCheck", "()V", ref global::android.widget.RadioGroup._m9); } private static global::MonoJavaBridge.MethodId _m10; public RadioGroup(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RadioGroup._m10.native == global::System.IntPtr.Zero) global::android.widget.RadioGroup._m10 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m11; public RadioGroup(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RadioGroup._m11.native == global::System.IntPtr.Zero) global::android.widget.RadioGroup._m11 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "<init>", "(Landroid/content/Context;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static RadioGroup() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RadioGroup.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RadioGroup")); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Avalonia.Interactivity; using Avalonia.VisualTree; namespace Avalonia.Input { /// <summary> /// Handles access keys for a window. /// </summary> public class AccessKeyHandler : IAccessKeyHandler { /// <summary> /// Defines the AccessKeyPressed attached event. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> AccessKeyPressedEvent = RoutedEvent.Register<RoutedEventArgs>( "AccessKeyPressed", RoutingStrategies.Bubble, typeof(AccessKeyHandler)); /// <summary> /// The registered access keys. /// </summary> private readonly List<Tuple<string, IInputElement>> _registered = new List<Tuple<string, IInputElement>>(); /// <summary> /// The window to which the handler belongs. /// </summary> private IInputRoot _owner; /// <summary> /// Whether access keys are currently being shown; /// </summary> private bool _showingAccessKeys; /// <summary> /// Whether to ignore the Alt KeyUp event. /// </summary> private bool _ignoreAltUp; /// <summary> /// Whether the AltKey is down. /// </summary> private bool _altIsDown; /// <summary> /// Element to restore folowing AltKey taking focus. /// </summary> private IInputElement _restoreFocusElement; /// <summary> /// Gets or sets the window's main menu. /// </summary> public IMainMenu MainMenu { get; set; } /// <summary> /// Sets the owner of the access key handler. /// </summary> /// <param name="owner">The owner.</param> /// <remarks> /// This method can only be called once, typically by the owner itself on creation. /// </remarks> public void SetOwner(IInputRoot owner) { Contract.Requires<ArgumentNullException>(owner != null); if (_owner != null) { throw new InvalidOperationException("AccessKeyHandler owner has already been set."); } _owner = owner; _owner.AddHandler(InputElement.KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); _owner.AddHandler(InputElement.KeyDownEvent, OnKeyDown, RoutingStrategies.Bubble); _owner.AddHandler(InputElement.KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); _owner.AddHandler(InputElement.PointerPressedEvent, OnPreviewPointerPressed, RoutingStrategies.Tunnel); } /// <summary> /// Registers an input element to be associated with an access key. /// </summary> /// <param name="accessKey">The access key.</param> /// <param name="element">The input element.</param> public void Register(char accessKey, IInputElement element) { var existing = _registered.FirstOrDefault(x => x.Item2 == element); if (existing != null) { _registered.Remove(existing); } _registered.Add(Tuple.Create(accessKey.ToString().ToUpper(), element)); } /// <summary> /// Unregisters the access keys associated with the input element. /// </summary> /// <param name="element">The input element.</param> public void Unregister(IInputElement element) { foreach (var i in _registered.Where(x => x.Item2 == element).ToList()) { _registered.Remove(i); } } /// <summary> /// Called when a key is pressed in the owner window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.LeftAlt) { _altIsDown = true; if (MainMenu == null || !MainMenu.IsOpen) { // TODO: Use FocusScopes to store the current element and restore it when context menu is closed. // Save currently focused input element. _restoreFocusElement = FocusManager.Instance.Current; // When Alt is pressed without a main menu, or with a closed main menu, show // access key markers in the window (i.e. "_File"). _owner.ShowAccessKeys = _showingAccessKeys = true; } else { // If the Alt key is pressed and the main menu is open, close the main menu. CloseMenu(); _ignoreAltUp = true; _restoreFocusElement?.Focus(); _restoreFocusElement = null; } // We always handle the Alt key. e.Handled = true; } else if (_altIsDown) { _ignoreAltUp = true; } } /// <summary> /// Called when a key is pressed in the owner window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnKeyDown(object sender, KeyEventArgs e) { bool menuIsOpen = MainMenu?.IsOpen == true; if (e.Key == Key.Escape && menuIsOpen) { // When the Escape key is pressed with the main menu open, close it. CloseMenu(); e.Handled = true; } else if ((e.Modifiers & InputModifiers.Alt) != 0 || menuIsOpen) { // If any other key is pressed with the Alt key held down, or the main menu is open, // find all controls who have registered that access key. var text = e.Key.ToString().ToUpper(); var matches = _registered .Where(x => x.Item1 == text && x.Item2.IsEffectivelyVisible) .Select(x => x.Item2); // If the menu is open, only match controls in the menu's visual tree. if (menuIsOpen) { matches = matches.Where(x => MainMenu.IsVisualAncestorOf(x)); } var match = matches.FirstOrDefault(); // If there was a match, raise the AccessKeyPressed event on it. if (match != null) { match.RaiseEvent(new RoutedEventArgs(AccessKeyPressedEvent)); e.Handled = true; } } } /// <summary> /// Handles the Alt/F10 keys being released in the window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewKeyUp(object sender, KeyEventArgs e) { switch (e.Key) { case Key.LeftAlt: _altIsDown = false; if (_ignoreAltUp) { _ignoreAltUp = false; } else if (_showingAccessKeys && MainMenu != null) { MainMenu.Open(); e.Handled = true; } break; case Key.F10: _owner.ShowAccessKeys = _showingAccessKeys = true; MainMenu.Open(); e.Handled = true; break; } } /// <summary> /// Handles pointer presses in the window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewPointerPressed(object sender, PointerEventArgs e) { if (_showingAccessKeys) { _owner.ShowAccessKeys = false; } } /// <summary> /// Closes the <see cref="MainMenu"/> and performs other bookeeping. /// </summary> private void CloseMenu() { MainMenu.Close(); _owner.ShowAccessKeys = _showingAccessKeys = false; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ComponentModel.CategoryAttribute.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ComponentModel { [AttributeUsage(AttributeTargets.All)] public partial class CategoryAttribute : Attribute { #region Methods and constructors public CategoryAttribute() { } public CategoryAttribute(string category) { } public override bool Equals(Object obj) { return default(bool); } public override int GetHashCode() { return default(int); } protected virtual new string GetLocalizedString(string value) { return default(string); } public override bool IsDefaultAttribute() { return default(bool); } #endregion #region Properties and indexers public static System.ComponentModel.CategoryAttribute Action { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Appearance { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Asynchronous { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Behavior { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public string Category { get { return default(string); } } public static System.ComponentModel.CategoryAttribute Data { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Default { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Design { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute DragDrop { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Focus { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Format { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Key { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Layout { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute Mouse { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } public static System.ComponentModel.CategoryAttribute WindowStyle { get { Contract.Ensures(Contract.Result<System.ComponentModel.CategoryAttribute>() != null); return default(System.ComponentModel.CategoryAttribute); } } #endregion } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.Collections.Generic; namespace AssetBundleGraph { [Serializable] public class ConnectionGUI { [SerializeField] private ConnectionData m_data; [SerializeField] private ConnectionPointData m_outputPoint; [SerializeField] private ConnectionPointData m_inputPoint; [SerializeField] private ConnectionGUIInspectorHelper m_inspector; [SerializeField] private string connectionButtonStyle; public string Label { get { return m_data.Label; } set { m_data.Label = value; } } public string Id { get { return m_data.Id; } } public string OutputNodeId { get { return m_outputPoint.NodeId; } } public string InputNodeId { get { return m_inputPoint.NodeId; } } public ConnectionPointData OutputPoint { get { return m_outputPoint; } } public ConnectionPointData InputPoint { get { return m_inputPoint; } } public ConnectionData Data { get { return m_data; } } public ConnectionGUIInspectorHelper Inspector { get { if(m_inspector == null) { m_inspector = ScriptableObject.CreateInstance<ConnectionGUIInspectorHelper>(); m_inspector.hideFlags = HideFlags.DontSave; } return m_inspector; } } private Rect m_buttonRect; public static ConnectionGUI LoadConnection (ConnectionData data, ConnectionPointData output, ConnectionPointData input) { return new ConnectionGUI( data, output, input ); } public static ConnectionGUI CreateConnection (string label, ConnectionPointData output, ConnectionPointData input) { return new ConnectionGUI( new ConnectionData(label, output, input), output, input ); } private ConnectionGUI (ConnectionData data, ConnectionPointData output, ConnectionPointData input) { UnityEngine.Assertions.Assert.IsTrue(output.IsOutput, "Given Output point is not output."); UnityEngine.Assertions.Assert.IsTrue(input.IsInput, "Given Input point is not input."); m_inspector = ScriptableObject.CreateInstance<ConnectionGUIInspectorHelper>(); m_inspector.hideFlags = HideFlags.DontSave; this.m_data = data; this.m_outputPoint = output; this.m_inputPoint = input; connectionButtonStyle = "sv_label_0"; } public Rect GetRect () { return m_buttonRect; } public void DrawConnection (List<NodeGUI> nodes, Dictionary<string, List<AssetReference>> assetGroups) { var startNode = nodes.Find(node => node.Id == OutputNodeId); if (startNode == null) { return; } var endNode = nodes.Find(node => node.Id == InputNodeId); if (endNode == null) { return; } var startPoint = NodeGUI.ScaleEffect(m_outputPoint.GetGlobalPosition(startNode)); var startV3 = new Vector3(startPoint.x, startPoint.y, 0f); var endPoint = NodeGUI.ScaleEffect(m_inputPoint.GetGlobalPosition(endNode)); var endV3 = new Vector3(endPoint.x, endPoint.y + 1f, 0f); var centerPoint = startPoint + ((endPoint - startPoint) / 2); var centerPointV3 = new Vector3(centerPoint.x, centerPoint.y, 0f); var pointDistance = (endPoint.x - startPoint.x) / 3f; if (pointDistance < AssetBundleGraphSettings.GUI.CONNECTION_CURVE_LENGTH) pointDistance = AssetBundleGraphSettings.GUI.CONNECTION_CURVE_LENGTH; var startTan = new Vector3(startPoint.x + pointDistance, startPoint.y, 0f); var endTan = new Vector3(endPoint.x - pointDistance, endPoint.y, 0f); var totalAssets = 0; var totalGroups = 0; if(assetGroups != null) { totalAssets = assetGroups.Select(v => v.Value.Count).Sum(); totalGroups = assetGroups.Keys.Count; } if(m_inspector != null && Selection.activeObject == m_inspector && m_inspector.connectionGUI == this) { Handles.DrawBezier(startV3, endV3, startTan, endTan, new Color(0.43f, 0.65f, 0.90f, 1.0f), null, 2f); } else { Handles.DrawBezier(startV3, endV3, startTan, endTan, ((totalAssets > 0) ? Color.white : Color.gray), null, 2f); } // draw connection label if connection's label is not normal. if (NodeGUI.scaleFactor == NodeGUI.SCALE_MAX) { GUIStyle labelStyle = new GUIStyle("WhiteMiniLabel"); labelStyle.alignment = TextAnchor.MiddleLeft; switch (Label){ case AssetBundleGraphSettings.DEFAULT_OUTPUTPOINT_LABEL: { // show nothing break; } case AssetBundleGraphSettings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL: { var labelWidth = labelStyle.CalcSize(new GUIContent(AssetBundleGraphSettings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL)); var labelPointV3 = new Vector3(centerPointV3.x - (labelWidth.x / 2), centerPointV3.y - 24f, 0f) ; Handles.Label(labelPointV3, AssetBundleGraphSettings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL, labelStyle); break; } default: { var labelWidth = labelStyle.CalcSize(new GUIContent(Label)); var labelPointV3 = new Vector3(centerPointV3.x - (labelWidth.x / 2), centerPointV3.y - 24f, 0f) ; Handles.Label(labelPointV3, Label, labelStyle); break; } } } string connectionLabel; if(totalGroups > 1) { connectionLabel = string.Format("{0}:{1}", totalAssets, totalGroups); } else { connectionLabel = string.Format("{0}", totalAssets); } var style = new GUIStyle(connectionButtonStyle); var labelSize = style.CalcSize(new GUIContent(connectionLabel)); m_buttonRect = new Rect(centerPointV3.x - labelSize.x/2f, centerPointV3.y - labelSize.y/2f, labelSize.x, 30f); if ( Event.current.type == EventType.ContextClick || (Event.current.type == EventType.MouseUp && Event.current.button == 1) ) { var rightClickPos = Event.current.mousePosition; if (m_buttonRect.Contains(rightClickPos)) { var menu = new GenericMenu(); menu.AddItem( new GUIContent("Delete"), false, () => { Delete(); } ); menu.ShowAsContext(); Event.current.Use(); } } if (GUI.Button(m_buttonRect, connectionLabel, style)) { Inspector.UpdateInspector(this, assetGroups); ConnectionGUIUtility.ConnectionEventHandler(new ConnectionEvent(ConnectionEvent.EventType.EVENT_CONNECTION_TAPPED, this)); } } public bool IsEqual (ConnectionPointData from, ConnectionPointData to) { return (m_outputPoint == from && m_inputPoint == to); } public void SetActive () { Selection.activeObject = Inspector; connectionButtonStyle = "sv_label_1"; } public void SetInactive () { connectionButtonStyle = "sv_label_0"; } public void Delete () { ConnectionGUIUtility.ConnectionEventHandler(new ConnectionEvent(ConnectionEvent.EventType.EVENT_CONNECTION_DELETED, this)); } } public static class NodeEditor_ConnectionListExtension { public static bool ContainsConnection(this List<ConnectionGUI> connections, ConnectionPointData output, ConnectionPointData input) { foreach (var con in connections) { if (con.IsEqual(output, input)) { return true; } } return false; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: RemotingConfigParser.cs ** ** Purpose: Parse remoting configuration files. ** ** ===========================================================*/ using System; using System.Collections; using System.IO; using System.Reflection; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Globalization; using System.Runtime.Versioning; namespace System.Runtime.Remoting.Activation { internal class RemotingXmlConfigFileData { // debug settings internal static volatile bool LoadTypes = false; // indicates whether we should attempt to load types in config files // // configuration entry storage classes (in alphabetical order) // There is one class for each type of entry in a remoting config file. // internal class ChannelEntry { internal String TypeName; internal String AssemblyName; internal Hashtable Properties; internal bool DelayLoad = false; internal ArrayList ClientSinkProviders = new ArrayList(); internal ArrayList ServerSinkProviders = new ArrayList(); internal ChannelEntry(String typeName, String assemblyName, Hashtable properties) { TypeName = typeName; AssemblyName = assemblyName; Properties = properties; } // ChannelEntry } // class ChannelEntry internal class ClientWellKnownEntry { internal String TypeName; internal String AssemblyName; internal String Url; internal ClientWellKnownEntry(String typeName, String assemName, String url) { TypeName = typeName; AssemblyName = assemName; Url = url; } } // class ClientWellKnownEntry internal class ContextAttributeEntry { internal String TypeName; internal String AssemblyName; internal Hashtable Properties; internal ContextAttributeEntry(String typeName, String assemName, Hashtable properties) { TypeName = typeName; AssemblyName = assemName; Properties = properties; } } // class ContextAttributeEntry internal class InteropXmlElementEntry { internal String XmlElementName; internal String XmlElementNamespace; internal String UrtTypeName; internal String UrtAssemblyName; internal InteropXmlElementEntry(String xmlElementName, String xmlElementNamespace, String urtTypeName, String urtAssemblyName) { XmlElementName = xmlElementName; XmlElementNamespace = xmlElementNamespace; UrtTypeName = urtTypeName; UrtAssemblyName = urtAssemblyName; } } // class InteropXmlElementEntry internal class CustomErrorsEntry { internal CustomErrorsModes Mode; internal CustomErrorsEntry(CustomErrorsModes mode) { Mode = mode; } } internal class InteropXmlTypeEntry { internal String XmlTypeName; internal String XmlTypeNamespace; internal String UrtTypeName; internal String UrtAssemblyName; internal InteropXmlTypeEntry(String xmlTypeName, String xmlTypeNamespace, String urtTypeName, String urtAssemblyName) { XmlTypeName = xmlTypeName; XmlTypeNamespace = xmlTypeNamespace; UrtTypeName = urtTypeName; UrtAssemblyName = urtAssemblyName; } } // class InteropXmlTypeEntry internal class LifetimeEntry { // If any of these are false, then the corresponding property wasn't specified // in the config file. internal bool IsLeaseTimeSet = false; internal bool IsRenewOnCallTimeSet = false; internal bool IsSponsorshipTimeoutSet = false; internal bool IsLeaseManagerPollTimeSet = false; private TimeSpan _leaseTime; private TimeSpan _renewOnCallTime; private TimeSpan _sponsorshipTimeout; private TimeSpan _leaseManagerPollTime; internal TimeSpan LeaseTime { get { BCLDebug.Assert(IsLeaseTimeSet == true, "LeaseTime not set"); return _leaseTime; } set { _leaseTime = value; IsLeaseTimeSet = true; } } internal TimeSpan RenewOnCallTime { get { BCLDebug.Assert(IsRenewOnCallTimeSet == true, "RenewOnCallTime not set"); return _renewOnCallTime; } set { _renewOnCallTime = value; IsRenewOnCallTimeSet = true; } } internal TimeSpan SponsorshipTimeout { get { BCLDebug.Assert(IsSponsorshipTimeoutSet == true, "SponsorShipTimeout not set"); return _sponsorshipTimeout; } set { _sponsorshipTimeout = value; IsSponsorshipTimeoutSet = true; } } internal TimeSpan LeaseManagerPollTime { get { BCLDebug.Assert(IsLeaseManagerPollTimeSet == true, "LeaseManagerPollTime not set"); return _leaseManagerPollTime; } set { _leaseManagerPollTime = value; IsLeaseManagerPollTimeSet = true; } } } // class LifetimeEntry internal class PreLoadEntry { // If TypeName is null, then all types in the assembly specified // should be preloaded. internal String TypeName; internal String AssemblyName; public PreLoadEntry(String typeName, String assemblyName) { TypeName = typeName; AssemblyName = assemblyName; } } // class PreLoadEntry internal class RemoteAppEntry { internal String AppUri; internal ArrayList WellKnownObjects = new ArrayList(); internal ArrayList ActivatedObjects = new ArrayList(); internal RemoteAppEntry(String appUri) { AppUri = appUri; } internal void AddWellKnownEntry(String typeName, String assemName, String url) { ClientWellKnownEntry cwke = new ClientWellKnownEntry(typeName, assemName, url); WellKnownObjects.Add(cwke); } internal void AddActivatedEntry(String typeName, String assemName, ArrayList contextAttributes) { TypeEntry te = new TypeEntry(typeName, assemName, contextAttributes); ActivatedObjects.Add(te); } } // class RemoteAppEntry internal class ServerWellKnownEntry : TypeEntry { internal String ObjectURI; internal WellKnownObjectMode ObjectMode; internal ServerWellKnownEntry( String typeName, String assemName, ArrayList contextAttributes, String objURI, WellKnownObjectMode objMode) : base(typeName, assemName, contextAttributes) { ObjectURI = objURI; ObjectMode = objMode; } } // class ServerWellKnownEntry internal class SinkProviderEntry { internal String TypeName; internal String AssemblyName; internal Hashtable Properties; internal ArrayList ProviderData = new ArrayList(); // array of SinkProviderData structures internal bool IsFormatter; // Is this a formatter sink provider? internal SinkProviderEntry(String typeName, String assemName, Hashtable properties, bool isFormatter) { TypeName = typeName; AssemblyName = assemName; Properties = properties; IsFormatter = isFormatter; } } // class SinkProviderEntry internal class TypeEntry { internal String TypeName; internal String AssemblyName; internal ArrayList ContextAttributes; internal TypeEntry(String typeName, String assemName, ArrayList contextAttributes) { TypeName = typeName; AssemblyName = assemName; ContextAttributes = contextAttributes; } } // class TypeEntry // // end of configuration entry storage classes // // // configuration data access // internal String ApplicationName = null; // application name internal LifetimeEntry Lifetime = null; // corresponds to top-level lifetime element internal bool UrlObjRefMode = RemotingConfigHandler.UrlObjRefMode; // should url obj ref's be used? internal CustomErrorsEntry CustomErrors = null; internal ArrayList ChannelEntries = new ArrayList(); internal ArrayList InteropXmlElementEntries = new ArrayList(); internal ArrayList InteropXmlTypeEntries = new ArrayList(); internal ArrayList PreLoadEntries = new ArrayList(); internal ArrayList RemoteAppEntries = new ArrayList(); internal ArrayList ServerActivatedEntries = new ArrayList(); internal ArrayList ServerWellKnownEntries = new ArrayList(); // // end of configuration data access // // // modify configuration data (for multiple entry entities) // internal void AddInteropXmlElementEntry(String xmlElementName, String xmlElementNamespace, String urtTypeName, String urtAssemblyName) { TryToLoadTypeIfApplicable(urtTypeName, urtAssemblyName); InteropXmlElementEntry ixee = new InteropXmlElementEntry( xmlElementName, xmlElementNamespace, urtTypeName, urtAssemblyName); InteropXmlElementEntries.Add(ixee); } internal void AddInteropXmlTypeEntry(String xmlTypeName, String xmlTypeNamespace, String urtTypeName, String urtAssemblyName) { TryToLoadTypeIfApplicable(urtTypeName, urtAssemblyName); InteropXmlTypeEntry ixte = new InteropXmlTypeEntry(xmlTypeName, xmlTypeNamespace, urtTypeName, urtAssemblyName); InteropXmlTypeEntries.Add(ixte); } internal void AddPreLoadEntry(String typeName, String assemblyName) { TryToLoadTypeIfApplicable(typeName, assemblyName); PreLoadEntry ple = new PreLoadEntry(typeName, assemblyName); PreLoadEntries.Add(ple); } internal RemoteAppEntry AddRemoteAppEntry(String appUri) { RemoteAppEntry rae = new RemoteAppEntry(appUri); RemoteAppEntries.Add(rae); return rae; } internal void AddServerActivatedEntry(String typeName, String assemName, ArrayList contextAttributes) { TryToLoadTypeIfApplicable(typeName, assemName); TypeEntry te = new TypeEntry(typeName, assemName, contextAttributes); ServerActivatedEntries.Add(te); } internal ServerWellKnownEntry AddServerWellKnownEntry(String typeName, String assemName, ArrayList contextAttributes, String objURI, WellKnownObjectMode objMode) { TryToLoadTypeIfApplicable(typeName, assemName); ServerWellKnownEntry swke = new ServerWellKnownEntry(typeName, assemName, contextAttributes, objURI, objMode); ServerWellKnownEntries.Add(swke); return swke; } // debug settings helper private void TryToLoadTypeIfApplicable(String typeName, String assemblyName) { if (!LoadTypes) return; Assembly asm = Assembly.Load(assemblyName); if (asm == null) { throw new RemotingException( Environment.GetResourceString("Remoting_AssemblyLoadFailed", assemblyName)); } Type type = asm.GetType(typeName, false, false); if (type == null) { throw new RemotingException( Environment.GetResourceString("Remoting_BadType", typeName)); } } } // RemotingXmlConfigFileData internal static class RemotingXmlConfigFileParser { // template arrays private static Hashtable _channelTemplates = CreateSyncCaseInsensitiveHashtable(); private static Hashtable _clientChannelSinkTemplates = CreateSyncCaseInsensitiveHashtable(); private static Hashtable _serverChannelSinkTemplates = CreateSyncCaseInsensitiveHashtable(); private static Hashtable CreateSyncCaseInsensitiveHashtable() { return Hashtable.Synchronized(CreateCaseInsensitiveHashtable()); } private static Hashtable CreateCaseInsensitiveHashtable() { return new Hashtable(StringComparer.InvariantCultureIgnoreCase); } public static RemotingXmlConfigFileData ParseDefaultConfiguration() { ConfigNode node; // <system.runtime.remoting> ConfigNode rootNode = new ConfigNode("system.runtime.remoting", null); /* <application> <channels> <channel ref="http client" displayName="http client (delay loaded)" delayLoadAsClientChannel="true" /> <channel ref="tcp client" displayName="tcp client (delay loaded)" delayLoadAsClientChannel="true" /> <channel ref="ipc client" displayName="ipc client (delay loaded)" delayLoadAsClientChannel="true" /> </channels> </application> */ ConfigNode appNode = new ConfigNode("application", rootNode); rootNode.Children.Add(appNode); ConfigNode channelsNode = new ConfigNode("channels", appNode); appNode.Children.Add(channelsNode); node = new ConfigNode("channel", appNode); node.Attributes.Add(new DictionaryEntry("ref", "http client")); node.Attributes.Add(new DictionaryEntry("displayName", "http client (delay loaded)")); node.Attributes.Add(new DictionaryEntry("delayLoadAsClientChannel", "true")); channelsNode.Children.Add(node); node = new ConfigNode("channel", appNode); node.Attributes.Add(new DictionaryEntry("ref", "tcp client")); node.Attributes.Add(new DictionaryEntry("displayName", "tcp client (delay loaded)")); node.Attributes.Add(new DictionaryEntry("delayLoadAsClientChannel", "true")); channelsNode.Children.Add(node); node = new ConfigNode("channel", appNode); node.Attributes.Add(new DictionaryEntry("ref", "ipc client")); node.Attributes.Add(new DictionaryEntry("displayName", "ipc client (delay loaded)")); node.Attributes.Add(new DictionaryEntry("delayLoadAsClientChannel", "true")); channelsNode.Children.Add(node); /* <channels> <channel id="http" type="System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <channel id="http client" type="System.Runtime.Remoting.Channels.Http.HttpClientChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <channel id="http server" type="System.Runtime.Remoting.Channels.Http.HttpServerChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <channel id="tcp" type="System.Runtime.Remoting.Channels.Tcp.TcpChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <channel id="tcp client" type="System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <channel id="tcp server" type="System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <channel id="ipc" type="System.Runtime.Remoting.Channels.Ipc.IpcChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <channel id="ipc client" type="System.Runtime.Remoting.Channels.Ipc.IpcClientChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <channel id="ipc server" type="System.Runtime.Remoting.Channels.Ipc.IpcServerChannel, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </channels> */ channelsNode = new ConfigNode("channels", rootNode); rootNode.Children.Add(channelsNode); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "http")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Http.HttpChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "http client")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Http.HttpClientChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "http server")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Http.HttpServerChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "tcp")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Tcp.TcpChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "tcp client")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "tcp server")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "ipc")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Ipc.IpcChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "ipc client")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Ipc.IpcClientChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); node = new ConfigNode("channel", channelsNode); node.Attributes.Add(new DictionaryEntry("id", "ipc server")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.Ipc.IpcServerChannel, " + AssemblyRef.SystemRuntimeRemoting)); channelsNode.Children.Add(node); /* <channelSinkProviders> <clientProviders> <formatter id="soap" type="System.Runtime.Remoting.Channels.SoapClientFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </clientProviders> <serverProviders> <formatter id="soap" type="System.Runtime.Remoting.Channels.SoapServerFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <provider id="wsdl" type="System.Runtime.Remoting.MetadataServices.SdlChannelSinkProvider, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </serverProviders> </channelSinkProviders> */ ConfigNode channelsSinkNode = new ConfigNode("channelSinkProviders", rootNode); rootNode.Children.Add(channelsSinkNode); ConfigNode clientProvidersNode = new ConfigNode("clientProviders", channelsSinkNode); channelsSinkNode.Children.Add(clientProvidersNode); node = new ConfigNode("formatter", clientProvidersNode); node.Attributes.Add(new DictionaryEntry("id", "soap")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.SoapClientFormatterSinkProvider, " + AssemblyRef.SystemRuntimeRemoting)); clientProvidersNode.Children.Add(node); node = new ConfigNode("formatter", clientProvidersNode); node.Attributes.Add(new DictionaryEntry("id", "binary")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider, " + AssemblyRef.SystemRuntimeRemoting)); clientProvidersNode.Children.Add(node); ConfigNode serverProvidersNode = new ConfigNode("serverProviders", channelsSinkNode); channelsSinkNode.Children.Add(serverProvidersNode); node = new ConfigNode("formatter", serverProvidersNode); node.Attributes.Add(new DictionaryEntry("id", "soap")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.SoapServerFormatterSinkProvider, " + AssemblyRef.SystemRuntimeRemoting)); serverProvidersNode.Children.Add(node); node = new ConfigNode("formatter", serverProvidersNode); node.Attributes.Add(new DictionaryEntry("id", "binary")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider, " + AssemblyRef.SystemRuntimeRemoting)); serverProvidersNode.Children.Add(node); node = new ConfigNode("provider", serverProvidersNode); node.Attributes.Add(new DictionaryEntry("id", "wsdl")); node.Attributes.Add(new DictionaryEntry("type", "System.Runtime.Remoting.MetadataServices.SdlChannelSinkProvider, " + AssemblyRef.SystemRuntimeRemoting)); serverProvidersNode.Children.Add(node); return ParseConfigNode(rootNode); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static RemotingXmlConfigFileData ParseConfigFile(String filename) { ConfigTreeParser parser = new ConfigTreeParser(); ConfigNode rootNode = parser.Parse(filename, "/configuration/system.runtime.remoting"); return ParseConfigNode(rootNode); } private static RemotingXmlConfigFileData ParseConfigNode(ConfigNode rootNode) { RemotingXmlConfigFileData configData = new RemotingXmlConfigFileData(); // check to see if this file has a system.runtime.remoting section if (rootNode == null) return null; // process attributes foreach (DictionaryEntry entry in rootNode.Attributes) { String key = entry.Key.ToString(); switch (key) { case "version": { // we ignore the version attribute because this may be used // by the configuration system break; } default: break; } // switch } // foreach ConfigNode appNode = null; // "application" node ConfigNode channelsNode = null; // "channels" node ConfigNode providerNode = null; // "channelSinkProviders" node ConfigNode debugNode = null; // "debug" node ConfigNode customErrorsNode = null; // "customErrors" node foreach (ConfigNode node in rootNode.Children) { switch (node.Name) { case "application": { // there can only be one application node in a config file if (appNode != null) ReportUniqueSectionError(rootNode, appNode, configData); appNode = node; break; } // case "application" case "channels": { if (channelsNode != null) ReportUniqueSectionError(rootNode, channelsNode, configData); channelsNode = node; break; } // case "channels" case "channelSinkProviders": { if (providerNode != null) ReportUniqueSectionError(rootNode, providerNode, configData); providerNode = node; break; } // case "channelSinkProviders" case "debug": { if (debugNode != null) ReportUniqueSectionError(rootNode, debugNode, configData); debugNode = node; break; } // case "debug" case "customErrors": { if (customErrorsNode != null) ReportUniqueSectionError(rootNode, customErrorsNode, configData); customErrorsNode = node; break; }// case "customErrors" default: break; } // switch } // foreach if (debugNode != null) ProcessDebugNode(debugNode, configData); if (providerNode != null) ProcessChannelSinkProviderTemplates(providerNode, configData); if (channelsNode != null) ProcessChannelTemplates(channelsNode, configData); if (appNode != null) ProcessApplicationNode(appNode, configData); if (customErrorsNode != null) ProcessCustomErrorsNode(customErrorsNode, configData); return configData; } // ParseConfigFile private static void ReportError(String errorStr, RemotingXmlConfigFileData configData) { // < throw new RemotingException(errorStr); } // ReportError // means section must be unique private static void ReportUniqueSectionError(ConfigNode parent, ConfigNode child, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_NodeMustBeUnique"), child.Name, parent.Name), configData); } // ReportUniqueSectionError private static void ReportUnknownValueError(ConfigNode node, String value, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_UnknownValue"), node.Name, value), configData); } // ReportUnknownValueError private static void ReportMissingAttributeError(ConfigNode node, String attributeName, RemotingXmlConfigFileData configData) { ReportMissingAttributeError(node.Name, attributeName, configData); } // ReportMissingAttributeError private static void ReportMissingAttributeError(String nodeDescription, String attributeName, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_RequiredXmlAttribute"), nodeDescription, attributeName), configData); } // ReportMissingAttributeError private static void ReportMissingTypeAttributeError(ConfigNode node, String attributeName, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_MissingTypeAttribute"), node.Name, attributeName), configData); } // ReportMissingAttributeError private static void ReportMissingXmlTypeAttributeError(ConfigNode node, String attributeName, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_MissingXmlTypeAttribute"), node.Name, attributeName), configData); } // ReportMissingAttributeError private static void ReportInvalidTimeFormatError(String time, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_InvalidTimeFormat"), time), configData); } // ReportInvalidTypeFormatError // If nodes can be represented as a template, only a template version // can have an 'id' attribute private static void ReportNonTemplateIdAttributeError(ConfigNode node, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_NonTemplateIdAttribute"), node.Name), configData); } // ReportNonTemplateIdAttributeError private static void ReportTemplateCannotReferenceTemplateError( ConfigNode node, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_TemplateCannotReferenceTemplate"), node.Name), configData); } // ReportTemplateCannotReferenceTemplateError private static void ReportUnableToResolveTemplateReferenceError( ConfigNode node, String referenceName, RemotingXmlConfigFileData configData) { ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_UnableToResolveTemplate"), node.Name, referenceName), configData); } // ReportUnableToResolveTemplateReferenceError private static void ReportAssemblyVersionInfoPresent( String assemName, String entryDescription, RemotingXmlConfigFileData configData) { // for some entries, version information is not allowed in the assembly name ReportError( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Config_VersionPresent"), assemName, entryDescription), configData); } // ReportAssemblyVersionInfoPresent private static void ProcessDebugNode(ConfigNode node, RemotingXmlConfigFileData configData) { foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "loadTypes": RemotingXmlConfigFileData.LoadTypes = Convert.ToBoolean((String)entry.Value, CultureInfo.InvariantCulture); break; default: break; } // switch } // foreach } // ProcessDebugNode private static void ProcessApplicationNode(ConfigNode node, RemotingXmlConfigFileData configData) { foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); if (key.Equals("name")) configData.ApplicationName = (String)entry.Value; } foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "channels": ProcessChannelsNode(childNode, configData); break; case "client": ProcessClientNode(childNode, configData); break; case "lifetime": ProcessLifetimeNode(node, childNode, configData); break; case "service": ProcessServiceNode(childNode, configData); break; case "soapInterop": ProcessSoapInteropNode(childNode, configData); break; default: break; } // switch } // foreach } // ProcessApplicationNode private static void ProcessCustomErrorsNode(ConfigNode node, RemotingXmlConfigFileData configData) { foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); if (key.Equals("mode")) { string value = (string)entry.Value; CustomErrorsModes mode = CustomErrorsModes.On; if (String.Compare(value, "on", StringComparison.OrdinalIgnoreCase) == 0) mode = CustomErrorsModes.On; else if (String.Compare(value, "off", StringComparison.OrdinalIgnoreCase) == 0) mode = CustomErrorsModes.Off; else if (String.Compare(value, "remoteonly", StringComparison.OrdinalIgnoreCase) == 0) mode = CustomErrorsModes.RemoteOnly; else ReportUnknownValueError(node, value, configData); configData.CustomErrors = new RemotingXmlConfigFileData.CustomErrorsEntry(mode); } } } private static void ProcessLifetimeNode(ConfigNode parentNode, ConfigNode node, RemotingXmlConfigFileData configData) { if (configData.Lifetime != null) ReportUniqueSectionError(node, parentNode, configData); configData.Lifetime = new RemotingXmlConfigFileData.LifetimeEntry(); foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "leaseTime": configData.Lifetime.LeaseTime = ParseTime((String)entry.Value, configData); break; case "sponsorshipTimeout": configData.Lifetime.SponsorshipTimeout = ParseTime((String)entry.Value, configData); break; case "renewOnCallTime": configData.Lifetime.RenewOnCallTime = ParseTime((String)entry.Value, configData); break; case "leaseManagerPollTime": configData.Lifetime.LeaseManagerPollTime = ParseTime((String)entry.Value, configData); break; default: break; } // switch } // foreach } // ProcessLifetimeNode // appears under "application" private static void ProcessServiceNode(ConfigNode node, RemotingXmlConfigFileData configData) { foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "wellknown": ProcessServiceWellKnownNode(childNode, configData); break; case "activated": ProcessServiceActivatedNode(childNode, configData); break; default: break; } // switch } // foreach } // ProcessServiceNode // appears under "application" private static void ProcessClientNode(ConfigNode node, RemotingXmlConfigFileData configData) { String remoteAppUri = null; // process attributes foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "url": remoteAppUri = (String)entry.Value; break; case "displayName": break; // displayName is ignored (used by config utility for labelling the application) default: break; } // switch } // foreach attribute RemotingXmlConfigFileData.RemoteAppEntry remoteApp = configData.AddRemoteAppEntry(remoteAppUri); // process child nodes foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "wellknown": ProcessClientWellKnownNode(childNode, configData, remoteApp); break; case "activated": ProcessClientActivatedNode(childNode, configData, remoteApp); break; default: break; } // switch } // foreach child node // if there are any activated entries, we require a remote app url. if ((remoteApp.ActivatedObjects.Count > 0) && (remoteAppUri == null)) ReportMissingAttributeError(node, "url", configData); } // ProcessClientNode // appears under "application" private static void ProcessSoapInteropNode(ConfigNode node, RemotingXmlConfigFileData configData) { // process attributes foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "urlObjRef": { configData.UrlObjRefMode = Convert.ToBoolean(entry.Value, CultureInfo.InvariantCulture); break; } default: break; } // switch } // foreach attribute foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "preLoad": ProcessPreLoadNode(childNode, configData); break; case "interopXmlElement": ProcessInteropXmlElementNode(childNode, configData); break; case "interopXmlType": ProcessInteropXmlTypeNode(childNode, configData); break; default: break; } // switch } } // ProcessSoapInteropNode // appears under "application" private static void ProcessChannelsNode(ConfigNode node, RemotingXmlConfigFileData configData) { foreach (ConfigNode childNode in node.Children) { if (childNode.Name.Equals("channel")) { RemotingXmlConfigFileData.ChannelEntry channelEntry = ProcessChannelsChannelNode(childNode, configData, false); configData.ChannelEntries.Add(channelEntry); } } // foreach } // ProcessInteropNode // appears under "application/service" private static void ProcessServiceWellKnownNode(ConfigNode node, RemotingXmlConfigFileData configData) { String typeName = null; String assemName = null; ArrayList contextAttributes = new ArrayList(); String objectURI = null; WellKnownObjectMode objectMode = WellKnownObjectMode.Singleton; bool objectModeFound = false; // examine attributes foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "displayName": break; // displayName is ignored (used by config utility for labelling the application) case "mode": { String value = (String)entry.Value; objectModeFound = true; if (String.CompareOrdinal(value, "Singleton") == 0) objectMode = WellKnownObjectMode.Singleton; else if (String.CompareOrdinal(value, "SingleCall") == 0) objectMode = WellKnownObjectMode.SingleCall; else objectModeFound = false; break; } // case "mode" case "objectUri": objectURI = (String)entry.Value; break; case "type": { RemotingConfigHandler.ParseType((String)entry.Value, out typeName, out assemName); break; } // case "type" default: break; } // switch } // foreach // examine child nodes foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "contextAttribute": { contextAttributes.Add(ProcessContextAttributeNode(childNode, configData)); break; } // case "contextAttribute" case "lifetime": { // < break; } // case "lifetime" default: break; } // switch } // foreach child node // check for errors if (!objectModeFound) { ReportError( Environment.GetResourceString("Remoting_Config_MissingWellKnownModeAttribute"), configData); } if ((typeName == null) || (assemName == null)) ReportMissingTypeAttributeError(node, "type", configData); // objectURI defaults to typeName if not specified if (objectURI == null) objectURI = typeName + ".soap"; configData.AddServerWellKnownEntry(typeName, assemName, contextAttributes, objectURI, objectMode); } // ProcessServiceWellKnownNode // appears under "application/service" private static void ProcessServiceActivatedNode(ConfigNode node, RemotingXmlConfigFileData configData) { String typeName = null; String assemName = null; ArrayList contextAttributes = new ArrayList(); foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "type": { RemotingConfigHandler.ParseType((String)entry.Value, out typeName, out assemName); break; } // case "type" default: break; } // switch } // foreach attribute foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "contextAttribute": { contextAttributes.Add(ProcessContextAttributeNode(childNode, configData)); break; } // case "contextattribute" case "lifetime": { // < break; } // case "lifetime" default: break; } // switch } // foreach child node // check for errors if ((typeName == null) || (assemName == null)) ReportMissingTypeAttributeError(node, "type", configData); if (CheckAssemblyNameForVersionInfo(assemName)) ReportAssemblyVersionInfoPresent(assemName, "service activated", configData); configData.AddServerActivatedEntry(typeName, assemName, contextAttributes); } // ProcessServiceActivatedNode // appears under "application/client" private static void ProcessClientWellKnownNode(ConfigNode node, RemotingXmlConfigFileData configData, RemotingXmlConfigFileData.RemoteAppEntry remoteApp) { String typeName = null; String assemName = null; String url = null; foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "displayName": break; // displayName is ignored (used by config utility for labelling the application) case "type": { RemotingConfigHandler.ParseType((String)entry.Value, out typeName, out assemName); break; } // case "type" case "url": url = (String)entry.Value; break; default: break; } // switch } // foreach // check for errors if (url == null) ReportMissingAttributeError("WellKnown client", "url", configData); if ((typeName == null) || (assemName == null)) ReportMissingTypeAttributeError(node, "type", configData); if (CheckAssemblyNameForVersionInfo(assemName)) ReportAssemblyVersionInfoPresent(assemName, "client wellknown", configData); remoteApp.AddWellKnownEntry(typeName, assemName, url); } // ProcessClientWellKnownNode // appears under "application/client" private static void ProcessClientActivatedNode(ConfigNode node, RemotingXmlConfigFileData configData, RemotingXmlConfigFileData.RemoteAppEntry remoteApp) { String typeName = null; String assemName = null; ArrayList contextAttributes = new ArrayList(); foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "type": { RemotingConfigHandler.ParseType((String)entry.Value, out typeName, out assemName); break; } // case "type" default: break; } // switch } // foreach foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "contextAttribute": { contextAttributes.Add(ProcessContextAttributeNode(childNode, configData)); break; } // case "contextAttribute" default: break; } // switch } // foreach child node // check for errors if ((typeName == null) || (assemName == null)) ReportMissingTypeAttributeError(node, "type", configData); remoteApp.AddActivatedEntry(typeName, assemName, contextAttributes); } // ProcessClientActivatedNode private static void ProcessInteropXmlElementNode(ConfigNode node, RemotingXmlConfigFileData configData) { String xmlElementName = null; String xmlElementNamespace = null; String urtTypeName = null; String urtAssemName = null; foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "xml": { RemotingConfigHandler.ParseType((String)entry.Value, out xmlElementName, out xmlElementNamespace); break; } case "clr": { RemotingConfigHandler.ParseType((String)entry.Value, out urtTypeName, out urtAssemName); break; } // case "clr" default: break; } // switch } // foreach // check for errors if ((xmlElementName == null) || (xmlElementNamespace == null)) ReportMissingXmlTypeAttributeError(node, "xml", configData); if ((urtTypeName == null) || (urtAssemName == null)) ReportMissingTypeAttributeError(node, "clr", configData); configData.AddInteropXmlElementEntry(xmlElementName, xmlElementNamespace, urtTypeName, urtAssemName); } // ProcessInteropNode private static void ProcessInteropXmlTypeNode(ConfigNode node, RemotingXmlConfigFileData configData) { String xmlTypeName = null; String xmlTypeNamespace = null; String urtTypeName = null; String urtAssemName = null; foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "xml": { RemotingConfigHandler.ParseType((String)entry.Value, out xmlTypeName, out xmlTypeNamespace); break; } case "clr": { RemotingConfigHandler.ParseType((String)entry.Value, out urtTypeName, out urtAssemName); break; } // case "type" default: break; } // switch } // foreach // check for errors if ((xmlTypeName == null) || (xmlTypeNamespace == null)) ReportMissingXmlTypeAttributeError(node, "xml", configData); if ((urtTypeName == null) || (urtAssemName == null)) ReportMissingTypeAttributeError(node, "clr", configData); configData.AddInteropXmlTypeEntry(xmlTypeName, xmlTypeNamespace, urtTypeName, urtAssemName); } // ProcessInteropNode private static void ProcessPreLoadNode(ConfigNode node, RemotingXmlConfigFileData configData) { String typeName = null; String assemblyName = null; foreach (DictionaryEntry entry in node.Attributes) { String key = entry.Key.ToString(); switch (key) { case "type": { RemotingConfigHandler.ParseType((String)entry.Value, out typeName, out assemblyName); break; } case "assembly": { assemblyName = (String)entry.Value; break; } // case "type" default: break; } // switch } // foreach // check for errors if (assemblyName == null) { ReportError( Environment.GetResourceString("Remoting_Config_PreloadRequiresTypeOrAssembly"), configData); } configData.AddPreLoadEntry(typeName, assemblyName); } // ProcessPreLoadNode private static RemotingXmlConfigFileData.ContextAttributeEntry ProcessContextAttributeNode(ConfigNode node, RemotingXmlConfigFileData configData) { String typeName = null; String assemName = null; Hashtable properties = CreateCaseInsensitiveHashtable(); // examine attributes foreach (DictionaryEntry entry in node.Attributes) { String lowercaseKey = ((String)entry.Key).ToLower(CultureInfo.InvariantCulture); switch (lowercaseKey) { case "type": { RemotingConfigHandler.ParseType((String)entry.Value, out typeName, out assemName); break; } // case "type" default: properties[lowercaseKey] = entry.Value; break; } // switch } // foreach attribute // check for errors if ((typeName == null) || (assemName == null)) ReportMissingTypeAttributeError(node, "type", configData); RemotingXmlConfigFileData.ContextAttributeEntry attributeEntry = new RemotingXmlConfigFileData.ContextAttributeEntry( typeName, assemName, properties); return attributeEntry; } // ProcessContextAttributeNode // appears under "application/client" private static RemotingXmlConfigFileData.ChannelEntry ProcessChannelsChannelNode(ConfigNode node, RemotingXmlConfigFileData configData, bool isTemplate) { String id = null; String typeName = null; String assemName = null; Hashtable properties = CreateCaseInsensitiveHashtable(); bool delayLoad = false; RemotingXmlConfigFileData.ChannelEntry channelTemplate = null; // examine attributes foreach (DictionaryEntry entry in node.Attributes) { String keyStr = (String)entry.Key; switch (keyStr) { case "displayName": break; // displayName is ignored (used by config utility for labelling the application) case "id": { if (!isTemplate) { ReportNonTemplateIdAttributeError(node, configData); } else id = ((String)entry.Value).ToLower(CultureInfo.InvariantCulture); break; } // case "id" case "ref": { if (isTemplate) { ReportTemplateCannotReferenceTemplateError(node, configData); } else { channelTemplate = (RemotingXmlConfigFileData.ChannelEntry)_channelTemplates[entry.Value]; if (channelTemplate == null) { ReportUnableToResolveTemplateReferenceError( node, entry.Value.ToString(), configData); } else { // load template data typeName = channelTemplate.TypeName; assemName = channelTemplate.AssemblyName; foreach (DictionaryEntry param in channelTemplate.Properties) { properties[param.Key] = param.Value; } } } break; } // case "ref" case "type": { RemotingConfigHandler.ParseType((String)entry.Value, out typeName, out assemName); break; } // case "type" case "delayLoadAsClientChannel": { delayLoad = Convert.ToBoolean((String)entry.Value, CultureInfo.InvariantCulture); break; } // case "delayLoadAsClientChannel" default: properties[keyStr] = entry.Value; break; } // switch } // foreach attribute // check for errors if ((typeName == null) || (assemName == null)) ReportMissingTypeAttributeError(node, "type", configData); RemotingXmlConfigFileData.ChannelEntry channelEntry = new RemotingXmlConfigFileData.ChannelEntry(typeName, assemName, properties); channelEntry.DelayLoad = delayLoad; // look for sink providers foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "clientProviders": ProcessSinkProviderNodes(childNode, channelEntry, configData, false); break; case "serverProviders": ProcessSinkProviderNodes(childNode, channelEntry, configData, true); break; default: break; } // switch } // foreach // if we reference a template and didn't specify any sink providers, we // should copy over the providers from the template if (channelTemplate != null) { // < if (channelEntry.ClientSinkProviders.Count == 0) { channelEntry.ClientSinkProviders = channelTemplate.ClientSinkProviders; } if (channelEntry.ServerSinkProviders.Count == 0) { channelEntry.ServerSinkProviders = channelTemplate.ServerSinkProviders; } } if (isTemplate) { _channelTemplates[id] = channelEntry; return null; } else { return channelEntry; } } // ProcessChannelsChannelNode // // process sink provider data // private static void ProcessSinkProviderNodes(ConfigNode node, RemotingXmlConfigFileData.ChannelEntry channelEntry, RemotingXmlConfigFileData configData, bool isServer) { // look for sink providers foreach (ConfigNode childNode in node.Children) { RemotingXmlConfigFileData.SinkProviderEntry entry = ProcessSinkProviderNode(childNode, configData, false, isServer); if (isServer) channelEntry.ServerSinkProviders.Add(entry); else channelEntry.ClientSinkProviders.Add(entry); } // foreach } // ProcessSinkProviderNodes private static RemotingXmlConfigFileData.SinkProviderEntry ProcessSinkProviderNode(ConfigNode node, RemotingXmlConfigFileData configData, bool isTemplate, bool isServer) { bool isFormatter = false; // Make sure the node is a "formatter" or "provider". String nodeName = node.Name; if (nodeName.Equals("formatter")) isFormatter = true; else if (nodeName.Equals("provider")) isFormatter = false; else { ReportError( Environment.GetResourceString("Remoting_Config_ProviderNeedsElementName"), configData); } String id = null; String typeName = null; String assemName = null; Hashtable properties = CreateCaseInsensitiveHashtable(); RemotingXmlConfigFileData.SinkProviderEntry template = null; foreach (DictionaryEntry entry in node.Attributes) { String keyStr = (String)entry.Key; switch (keyStr) { case "id": { if (!isTemplate) { // only templates can have the id attribute ReportNonTemplateIdAttributeError(node, configData); } else id = (String)entry.Value; break; } // case "id" case "ref": { if (isTemplate) { ReportTemplateCannotReferenceTemplateError(node, configData); } else { if (isServer) { template = (RemotingXmlConfigFileData.SinkProviderEntry) _serverChannelSinkTemplates[entry.Value]; } else { template = (RemotingXmlConfigFileData.SinkProviderEntry) _clientChannelSinkTemplates[entry.Value]; } if (template == null) { ReportUnableToResolveTemplateReferenceError( node, entry.Value.ToString(), configData); } else { // load template data typeName = template.TypeName; assemName = template.AssemblyName; foreach (DictionaryEntry param in template.Properties) { properties[param.Key] = param.Value; } } } break; } // case "ref" case "type": { RemotingConfigHandler.ParseType((String)entry.Value, out typeName, out assemName); break; } // case "type" default: properties[keyStr] = entry.Value; break; } // switch } // foreach attribute // check for errors if ((typeName == null) || (assemName == null)) ReportMissingTypeAttributeError(node, "type", configData); RemotingXmlConfigFileData.SinkProviderEntry sinkProviderEntry = new RemotingXmlConfigFileData.SinkProviderEntry(typeName, assemName, properties, isFormatter); // start storing sink data foreach (ConfigNode childNode in node.Children) { SinkProviderData providerData = ProcessSinkProviderData(childNode, configData); sinkProviderEntry.ProviderData.Add(providerData); } // foreach // if we reference a template and didn't specify any provider data, we // should copy over the provider data from the template if (template != null) { // < if (sinkProviderEntry.ProviderData.Count == 0) { sinkProviderEntry.ProviderData = template.ProviderData; } } if (isTemplate) { if (isServer) _serverChannelSinkTemplates[id] = sinkProviderEntry; else _clientChannelSinkTemplates[id] = sinkProviderEntry; return null; } else { return sinkProviderEntry; } } // ProcessSinkProviderNode // providerData will already contain an object with the same name as the config node private static SinkProviderData ProcessSinkProviderData(ConfigNode node, RemotingXmlConfigFileData configData) { SinkProviderData providerData = new SinkProviderData(node.Name); foreach (ConfigNode childNode in node.Children) { SinkProviderData childData = ProcessSinkProviderData(childNode, configData); providerData.Children.Add(childData); } foreach (DictionaryEntry entry in node.Attributes) { providerData.Properties[entry.Key] = entry.Value; } return providerData; } // ProcessSinkProviderData // // process template nodes // private static void ProcessChannelTemplates(ConfigNode node, RemotingXmlConfigFileData configData) { foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "channel": ProcessChannelsChannelNode(childNode, configData, true); break; default: break; } // switch } } // ProcessChannelTemplates private static void ProcessChannelSinkProviderTemplates(ConfigNode node, RemotingXmlConfigFileData configData) { foreach (ConfigNode childNode in node.Children) { switch (childNode.Name) { case "clientProviders": ProcessChannelProviderTemplates(childNode, configData, false); break; case "serverProviders": ProcessChannelProviderTemplates(childNode, configData, true); break; default: break; } } } // ProcessChannelSinkProviderTemplates private static void ProcessChannelProviderTemplates(ConfigNode node, RemotingXmlConfigFileData configData, bool isServer) { foreach (ConfigNode childNode in node.Children) { ProcessSinkProviderNode(childNode, configData, true, isServer); } } // ProcessClientProviderTemplates // assembly names aren't supposed to have version information in some places // so we use this method to make sure that only an assembly name is // specified. private static bool CheckAssemblyNameForVersionInfo(String assemName) { if (assemName == null) return false; // if the assembly name has a comma, we know that version information is present int index = assemName.IndexOf(','); return (index != -1); } // CheckAssemblyNameForVersionInfo private static TimeSpan ParseTime(String time, RemotingXmlConfigFileData configData) { // time formats, e.g. // 10D -> 10 days // 10H -> 10 hours // 10M -> 10 minutes // 10S -> 10 seconds // 10MS -> 10 milliseconds // 10 -> default is seconds: 10 seconds String specifiedTime = time; String metric = "s"; // default is seconds int metricLength = 0; char lastChar = ' '; if (time.Length > 0) lastChar = time[time.Length - 1]; TimeSpan span = TimeSpan.FromSeconds(0); try { if (!Char.IsDigit(lastChar)) { if (time.Length == 0) ReportInvalidTimeFormatError(specifiedTime, configData); time = time.ToLower(CultureInfo.InvariantCulture); metricLength = 1; if (time.EndsWith("ms", StringComparison.Ordinal)) metricLength = 2; metric = time.Substring(time.Length - metricLength, metricLength); } int value = Int32.Parse(time.Substring(0, time.Length - metricLength), CultureInfo.InvariantCulture); switch (metric) { case "d": span = TimeSpan.FromDays(value); break; case "h": span = TimeSpan.FromHours(value); break; case "m": span = TimeSpan.FromMinutes(value); break; case "s": span = TimeSpan.FromSeconds(value); break; case "ms": span = TimeSpan.FromMilliseconds(value); break; default: { ReportInvalidTimeFormatError(specifiedTime, configData); break; } } // switch } catch (Exception) { ReportInvalidTimeFormatError(specifiedTime, configData); } return span; } // ParseTime } // class RemotingXmlConfigFileParser } // namespace
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. #define APIHACK using System; using System.Collections ; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Threading; using mshtml; using OpenLiveWriter.BlogClient; using OpenLiveWriter.BlogClient.Clients; using OpenLiveWriter.BlogClient.Detection; using OpenLiveWriter.BlogClient.Providers; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.CoreServices.Progress; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Localization; namespace OpenLiveWriter.BlogClient.Detection { public class BlogServiceDetector : BlogServiceDetectorBase { public BlogServiceDetector(IBlogClientUIContext uiContext, Control hiddenBrowserParentControl, string localBlogId, string homepageUrl, IBlogCredentialsAccessor credentials) : base(uiContext, hiddenBrowserParentControl, localBlogId, homepageUrl, credentials) { } protected override object DetectBlogService(IProgressHost progressHost) { using ( BlogClientUIContextSilentMode uiContextScope = new BlogClientUIContextSilentMode() ) //supress prompting for credentials { try { // get the weblog homepage and rsd service description if available IHTMLDocument2 weblogDOM = GetWeblogHomepageDOM(progressHost) ; // while we have the DOM available, scan for a writer manifest url if ( _manifestDownloadInfo == null ) { string manifestUrl = WriterEditingManifest.DiscoverUrl(_homepageUrl, weblogDOM) ; if ( manifestUrl != String.Empty ) _manifestDownloadInfo = new WriterEditingManifestDownloadInfo(manifestUrl); } string html = weblogDOM != null ? HTMLDocumentHelper.HTMLDocToString(weblogDOM) : null ; bool detectionSucceeded = false; if (!detectionSucceeded) detectionSucceeded = AttemptGenericAtomLinkDetection(_homepageUrl, html, !ApplicationDiagnostics.PreferAtom); if (!detectionSucceeded) detectionSucceeded = AttemptBloggerDetection(_homepageUrl, html); if (!detectionSucceeded) { RsdServiceDescription rsdServiceDescription = GetRsdServiceDescription(progressHost, weblogDOM) ; // if there was no rsd service description or we fail to auto-configure from the // rsd description then move on to other auto-detection techniques if ( !(detectionSucceeded = AttemptRsdBasedDetection( progressHost, rsdServiceDescription ) ) ) { // try detection by analyzing the homepage url and contents UpdateProgress( progressHost, 75, Res.Get(StringId.ProgressAnalyzingHomepage) ) ; if ( weblogDOM != null ) detectionSucceeded = AttemptHomepageBasedDetection(_homepageUrl, html) ; else detectionSucceeded = AttemptUrlBasedDetection(_homepageUrl) ; // if we successfully detected then see if we can narrow down // to a specific weblog if ( detectionSucceeded ) { if ( !BlogProviderParameters.UrlContainsParameters(_postApiUrl) ) { // we detected the provider, now see if we can detect the weblog id // (or at lease the list of the user's weblogs) UpdateProgress( progressHost, 80, Res.Get(StringId.ProgressAnalyzingWeblogList) ) ; AttemptUserBlogDetection() ; } } } } if (!detectionSucceeded && html != null) AttemptGenericAtomLinkDetection(_homepageUrl, html, false); // finished UpdateProgress( progressHost, 100, String.Empty ) ; } catch( OperationCancelledException ) { // WasCancelled == true } catch ( BlogClientOperationCancelledException ) { Cancel(); // WasCancelled == true } catch ( BlogAccountDetectorException ex ) { if (ApplicationDiagnostics.AutomationMode) Trace.WriteLine(ex.ToString()); else Trace.Fail(ex.ToString()); // ErrorOccurred == true } catch ( Exception ex ) { // ErrorOccurred == true Trace.Fail(ex.Message, ex.ToString()); ReportError(MessageId.WeblogDetectionUnexpectedError, ex.Message) ; } return this ; } } private bool AttemptGenericAtomLinkDetection(string url, string html, bool preferredOnly) { const string GENERIC_ATOM_PROVIDER_ID = "D48F1B5A-06E6-4f0f-BD76-74F34F520792"; if (html == null) return false; HtmlExtractor ex = new HtmlExtractor(html); if (ex .SeekWithin("<head>", "<body>") .SeekWithin("<link href rel='service' type='application/atomsvc+xml'>", "</head>") .Success) { IBlogProvider atomProvider = BlogProviderManager.FindProvider(GENERIC_ATOM_PROVIDER_ID); BeginTag bt = ex.Element as BeginTag; if (preferredOnly) { string classes = bt.GetAttributeValue("class"); if (classes == null) return false; if (!Regex.IsMatch(classes, @"\bpreferred\b")) return false; } string linkUrl = bt.GetAttributeValue("href"); Debug.WriteLine("Atom service link detected in the blog homepage"); _providerId = atomProvider.Id; _serviceName = atomProvider.Name; _clientType = atomProvider.ClientType; _blogName = string.Empty; _postApiUrl = linkUrl; IBlogClient client = BlogClientManager.CreateClient(atomProvider.ClientType, _postApiUrl, _credentials); client.VerifyCredentials(); _usersBlogs = client.GetUsersBlogs(); if (_usersBlogs.Length == 1) { _hostBlogId = _usersBlogs[0].Id; _blogName = _usersBlogs[0].Name; /* if (_usersBlogs[0].HomepageUrl != null && _usersBlogs[0].HomepageUrl.Length > 0) _homepageUrl = _usersBlogs[0].HomepageUrl; */ } // attempt to read the blog name from the homepage title if (_blogName == null || _blogName.Length == 0) { HtmlExtractor ex2 = new HtmlExtractor(html); if (ex2.Seek("<title>").Success) { _blogName = ex2.CollectTextUntil("title"); } } return true; } return false; } private class BloggerGeneratorCriterion : IElementPredicate { public bool IsMatch(Element e) { BeginTag tag = e as BeginTag; if (tag == null) return false; if (!tag.NameEquals("meta")) return false; if (tag.GetAttributeValue("name") != "generator") return false; string generator = tag.GetAttributeValue("content"); if (generator == null || CaseInsensitiveComparer.DefaultInvariant.Compare("blogger", generator) != 0) return false; return true; } } /// <summary> /// Do special Blogger-specific detection logic. We want to /// use the Blogger Atom endpoints specified in the HTML, not /// the Blogger endpoint in the RSD. /// </summary> private bool AttemptBloggerDetection( string homepageUrl, string html ) { html = html ?? ""; BloggerDetectionHelper bloggerDetectionHelper = new BloggerDetectionHelper(homepageUrl, html); if (!bloggerDetectionHelper.IsBlogger()) return false; const string BLOGGER_ATOM_PROVIDER_ID = "B6F817C3-9D39-45c1-A634-EAC792B8A635"; IBlogProvider bloggerProvider = BlogProviderManager.FindProvider(BLOGGER_ATOM_PROVIDER_ID); if (bloggerProvider == null) { Trace.Fail("Couldn't retrieve Blogger provider"); return false; } _providerId = bloggerProvider.Id; _serviceName = bloggerProvider.Name; _clientType = bloggerProvider.ClientType; _postApiUrl = "http://www.blogger.com/feeds/default/blogs"; BlogAccountDetector blogAccountDetector = new BlogAccountDetector(bloggerProvider.ClientType, "http://www.blogger.com", _credentials); if (blogAccountDetector.ValidateService()) { _usersBlogs = blogAccountDetector.UsersBlogs; foreach (BlogInfo blog in _usersBlogs) { string blogHomepageUrl = blog.HomepageUrl; if (NormalizeBloggerHomepageUrl(blogHomepageUrl) == NormalizeBloggerHomepageUrl(homepageUrl)) { _hostBlogId = blog.Id; _postApiUrl = blog.Id; _blogName = blog.Name; return true; } } // We didn't find the specific blog, but we'll prompt the user with the list of blogs return true; } else { AuthenticationErrorOccurred = blogAccountDetector.Exception is BlogClientAuthenticationException; ReportErrorAndFail(blogAccountDetector.ErrorMessageType, blogAccountDetector.ErrorMessageParams); return false; } } private string NormalizeBloggerHomepageUrl(string url) { // trim and uppercase url = url.Trim().ToUpperInvariant(); // if the url has any ONE of the common suffixes, it is dropped and // the string is returned. foreach (string commonSuffix in new string[] {"/index.html", "/", "/index.htm", "/index.php", "/default.htm", "/default.html"}) if (url.EndsWith(commonSuffix, StringComparison.OrdinalIgnoreCase)) return url.Substring(0, url.Length - commonSuffix.Length); return url; } private bool AttemptRsdBasedDetection( IProgressHost progressHost, RsdServiceDescription rsdServiceDescription ) { // always return alse for null description if ( rsdServiceDescription == null ) return false ; string providerId = String.Empty ; BlogAccount blogAccount = null ; // check for a match on rsd engine link foreach ( IBlogProvider provider in BlogProviderManager.Providers ) { blogAccount = provider.DetectAccountFromRsdHomepageLink(rsdServiceDescription) ; if ( blogAccount != null ) { providerId = provider.Id ; break; } } // if none found on engine link, match on engine name if ( blogAccount == null ) { foreach ( IBlogProvider provider in BlogProviderManager.Providers ) { blogAccount = provider.DetectAccountFromRsdEngineName(rsdServiceDescription) ; if ( blogAccount != null ) { providerId = provider.Id ; break; } } } // No provider associated with the RSD file, try to gin one up (will only // work if the RSD file contains an API for one of our supported client types) if ( blogAccount == null ) { // try to create one from RSD blogAccount = BlogAccountFromRsdServiceDescription.Create(rsdServiceDescription); } // if we have an rsd-detected weblog if ( blogAccount != null ) { // confirm that the credentials are OK UpdateProgress( progressHost, 65, Res.Get(StringId.ProgressVerifyingInterface) ) ; BlogAccountDetector blogAccountDetector = new BlogAccountDetector( blogAccount.ClientType, blogAccount.PostApiUrl, _credentials ) ; if ( blogAccountDetector.ValidateService() ) { // copy basic account info _providerId = providerId ; _serviceName = blogAccount.ServiceName; _clientType = blogAccount.ClientType ; _hostBlogId = blogAccount.BlogId; _postApiUrl = blogAccount.PostApiUrl; // see if we can improve on the blog name guess we already // have from the <title> element of the homepage BlogInfo blogInfo = blogAccountDetector.DetectAccount(_homepageUrl, _hostBlogId) ; if ( blogInfo != null ) _blogName = blogInfo.Name ; } else { // report user-authorization error ReportErrorAndFail(blogAccountDetector.ErrorMessageType, blogAccountDetector.ErrorMessageParams ) ; } // success! return true ; } else { // couldn't do it return false ; } } private bool AttemptUrlBasedDetection(string url) { // matched provider IBlogProvider blogAccountProvider = null ; // do url-based matching foreach ( IBlogProvider provider in BlogProviderManager.Providers ) { if ( provider.IsProviderForHomepageUrl(url)) { blogAccountProvider = provider ; break; } } if ( blogAccountProvider != null ) { CopySettingsFromProvider(blogAccountProvider) ; return true ; } else { return false ; } } private bool AttemptContentBasedDetection(string homepageContent) { // matched provider IBlogProvider blogAccountProvider = null ; // do url-based matching foreach ( IBlogProvider provider in BlogProviderManager.Providers ) { if ( provider.IsProviderForHomepageContent(homepageContent) ) { blogAccountProvider = provider ; break; } } if ( blogAccountProvider != null ) { CopySettingsFromProvider(blogAccountProvider) ; return true ; } else { return false ; } } private bool AttemptHomepageBasedDetection(string homepageUrl, string homepageContent) { if ( AttemptUrlBasedDetection(homepageUrl) ) { return true ; } else { return AttemptContentBasedDetection(homepageContent) ; } } private RsdServiceDescription GetRsdServiceDescription(IProgressHost progressHost, IHTMLDocument2 weblogDOM) { if ( weblogDOM != null ) { // try to download an RSD description UpdateProgress( progressHost, 50, Res.Get(StringId.ProgressAnalyzingInterface) ) ; return RsdServiceDetector.DetectFromWeblog( _homepageUrl, weblogDOM ) ; } else { return null ; } } private class BlogAccountFromRsdServiceDescription : BlogAccount { public static BlogAccount Create( RsdServiceDescription rsdServiceDescription ) { try { return new BlogAccountFromRsdServiceDescription(rsdServiceDescription); } catch(NoSupportedRsdClientTypeException) { return null ; } } private BlogAccountFromRsdServiceDescription( RsdServiceDescription rsdServiceDescription ) { // look for supported apis from highest fidelity to lowest RsdApi rsdApi = rsdServiceDescription.ScanForApi("WordPress") ; if ( rsdApi == null ) rsdApi = rsdServiceDescription.ScanForApi("MovableType") ; if ( rsdApi == null ) rsdApi = rsdServiceDescription.ScanForApi("MetaWeblog") ; if ( rsdApi != null ) { Init( rsdServiceDescription.EngineName, rsdApi.Name, rsdApi.ApiLink, rsdApi.BlogId ); return ; } else { // couldn't find a supported api type so we fall through to here throw new NoSupportedRsdClientTypeException(); } } } private class NoSupportedRsdClientTypeException : ApplicationException { public NoSupportedRsdClientTypeException() : base( "No supported Rsd client-type") { } } } /// <summary> /// Blog settings detector for SharePoint blogs. /// </summary> public class SharePointBlogDetector : BlogServiceDetectorBase { private IBlogCredentials _blogCredentials; public SharePointBlogDetector(IBlogClientUIContext uiContext, Control hiddenBrowserParentControl, string localBlogId, string homepageUrl, IBlogCredentialsAccessor credentials, IBlogCredentials blogCredentials) : base(uiContext, hiddenBrowserParentControl, localBlogId, homepageUrl, credentials) { _blogCredentials = blogCredentials; } protected override object DetectBlogService(IProgressHost progressHost) { using ( BlogClientUIContextSilentMode uiContextScope = new BlogClientUIContextSilentMode() ) //supress prompting for credentials { try { // copy basic account info IBlogProvider provider = BlogProviderManager.FindProvider("4AA58E69-8C24-40b1-BACE-3BB14237E8F9"); _providerId = provider.Id ; _serviceName = provider.Name; _clientType = provider.ClientType; //calculate the API url based on the homepage Url. // API URL Format: <blogurl>/_layouts/metaweblog.aspx string homepagePath = UrlHelper.SafeToAbsoluteUri(new Uri(_homepageUrl)).Split('?')[0]; if(homepagePath == null) homepagePath = "/"; //trim off any file information included in the URL (ex: /default.aspx) int lastPathPartIndex = homepagePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase); if(lastPathPartIndex != -1) { string lastPathPart = homepagePath.Substring(lastPathPartIndex); if(lastPathPart.IndexOf('.') != -1) { homepagePath = homepagePath.Substring(0, lastPathPartIndex); if(homepagePath == String.Empty) homepagePath = "/"; } } if(homepagePath != "/" && homepagePath.EndsWith("/", StringComparison.OrdinalIgnoreCase)) //trim off trailing slash homepagePath = homepagePath.Substring(0, homepagePath.Length - 1); //Update the homepage url _homepageUrl = homepagePath; _postApiUrl = String.Format(CultureInfo.InvariantCulture, "{0}/_layouts/metaweblog.aspx", homepagePath); if(VerifyCredentialsAndDetectAuthScheme(_postApiUrl, _blogCredentials, _credentials)) { AuthenticationErrorOccurred = false; //detect the user's blog ID. if ( !BlogProviderParameters.UrlContainsParameters(_postApiUrl) ) { // we detected the provider, now see if we can detect the weblog id // (or at lease the list of the user's weblogs) UpdateProgress( progressHost, 80, Res.Get(StringId.ProgressAnalyzingWeblogList) ) ; AttemptUserBlogDetection() ; } } else AuthenticationErrorOccurred = true; } catch( OperationCancelledException ) { // WasCancelled == true } catch ( BlogClientOperationCancelledException ) { Cancel(); // WasCancelled == true } catch ( BlogAccountDetectorException ) { // ErrorOccurred == true } catch ( BlogClientAuthenticationException ) { AuthenticationErrorOccurred = true; // ErrorOccurred == true } catch ( Exception ex ) { // ErrorOccurred == true ReportError(MessageId.WeblogDetectionUnexpectedError, ex.Message) ; } } return this; } /*private string DiscoverPostApiUrl(string baseUrl, string blogPath) { }*/ /// <summary> /// Verifies the user credentials and determines whether SharePoint is configure to use HTTP or MetaWeblog authentication /// </summary> /// <param name="postApiUrl"></param> /// <param name="blogCredentials"></param> /// <param name="credentials"></param> /// <returns></returns> private static bool VerifyCredentialsAndDetectAuthScheme(string postApiUrl, IBlogCredentials blogCredentials, IBlogCredentialsAccessor credentials) { BlogClientAttribute blogClientAttr = (BlogClientAttribute)typeof (SharePointClient).GetCustomAttributes(typeof (BlogClientAttribute), false)[0]; SharePointClient client = (SharePointClient)BlogClientManager.CreateClient(blogClientAttr.TypeName, postApiUrl, credentials); return SharePointClient.VerifyCredentialsAndDetectAuthScheme(blogCredentials, client); } } public abstract class BlogServiceDetectorBase : MultipartAsyncOperation, ITemporaryBlogSettingsDetectionContext { public BlogServiceDetectorBase(IBlogClientUIContext uiContext, Control hiddenBrowserParentControl, string localBlogId, string homepageUrl, IBlogCredentialsAccessor credentials) : base(uiContext) { // save references _uiContext = uiContext ; _localBlogId = localBlogId ; _homepageUrl = homepageUrl ; _credentials = credentials ; // add blog service detection AddProgressOperation( new ProgressOperation(DetectBlogService), 35 ); // add settings downloading (note: this operation will be a no-op // in the case where we don't succesfully detect a weblog) AddProgressOperation( new ProgressOperation(DetectWeblogSettings), new ProgressOperationCompleted(DetectWeblogSettingsCompleted), 30 ) ; // add template downloading (note: this operation will be a no-op in the // case where we don't successfully detect a weblog) _blogEditingTemplateDetector = new BlogEditingTemplateDetector(uiContext, hiddenBrowserParentControl) ; AddProgressOperation( new ProgressOperation(_blogEditingTemplateDetector.DetectTemplate), 35 ) ; } public BlogInfo[] UsersBlogs { get { return _usersBlogs; } } public string ProviderId { get { return _providerId; } } public string ServiceName { get { return _serviceName; } } public string ClientType { get { return _clientType; } } public string PostApiUrl { get { return _postApiUrl; } } public string HostBlogId { get { return _hostBlogId; } } public string BlogName { get { return _blogName; } } public IDictionary OptionOverrides { get { return _optionOverrides; } } public IDictionary HomePageOverrides { get { return _homePageOverrides; } } public IDictionary UserOptionOverrides { get { return null; } } public IBlogProviderButtonDescription[] ButtonDescriptions { get { return _buttonDescriptions; } } public BlogPostCategory[] Categories { get { return _categories; } } public BlogPostKeyword[] Keywords { get { return _keywords; } } public byte[] FavIcon { get { return _favIcon; } } public byte[] Image { get { return _image; } } public byte[] WatermarkImage { get { return _watermarkImage; } } public BlogEditingTemplateFile[] BlogTemplateFiles { get { return _blogEditingTemplateDetector.BlogTemplateFiles; } } public Color? PostBodyBackgroundColor { get { return _blogEditingTemplateDetector.PostBodyBackgroundColor; } } public bool WasCancelled { get { return CancelRequested; } } public bool ErrorOccurred { get { return _errorMessageType != MessageId.None; } } public bool AuthenticationErrorOccurred { get { return _authenticationErrorOccured; } set { _authenticationErrorOccured = value; } } private bool _authenticationErrorOccured = false; public bool TemplateDownloadFailed { get { return _blogEditingTemplateDetector.ExceptionOccurred; } } IBlogCredentialsAccessor IBlogSettingsDetectionContext.Credentials { get { return _credentials; } } string IBlogSettingsDetectionContext.HomepageUrl { get { return _homepageUrl; } } public WriterEditingManifestDownloadInfo ManifestDownloadInfo { get { return _manifestDownloadInfo; } set { _manifestDownloadInfo = value; } } string IBlogSettingsDetectionContext.ClientType { get { return _clientType; } set { _clientType = value; } } byte[] IBlogSettingsDetectionContext.FavIcon { get { return _favIcon; } set { _favIcon = value; } } byte[] IBlogSettingsDetectionContext.Image { get { return _image; } set { _image = value; } } byte[] IBlogSettingsDetectionContext.WatermarkImage { get { return _watermarkImage; } set { _watermarkImage = value; } } BlogPostCategory[] IBlogSettingsDetectionContext.Categories { get { return _categories; } set { _categories = value; } } BlogPostKeyword[] IBlogSettingsDetectionContext.Keywords { get { return _keywords; } set { _keywords = value; } } IDictionary IBlogSettingsDetectionContext.OptionOverrides { get { return _optionOverrides; } set { _optionOverrides = value; } } IDictionary IBlogSettingsDetectionContext.HomePageOverrides { get { return _homePageOverrides; } set { _homePageOverrides = value; } } IBlogProviderButtonDescription[] IBlogSettingsDetectionContext.ButtonDescriptions { get { return _buttonDescriptions; } set { _buttonDescriptions = value; } } public BlogInfo[] AvailableImageEndpoints { get { return availableImageEndpoints; } set { availableImageEndpoints = value; } } public void ShowLastError(IWin32Window owner) { if ( ErrorOccurred ) { DisplayMessage.Show( _errorMessageType, owner, _errorMessageParams ) ; } else { Trace.Fail("Called ShowLastError when no error occurred"); } } public static byte[] SafeDownloadFavIcon(string homepageUrl) { try { string favIconUrl = UrlHelper.UrlCombine(homepageUrl, "favicon.ico") ; using ( Stream favIconStream = HttpRequestHelper.SafeDownloadFile(favIconUrl) ) { using ( MemoryStream memoryStream = new MemoryStream() ) { StreamHelper.Transfer(favIconStream, memoryStream) ; memoryStream.Seek(0, SeekOrigin.Begin) ; return memoryStream.ToArray() ; } } } catch { return null ; } } protected abstract object DetectBlogService(IProgressHost progressHost); protected void AttemptUserBlogDetection() { BlogAccountDetector blogAccountDetector = new BlogAccountDetector( _clientType, _postApiUrl, _credentials) ; if ( blogAccountDetector.ValidateService() ) { BlogInfo blogInfo = blogAccountDetector.DetectAccount(_homepageUrl, _hostBlogId); if ( blogInfo != null ) { // save the detected info // TODO: Commenting out next line for Spaces demo tomorrow. // need to decide whether to keep it commented out going forward. // _homepageUrl = blogInfo.HomepageUrl; _hostBlogId = blogInfo.Id ; _blogName = blogInfo.Name ; } // always save the list of user's blogs _usersBlogs = blogAccountDetector.UsersBlogs ; } else { AuthenticationErrorOccurred = blogAccountDetector.Exception is BlogClientAuthenticationException; ReportErrorAndFail( blogAccountDetector.ErrorMessageType, blogAccountDetector.ErrorMessageParams ) ; } } protected IHTMLDocument2 GetWeblogHomepageDOM(IProgressHost progressHost) { // try download the weblog home page UpdateProgress( progressHost, 25, Res.Get(StringId.ProgressAnalyzingHomepage) ) ; string responseUri; IHTMLDocument2 weblogDOM = HTMLDocumentHelper.SafeGetHTMLDocumentFromUrl( _homepageUrl, out responseUri ); if (responseUri != null && responseUri != _homepageUrl) { _homepageUrl = responseUri; } if ( weblogDOM != null ) { // default the blog name to the title of the document if (weblogDOM.title != null) { _blogName = weblogDOM.title; // drop anything to the right of a "|", as it usually is a site name int index = _blogName.IndexOf("|", StringComparison.OrdinalIgnoreCase); if (index > 0) { string newname = _blogName.Substring(0, index).Trim(); if (newname != String.Empty) _blogName = newname; } } } return weblogDOM ; } protected void CopySettingsFromProvider(IBlogProvider blogAccountProvider) { _providerId = blogAccountProvider.Id ; _serviceName = blogAccountProvider.Name; _clientType = blogAccountProvider.ClientType; _postApiUrl = ProcessPostUrlMacros(blogAccountProvider.PostApiUrl); } private string ProcessPostUrlMacros(string postApiUrl) { return postApiUrl.Replace("<username>", _credentials.Username) ; } private object DetectWeblogSettings(IProgressHost progressHost) { using ( BlogClientUIContextSilentMode uiContextScope = new BlogClientUIContextSilentMode() ) //supress prompting for credentials { // no-op if we don't have a blog-id to work with if ( HostBlogId == String.Empty ) return this ; try { // detect settings BlogSettingsDetector blogSettingsDetector = new BlogSettingsDetector(this); blogSettingsDetector.DetectSettings(progressHost); } catch(OperationCancelledException) { // WasCancelled == true } catch (BlogClientOperationCancelledException) { Cancel() ; // WasCancelled == true } catch(Exception ex) { Trace.Fail("Unexpected error occurred while detecting weblog settings: " + ex.ToString()); } return this ; } } private void DetectWeblogSettingsCompleted(object result) { // no-op if we don't have a blog detected if ( HostBlogId == String.Empty ) return ; // get the editing template directory string blogTemplateDir = BlogEditingTemplate.GetBlogTemplateDir(_localBlogId); // set context for template detector BlogAccount blogAccount = new BlogAccount(ServiceName, ClientType, PostApiUrl, HostBlogId); _blogEditingTemplateDetector.SetContext(blogAccount, _credentials, _homepageUrl, blogTemplateDir, _manifestDownloadInfo, false, _providerId, _optionOverrides, null, _homePageOverrides); } protected void UpdateProgress( IProgressHost progressHost, int percent, string message ) { if ( CancelRequested ) throw new OperationCancelledException() ; progressHost.UpdateProgress(percent, 100, message ) ; } protected void ReportError( MessageId errorMessageType, params object[] errorMessageParams) { _errorMessageType = errorMessageType ; _errorMessageParams = errorMessageParams ; } protected void ReportErrorAndFail( MessageId errorMessageType, params object[] errorMessageParams ) { ReportError( errorMessageType, errorMessageParams ) ; throw new BlogAccountDetectorException() ; } protected class BlogAccountDetectorException : ApplicationException { public BlogAccountDetectorException() : base("Blog account detector did not succeed") { } } /// <summary> /// Blog account we are scanning /// </summary> private string _localBlogId ; protected string _homepageUrl ; protected WriterEditingManifestDownloadInfo _manifestDownloadInfo = null ; protected IBlogCredentialsAccessor _credentials ; // BlogTemplateDetector private BlogEditingTemplateDetector _blogEditingTemplateDetector ; /// <summary> /// Results of scanning /// </summary> protected string _providerId = String.Empty ; protected string _serviceName = String.Empty; protected string _clientType = String.Empty; protected string _postApiUrl = String.Empty ; protected string _hostBlogId = String.Empty ; protected string _blogName = String.Empty; protected BlogInfo[] _usersBlogs = new BlogInfo[] {}; // if we are unable to detect these values then leave them null // as an indicator that their values are "unknown" vs. "empty" // callers can then choose to not overwrite any existing settings // in this case protected IDictionary _homePageOverrides = null; protected IDictionary _optionOverrides = null ; private BlogPostCategory[] _categories = null; private BlogPostKeyword[] _keywords = null; private byte[] _favIcon = null ; private byte[] _image = null ; private byte[] _watermarkImage = null ; private IBlogProviderButtonDescription[] _buttonDescriptions = null ; // error info private MessageId _errorMessageType ; private object[] _errorMessageParams ; protected IBlogClientUIContext _uiContext ; private BlogInfo[] availableImageEndpoints; } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class HorizontalScrollView : android.widget.FrameLayout { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected HorizontalScrollView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override bool onTouchEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.HorizontalScrollView._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public override bool dispatchKeyEvent(android.view.KeyEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z", ref global::android.widget.HorizontalScrollView._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public override void addView(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "addView", "(Landroid/view/View;)V", ref global::android.widget.HorizontalScrollView._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public override void addView(android.view.View arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "addView", "(Landroid/view/View;I)V", ref global::android.widget.HorizontalScrollView._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; public override void addView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", ref global::android.widget.HorizontalScrollView._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m5; public override void addView(android.view.View arg0, int arg1, android.view.ViewGroup.LayoutParams arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "addView", "(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V", ref global::android.widget.HorizontalScrollView._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m6; protected override void onSizeChanged(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "onSizeChanged", "(IIII)V", ref global::android.widget.HorizontalScrollView._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m7; public override void scrollTo(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "scrollTo", "(II)V", ref global::android.widget.HorizontalScrollView._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m8; public override void computeScroll() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "computeScroll", "()V", ref global::android.widget.HorizontalScrollView._m8); } protected new float LeftFadingEdgeStrength { get { return getLeftFadingEdgeStrength(); } } private static global::MonoJavaBridge.MethodId _m9; protected override float getLeftFadingEdgeStrength() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.widget.HorizontalScrollView.staticClass, "getLeftFadingEdgeStrength", "()F", ref global::android.widget.HorizontalScrollView._m9); } protected new float RightFadingEdgeStrength { get { return getRightFadingEdgeStrength(); } } private static global::MonoJavaBridge.MethodId _m10; protected override float getRightFadingEdgeStrength() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.widget.HorizontalScrollView.staticClass, "getRightFadingEdgeStrength", "()F", ref global::android.widget.HorizontalScrollView._m10); } private static global::MonoJavaBridge.MethodId _m11; protected override int computeHorizontalScrollRange() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.HorizontalScrollView.staticClass, "computeHorizontalScrollRange", "()I", ref global::android.widget.HorizontalScrollView._m11); } private static global::MonoJavaBridge.MethodId _m12; protected override int computeHorizontalScrollOffset() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.HorizontalScrollView.staticClass, "computeHorizontalScrollOffset", "()I", ref global::android.widget.HorizontalScrollView._m12); } private static global::MonoJavaBridge.MethodId _m13; protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "onLayout", "(ZIIII)V", ref global::android.widget.HorizontalScrollView._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m14; public override void requestLayout() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "requestLayout", "()V", ref global::android.widget.HorizontalScrollView._m14); } private static global::MonoJavaBridge.MethodId _m15; protected override void onMeasure(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "onMeasure", "(II)V", ref global::android.widget.HorizontalScrollView._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m16; public override void requestChildFocus(android.view.View arg0, android.view.View arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "requestChildFocus", "(Landroid/view/View;Landroid/view/View;)V", ref global::android.widget.HorizontalScrollView._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m17; public override bool requestChildRectangleOnScreen(android.view.View arg0, android.graphics.Rect arg1, bool arg2) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "requestChildRectangleOnScreen", "(Landroid/view/View;Landroid/graphics/Rect;Z)Z", ref global::android.widget.HorizontalScrollView._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m18; public override bool onInterceptTouchEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "onInterceptTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.HorizontalScrollView._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m19; protected override bool onRequestFocusInDescendants(int arg0, android.graphics.Rect arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "onRequestFocusInDescendants", "(ILandroid/graphics/Rect;)Z", ref global::android.widget.HorizontalScrollView._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m20; protected override void measureChild(android.view.View arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "measureChild", "(Landroid/view/View;II)V", ref global::android.widget.HorizontalScrollView._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m21; protected override void measureChildWithMargins(android.view.View arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "measureChildWithMargins", "(Landroid/view/View;IIII)V", ref global::android.widget.HorizontalScrollView._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } public new int MaxScrollAmount { get { return getMaxScrollAmount(); } } private static global::MonoJavaBridge.MethodId _m22; public virtual int getMaxScrollAmount() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.HorizontalScrollView.staticClass, "getMaxScrollAmount", "()I", ref global::android.widget.HorizontalScrollView._m22); } private static global::MonoJavaBridge.MethodId _m23; public virtual void smoothScrollBy(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "smoothScrollBy", "(II)V", ref global::android.widget.HorizontalScrollView._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m24; public virtual void fling(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "fling", "(I)V", ref global::android.widget.HorizontalScrollView._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m25; public virtual bool isFillViewport() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "isFillViewport", "()Z", ref global::android.widget.HorizontalScrollView._m25); } public new bool FillViewport { set { setFillViewport(value); } } private static global::MonoJavaBridge.MethodId _m26; public virtual void setFillViewport(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "setFillViewport", "(Z)V", ref global::android.widget.HorizontalScrollView._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m27; public virtual bool isSmoothScrollingEnabled() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "isSmoothScrollingEnabled", "()Z", ref global::android.widget.HorizontalScrollView._m27); } public new bool SmoothScrollingEnabled { set { setSmoothScrollingEnabled(value); } } private static global::MonoJavaBridge.MethodId _m28; public virtual void setSmoothScrollingEnabled(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "setSmoothScrollingEnabled", "(Z)V", ref global::android.widget.HorizontalScrollView._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m29; public virtual bool executeKeyEvent(android.view.KeyEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "executeKeyEvent", "(Landroid/view/KeyEvent;)Z", ref global::android.widget.HorizontalScrollView._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m30; public virtual bool pageScroll(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "pageScroll", "(I)Z", ref global::android.widget.HorizontalScrollView._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public virtual bool fullScroll(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "fullScroll", "(I)Z", ref global::android.widget.HorizontalScrollView._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m32; public virtual bool arrowScroll(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.HorizontalScrollView.staticClass, "arrowScroll", "(I)Z", ref global::android.widget.HorizontalScrollView._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m33; public virtual void smoothScrollTo(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.HorizontalScrollView.staticClass, "smoothScrollTo", "(II)V", ref global::android.widget.HorizontalScrollView._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m34; protected virtual int computeScrollDeltaToGetChildRectOnScreen(android.graphics.Rect arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.HorizontalScrollView.staticClass, "computeScrollDeltaToGetChildRectOnScreen", "(Landroid/graphics/Rect;)I", ref global::android.widget.HorizontalScrollView._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m35; public HorizontalScrollView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.HorizontalScrollView._m35.native == global::System.IntPtr.Zero) global::android.widget.HorizontalScrollView._m35 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m36; public HorizontalScrollView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.HorizontalScrollView._m36.native == global::System.IntPtr.Zero) global::android.widget.HorizontalScrollView._m36 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m37; public HorizontalScrollView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.HorizontalScrollView._m37.native == global::System.IntPtr.Zero) global::android.widget.HorizontalScrollView._m37 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "<init>", "(Landroid/content/Context;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static HorizontalScrollView() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.HorizontalScrollView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/HorizontalScrollView")); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="ExtensionFeedItemServiceClient"/> instances.</summary> public sealed partial class ExtensionFeedItemServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ExtensionFeedItemServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ExtensionFeedItemServiceSettings"/>.</returns> public static ExtensionFeedItemServiceSettings GetDefault() => new ExtensionFeedItemServiceSettings(); /// <summary> /// Constructs a new <see cref="ExtensionFeedItemServiceSettings"/> object with default settings. /// </summary> public ExtensionFeedItemServiceSettings() { } private ExtensionFeedItemServiceSettings(ExtensionFeedItemServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetExtensionFeedItemSettings = existing.GetExtensionFeedItemSettings; MutateExtensionFeedItemsSettings = existing.MutateExtensionFeedItemsSettings; OnCopy(existing); } partial void OnCopy(ExtensionFeedItemServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ExtensionFeedItemServiceClient.GetExtensionFeedItem</c> and /// <c>ExtensionFeedItemServiceClient.GetExtensionFeedItemAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetExtensionFeedItemSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ExtensionFeedItemServiceClient.MutateExtensionFeedItems</c> and /// <c>ExtensionFeedItemServiceClient.MutateExtensionFeedItemsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateExtensionFeedItemsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ExtensionFeedItemServiceSettings"/> object.</returns> public ExtensionFeedItemServiceSettings Clone() => new ExtensionFeedItemServiceSettings(this); } /// <summary> /// Builder class for <see cref="ExtensionFeedItemServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class ExtensionFeedItemServiceClientBuilder : gaxgrpc::ClientBuilderBase<ExtensionFeedItemServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ExtensionFeedItemServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ExtensionFeedItemServiceClientBuilder() { UseJwtAccessWithScopes = ExtensionFeedItemServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ExtensionFeedItemServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ExtensionFeedItemServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ExtensionFeedItemServiceClient Build() { ExtensionFeedItemServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ExtensionFeedItemServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ExtensionFeedItemServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ExtensionFeedItemServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ExtensionFeedItemServiceClient.Create(callInvoker, Settings); } private async stt::Task<ExtensionFeedItemServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ExtensionFeedItemServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ExtensionFeedItemServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ExtensionFeedItemServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ExtensionFeedItemServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ExtensionFeedItemService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage extension feed items. /// </remarks> public abstract partial class ExtensionFeedItemServiceClient { /// <summary> /// The default endpoint for the ExtensionFeedItemService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ExtensionFeedItemService scopes.</summary> /// <remarks> /// The default ExtensionFeedItemService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ExtensionFeedItemServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ExtensionFeedItemServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ExtensionFeedItemServiceClient"/>.</returns> public static stt::Task<ExtensionFeedItemServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ExtensionFeedItemServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ExtensionFeedItemServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="ExtensionFeedItemServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ExtensionFeedItemServiceClient"/>.</returns> public static ExtensionFeedItemServiceClient Create() => new ExtensionFeedItemServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ExtensionFeedItemServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ExtensionFeedItemServiceSettings"/>.</param> /// <returns>The created <see cref="ExtensionFeedItemServiceClient"/>.</returns> internal static ExtensionFeedItemServiceClient Create(grpccore::CallInvoker callInvoker, ExtensionFeedItemServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ExtensionFeedItemService.ExtensionFeedItemServiceClient grpcClient = new ExtensionFeedItemService.ExtensionFeedItemServiceClient(callInvoker); return new ExtensionFeedItemServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ExtensionFeedItemService client</summary> public virtual ExtensionFeedItemService.ExtensionFeedItemServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExtensionFeedItem GetExtensionFeedItem(GetExtensionFeedItemRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExtensionFeedItem> GetExtensionFeedItemAsync(GetExtensionFeedItemRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExtensionFeedItem> GetExtensionFeedItemAsync(GetExtensionFeedItemRequest request, st::CancellationToken cancellationToken) => GetExtensionFeedItemAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the extension feed item to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExtensionFeedItem GetExtensionFeedItem(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetExtensionFeedItem(new GetExtensionFeedItemRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the extension feed item to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExtensionFeedItem> GetExtensionFeedItemAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetExtensionFeedItemAsync(new GetExtensionFeedItemRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the extension feed item to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExtensionFeedItem> GetExtensionFeedItemAsync(string resourceName, st::CancellationToken cancellationToken) => GetExtensionFeedItemAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the extension feed item to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExtensionFeedItem GetExtensionFeedItem(gagvr::ExtensionFeedItemName resourceName, gaxgrpc::CallSettings callSettings = null) => GetExtensionFeedItem(new GetExtensionFeedItemRequest { ResourceNameAsExtensionFeedItemName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the extension feed item to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExtensionFeedItem> GetExtensionFeedItemAsync(gagvr::ExtensionFeedItemName resourceName, gaxgrpc::CallSettings callSettings = null) => GetExtensionFeedItemAsync(new GetExtensionFeedItemRequest { ResourceNameAsExtensionFeedItemName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the extension feed item to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExtensionFeedItem> GetExtensionFeedItemAsync(gagvr::ExtensionFeedItemName resourceName, st::CancellationToken cancellationToken) => GetExtensionFeedItemAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes extension feed items. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CountryCodeError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionFeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [ImageError]() /// [InternalError]() /// [LanguageCodeError]() /// [MutateError]() /// [NewResourceCreationError]() /// [OperationAccessDeniedError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateExtensionFeedItemsResponse MutateExtensionFeedItems(MutateExtensionFeedItemsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes extension feed items. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CountryCodeError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionFeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [ImageError]() /// [InternalError]() /// [LanguageCodeError]() /// [MutateError]() /// [NewResourceCreationError]() /// [OperationAccessDeniedError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateExtensionFeedItemsResponse> MutateExtensionFeedItemsAsync(MutateExtensionFeedItemsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes extension feed items. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CountryCodeError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionFeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [ImageError]() /// [InternalError]() /// [LanguageCodeError]() /// [MutateError]() /// [NewResourceCreationError]() /// [OperationAccessDeniedError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateExtensionFeedItemsResponse> MutateExtensionFeedItemsAsync(MutateExtensionFeedItemsRequest request, st::CancellationToken cancellationToken) => MutateExtensionFeedItemsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes extension feed items. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CountryCodeError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionFeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [ImageError]() /// [InternalError]() /// [LanguageCodeError]() /// [MutateError]() /// [NewResourceCreationError]() /// [OperationAccessDeniedError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose extension feed items are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual extension feed items. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateExtensionFeedItemsResponse MutateExtensionFeedItems(string customerId, scg::IEnumerable<ExtensionFeedItemOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateExtensionFeedItems(new MutateExtensionFeedItemsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes extension feed items. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CountryCodeError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionFeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [ImageError]() /// [InternalError]() /// [LanguageCodeError]() /// [MutateError]() /// [NewResourceCreationError]() /// [OperationAccessDeniedError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose extension feed items are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual extension feed items. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateExtensionFeedItemsResponse> MutateExtensionFeedItemsAsync(string customerId, scg::IEnumerable<ExtensionFeedItemOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateExtensionFeedItemsAsync(new MutateExtensionFeedItemsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes extension feed items. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CountryCodeError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionFeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [ImageError]() /// [InternalError]() /// [LanguageCodeError]() /// [MutateError]() /// [NewResourceCreationError]() /// [OperationAccessDeniedError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose extension feed items are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual extension feed items. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateExtensionFeedItemsResponse> MutateExtensionFeedItemsAsync(string customerId, scg::IEnumerable<ExtensionFeedItemOperation> operations, st::CancellationToken cancellationToken) => MutateExtensionFeedItemsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ExtensionFeedItemService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage extension feed items. /// </remarks> public sealed partial class ExtensionFeedItemServiceClientImpl : ExtensionFeedItemServiceClient { private readonly gaxgrpc::ApiCall<GetExtensionFeedItemRequest, gagvr::ExtensionFeedItem> _callGetExtensionFeedItem; private readonly gaxgrpc::ApiCall<MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse> _callMutateExtensionFeedItems; /// <summary> /// Constructs a client wrapper for the ExtensionFeedItemService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ExtensionFeedItemServiceSettings"/> used within this client. /// </param> public ExtensionFeedItemServiceClientImpl(ExtensionFeedItemService.ExtensionFeedItemServiceClient grpcClient, ExtensionFeedItemServiceSettings settings) { GrpcClient = grpcClient; ExtensionFeedItemServiceSettings effectiveSettings = settings ?? ExtensionFeedItemServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetExtensionFeedItem = clientHelper.BuildApiCall<GetExtensionFeedItemRequest, gagvr::ExtensionFeedItem>(grpcClient.GetExtensionFeedItemAsync, grpcClient.GetExtensionFeedItem, effectiveSettings.GetExtensionFeedItemSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetExtensionFeedItem); Modify_GetExtensionFeedItemApiCall(ref _callGetExtensionFeedItem); _callMutateExtensionFeedItems = clientHelper.BuildApiCall<MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse>(grpcClient.MutateExtensionFeedItemsAsync, grpcClient.MutateExtensionFeedItems, effectiveSettings.MutateExtensionFeedItemsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateExtensionFeedItems); Modify_MutateExtensionFeedItemsApiCall(ref _callMutateExtensionFeedItems); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetExtensionFeedItemApiCall(ref gaxgrpc::ApiCall<GetExtensionFeedItemRequest, gagvr::ExtensionFeedItem> call); partial void Modify_MutateExtensionFeedItemsApiCall(ref gaxgrpc::ApiCall<MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse> call); partial void OnConstruction(ExtensionFeedItemService.ExtensionFeedItemServiceClient grpcClient, ExtensionFeedItemServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ExtensionFeedItemService client</summary> public override ExtensionFeedItemService.ExtensionFeedItemServiceClient GrpcClient { get; } partial void Modify_GetExtensionFeedItemRequest(ref GetExtensionFeedItemRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateExtensionFeedItemsRequest(ref MutateExtensionFeedItemsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::ExtensionFeedItem GetExtensionFeedItem(GetExtensionFeedItemRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetExtensionFeedItemRequest(ref request, ref callSettings); return _callGetExtensionFeedItem.Sync(request, callSettings); } /// <summary> /// Returns the requested extension feed item in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::ExtensionFeedItem> GetExtensionFeedItemAsync(GetExtensionFeedItemRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetExtensionFeedItemRequest(ref request, ref callSettings); return _callGetExtensionFeedItem.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes extension feed items. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CountryCodeError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionFeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [ImageError]() /// [InternalError]() /// [LanguageCodeError]() /// [MutateError]() /// [NewResourceCreationError]() /// [OperationAccessDeniedError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateExtensionFeedItemsResponse MutateExtensionFeedItems(MutateExtensionFeedItemsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateExtensionFeedItemsRequest(ref request, ref callSettings); return _callMutateExtensionFeedItems.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes extension feed items. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CountryCodeError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionFeedItemError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [ImageError]() /// [InternalError]() /// [LanguageCodeError]() /// [MutateError]() /// [NewResourceCreationError]() /// [OperationAccessDeniedError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateExtensionFeedItemsResponse> MutateExtensionFeedItemsAsync(MutateExtensionFeedItemsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateExtensionFeedItemsRequest(ref request, ref callSettings); return _callMutateExtensionFeedItems.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using Baseline; using Baseline.ImTools; using LamarCodeGeneration; using Marten.Events; using Marten.Exceptions; using Marten.Schema; #nullable enable namespace Marten.Storage { public class StorageFeatures { private readonly StoreOptions _options; private readonly Ref<ImHashMap<Type, DocumentMapping>> _documentMappings = Ref.Of(ImHashMap<Type, DocumentMapping>.Empty); private readonly Ref<ImHashMap<Type, IDocumentMapping>> _mappings = Ref.Of(ImHashMap<Type, IDocumentMapping>.Empty); private readonly Dictionary<Type, IFeatureSchema> _features = new Dictionary<Type, IFeatureSchema>(); internal StorageFeatures(StoreOptions options) { _options = options; SystemFunctions = new SystemFunctions(options); } private readonly IDictionary<Type, IDocumentMappingBuilder> _builders = new Dictionary<Type, IDocumentMappingBuilder>(); private readonly ThreadLocal<IList<Type>> _buildingList = new ThreadLocal<IList<Type>>(); internal DocumentMapping Build(Type type, StoreOptions options) { if (_buildingList.IsValueCreated) { if (_buildingList.Value!.Contains(type)) { throw new InvalidOperationException($"Cyclic dependency between documents detected. The types are: {_buildingList.Value.Select(x => x.FullNameInCode()).Join(", ")}"); } } else { _buildingList.Value = new List<Type>(); } _buildingList.Value.Add(type); if (_builders.TryGetValue(type, out var builder)) { var mapping = builder.Build(options); _buildingList.Value.Remove(type); return mapping; } _buildingList.Value.Remove(type); return new DocumentMapping(type, options); } internal void RegisterDocumentType(Type documentType) { if (!_builders.ContainsKey(documentType)) { _builders[documentType] = typeof(DocumentMappingBuilder<>).CloseAndBuildAs<IDocumentMappingBuilder>(documentType); } } internal DocumentMappingBuilder<T> BuilderFor<T>() { if (_builders.TryGetValue(typeof(T), out var builder)) { return (DocumentMappingBuilder<T>) builder; } builder = new DocumentMappingBuilder<T>(); _builders[typeof(T)] = builder; return (DocumentMappingBuilder<T>) builder; } internal void BuildAllMappings() { foreach (var pair in _builders.ToArray()) { // Just forcing them all to be built FindMapping(pair.Key); } // This needs to be done second so that it can pick up any subclass // relationships foreach (var documentType in _options.Projections.AllPublishedTypes()) { FindMapping(documentType); } } /// <summary> /// Register custom storage features /// </summary> /// <param name="feature"></param> public void Add(IFeatureSchema feature) { if (!_features.ContainsKey(feature.StorageType)) { _features[feature.StorageType] = feature; } } /// <summary> /// Register custom storage features by type. Type must have either a no-arg, public /// constructor or a constructor that takes in a single StoreOptions parameter /// </summary> /// <typeparam name="T"></typeparam> public void Add<T>() where T : IFeatureSchema { var ctor = typeof(T).GetTypeInfo().GetConstructor(new Type[] { typeof(StoreOptions) }); IFeatureSchema feature; if (ctor != null) { feature = Activator.CreateInstance(typeof(T), _options)! .As<IFeatureSchema>(); } else { feature = Activator.CreateInstance(typeof(T))!.As<IFeatureSchema>(); } Add(feature); } internal SystemFunctions SystemFunctions { get; } internal IEnumerable<DocumentMapping> AllDocumentMappings => _documentMappings.Value.Enumerate().Select(x => x.Value); internal DocumentMapping MappingFor(Type documentType) { if (!_documentMappings.Value.TryFind(documentType, out var value)) { var buildingList = new List<Type>(); value = Build(documentType, _options); _documentMappings.Swap(d => d.AddOrUpdate(documentType, value)); } return value; } internal IDocumentMapping FindMapping(Type documentType) { if (documentType == null) throw new ArgumentNullException(nameof(documentType)); if (!_mappings.Value.TryFind(documentType, out var value)) { var subclass = AllDocumentMappings.SelectMany(x => x.SubClasses) .FirstOrDefault(x => x.DocumentType == documentType) as IDocumentMapping; value = subclass ?? MappingFor(documentType); _mappings.Swap(d => d.AddOrUpdate(documentType, value)); assertNoDuplicateDocumentAliases(); } return value; } internal void AddMapping(IDocumentMapping mapping) { _mappings.Swap(d => d.AddOrUpdate(mapping.DocumentType, mapping)); } private void assertNoDuplicateDocumentAliases() { var duplicates = AllDocumentMappings.Where(x => !x.StructuralTyped) .GroupBy(x => x.Alias) .Where(x => x.Count() > 1) .ToArray(); if (duplicates.Any()) { var message = duplicates.Select(group => { return $"Document types {group.Select(x => x.DocumentType.FullName!).Join(", ")} all have the same document alias '{group.Key}'. You must explicitly make document type aliases to disambiguate the database schema objects"; }).Join("\n"); throw new AmbiguousDocumentTypeAliasesException(message); } } /// <summary> /// Retrieve an IFeatureSchema for the designated type /// </summary> /// <param name="featureType"></param> /// <returns></returns> public IFeatureSchema FindFeature(Type featureType) { if (_features.TryGetValue(featureType, out var schema)) { return schema; } if (_options.EventGraph.AllEvents().Any(x => x.DocumentType == featureType)) { return _options.EventGraph; } return MappingFor(featureType).Schema; } internal void PostProcessConfiguration() { SystemFunctions.AddSystemFunction(_options, "mt_immutable_timestamp", "text"); SystemFunctions.AddSystemFunction(_options, "mt_immutable_timestamptz", "text"); Add(SystemFunctions); Add(_options.EventGraph); _features[typeof(StreamState)] = _options.EventGraph; _features[typeof(StreamAction)] = _options.EventGraph; _features[typeof(IEvent)] = _options.EventGraph; _mappings.Swap(d => d.AddOrUpdate(typeof(IEvent), new EventQueryMapping(_options))); foreach (var mapping in _documentMappings.Value.Enumerate().Select(x => x.Value)) { foreach (var subClass in mapping.SubClasses) { _mappings.Swap(d => d.AddOrUpdate(subClass.DocumentType, subClass)); _features[subClass.DocumentType] = subClass.Parent.Schema; } } } /// <summary> /// All referenced schema names by this DocumentStore /// </summary> /// <returns></returns> public string[] AllSchemaNames() { var schemas = AllDocumentMappings .Select(x => x.DatabaseSchemaName) .Distinct() .ToList(); schemas.Fill(_options.DatabaseSchemaName); schemas.Fill(_options.Events.DatabaseSchemaName); return schemas.Select(x => x.ToLowerInvariant()).ToArray(); } internal IEnumerable<IFeatureSchema> AllActiveFeatures(ITenant tenant) { yield return SystemFunctions; var mappings = _documentMappings.Value .Enumerate().Select(x => x.Value) .OrderBy(x => x.DocumentType.Name) .TopologicalSort(m => m.ReferencedTypes() .Select(MappingFor)); foreach (var mapping in mappings) { yield return mapping.Schema; } if (SequenceIsRequired()) { yield return tenant.Sequences; } if (_options.Events.As<EventGraph>().IsActive(_options)) { yield return _options.EventGraph; } var custom = _features.Values .Where(x => x.GetType().Assembly != GetType().Assembly).ToArray(); foreach (var featureSchema in custom) { yield return featureSchema; } } internal bool SequenceIsRequired() { return _documentMappings.Value.Enumerate().Select(x => x.Value).Any(x => x.IdStrategy.RequiresSequences); } private ImHashMap<Type, IEnumerable<Type>> _typeDependencies = ImHashMap<Type, IEnumerable<Type>>.Empty; internal IEnumerable<Type> GetTypeDependencies(Type type) { if (_typeDependencies.TryFind(type, out var deps)) { return deps; } deps = determineTypeDependencies(type); _typeDependencies = _typeDependencies.AddOrUpdate(type, deps); return deps; } private IEnumerable<Type> determineTypeDependencies(Type type) { var mapping = FindMapping(type); var documentMapping = mapping as DocumentMapping ?? (mapping as SubClassMapping)?.Parent; if (documentMapping == null) return Enumerable.Empty<Type>(); return documentMapping.ReferencedTypes() .SelectMany(keyDefinition => { var results = new List<Type>(); // If the reference type has sub-classes, also need to insert/update them first too if (FindMapping(keyDefinition) is DocumentMapping referenceMappingType && referenceMappingType.SubClasses.Any()) { results.AddRange(referenceMappingType.SubClasses.Select(s => s.DocumentType)); } results.Add(keyDefinition); return results; }); } /// <summary> /// Used to support MartenRegistry.Include() /// </summary> /// <param name="includedStorage"></param> internal void IncludeDocumentMappingBuilders(StorageFeatures includedStorage) { foreach (var builder in includedStorage._builders.Values) { if (_builders.TryGetValue(builder.DocumentType, out var existing)) { existing.Include(builder); } else { _builders.Add(builder.DocumentType, builder); } } } } }
// 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. namespace Microsoft.Hadoop.Client.WebHCatRest { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Management.HDInsight; using Microsoft.WindowsAzure.Management.HDInsight.Framework; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.WebRequest; using Microsoft.WindowsAzure.Management.HDInsight.Framework.ServiceLocation; /// <summary> /// Represents a remote rest request to submit a Hadoop jobDetails. /// </summary> internal class HadoopRemoteJobSubmissionRestClient : IHadoopJobSubmissionRestClient { private readonly BasicAuthCredential credentials; private readonly IAbstractionContext context; private readonly bool ignoreSslErrors; private readonly string userAgentString; /// <summary> /// Initializes a new instance of the HadoopRemoteJobSubmissionRestClient class. /// </summary> /// <param name="credentials"> /// The credentials to use to connect to the server. /// </param> /// <param name="context"> /// A CancellationToken that can be used to cancel events. /// </param> /// <param name="ignoreSslErrors"> /// Specifies that server side SSL error should be ignored. /// </param> /// <param name="userAgentString">UserAgent string to pass to all calls.</param> public HadoopRemoteJobSubmissionRestClient(BasicAuthCredential credentials, IAbstractionContext context, bool ignoreSslErrors, string userAgentString) { this.credentials = credentials; this.context = context; this.ignoreSslErrors = ignoreSslErrors; this.userAgentString = userAgentString ?? string.Empty; } /// <inheritdoc/> public string GetUserAgentString() { return this.userAgentString; } /// <inheritdoc /> public async Task<IHttpResponseMessageAbstraction> ListJobs() { var relative = new Uri( HadoopRemoteRestConstants.Jobs + "?" + HadoopRemoteRestConstants.UserName + "=" + this.credentials.UserName.EscapeDataString() + "&" + HadoopRemoteRestConstants.ShowAllFields, UriKind.Relative); return await this.MakeAsyncGetRequest(relative); } /// <inheritdoc /> public async Task<IHttpResponseMessageAbstraction> GetJob(string jobId) { var relative = new Uri( HadoopRemoteRestConstants.Jobs + "/" + jobId.EscapeDataString() + "?" + HadoopRemoteRestConstants.UserName + "=" + this.credentials.UserName.EscapeDataString(), UriKind.Relative); return await this.MakeAsyncGetRequest(relative); } /// <inheritdoc /> public async Task<IHttpResponseMessageAbstraction> SubmitMapReduceJob(string payload) { var relative = new Uri(HadoopRemoteRestConstants.MapReduceJar + "?" + HadoopRemoteRestConstants.UserName + "=" + this.credentials.UserName.EscapeDataString(), UriKind.Relative); return await this.MakeAsyncJobSubmissionRequest(relative, payload); } /// <inheritdoc /> public async Task<IHttpResponseMessageAbstraction> SubmitHiveJob(string payload) { var relative = new Uri(HadoopRemoteRestConstants.Hive + "?" + HadoopRemoteRestConstants.UserName + "=" + this.credentials.UserName.EscapeDataString(), UriKind.Relative); return await this.MakeAsyncJobSubmissionRequest(relative, payload); } /// <inheritdoc /> public async Task<IHttpResponseMessageAbstraction> SubmitStreamingMapReduceJob(string payload) { var relative = new Uri(HadoopRemoteRestConstants.MapReduceStreaming + "?" + HadoopRemoteRestConstants.UserName + "=" + this.credentials.UserName.EscapeDataString(), UriKind.Relative); return await this.MakeAsyncJobSubmissionRequest(relative, payload); } /// <inheritdoc /> public async Task<IHttpResponseMessageAbstraction> SubmitPigJob(string payload) { var relative = new Uri(HadoopRemoteRestConstants.Pig + "?" + HadoopRemoteRestConstants.UserName + "=" + this.credentials.UserName.EscapeDataString(), UriKind.Relative); return await this.MakeAsyncJobSubmissionRequest(relative, payload); } /// <inheritdoc /> public async Task<IHttpResponseMessageAbstraction> SubmitSqoopJob(string payload) { var relative = new Uri(HadoopRemoteRestConstants.Sqoop + "?" + HadoopRemoteRestConstants.UserName + "=" + this.credentials.UserName.EscapeDataString(), UriKind.Relative); return await this.MakeAsyncJobSubmissionRequest(relative, payload); } /// <inheritdoc /> public async Task<IHttpResponseMessageAbstraction> StopJob(string jobId) { var relative = new Uri(HadoopRemoteRestConstants.Jobs + "/" + jobId.EscapeDataString() + "?" + HadoopRemoteRestConstants.UserName + "=" + this.credentials.UserName.EscapeDataString(), UriKind.Relative); return await this.MakeAsyncJobCancellationRequest(relative); } /// <summary> /// Makes a HTTP GET request to the remote cluster. /// </summary> /// <param name="relativeUri">The relative uri for the request.</param> /// <returns>The response message from the remote cluster.</returns> private async Task<IHttpResponseMessageAbstraction> MakeAsyncGetRequest(Uri relativeUri) { using (var httpClient = ServiceLocator.Instance.Locate<IHttpClientAbstractionFactory>().Create(this.context, this.ignoreSslErrors)) { var uri = new Uri(this.credentials.Server, relativeUri); httpClient.RequestUri = uri; httpClient.Method = HttpMethod.Get; httpClient.Content = new StringContent(string.Empty); this.ProvideStandardHeaders(httpClient); return await SendRequestWithErrorChecking(httpClient, HttpStatusCode.OK); } } /// <summary> /// Makes a request to the remote cluster to submit a jobDetails. /// </summary> /// <param name="relativeUri">The relative uri to send the requst to.</param> /// <param name="payload">The jobDetails configuration payload.</param> /// <returns>The response message from the remote cluster.</returns> private async Task<IHttpResponseMessageAbstraction> MakeAsyncJobSubmissionRequest(Uri relativeUri, string payload) { using (var httpClient = ServiceLocator.Instance.Locate<IHttpClientAbstractionFactory>().Create(this.context, this.ignoreSslErrors)) { var uri = new Uri(this.credentials.Server, relativeUri); httpClient.RequestUri = uri; httpClient.Method = HttpMethod.Post; this.ProvideStandardHeaders(httpClient); httpClient.Content = new StringContent(payload); return await SendRequestWithErrorChecking(httpClient, HttpStatusCode.OK); } } /// <summary> /// Makes a request to the remote cluster to submit a jobDetails. /// </summary> /// <param name="relativeUri">The relative uri to send the requst to.</param> /// <returns>The response message from the remote cluster.</returns> private async Task<IHttpResponseMessageAbstraction> MakeAsyncJobCancellationRequest(Uri relativeUri) { using (var httpClient = ServiceLocator.Instance.Locate<IHttpClientAbstractionFactory>().Create(this.context, this.ignoreSslErrors)) { var uri = new Uri(this.credentials.Server, relativeUri); httpClient.RequestUri = uri; httpClient.Method = HttpMethod.Delete; httpClient.Content = new StringContent(string.Empty); this.ProvideStandardHeaders(httpClient); return await SendRequestWithErrorChecking(httpClient, HttpStatusCode.OK); } } /// <summary> /// Provides the basic authorization for a connection. /// </summary> /// <param name="httpClient"> /// The HttpClient to which authorization should be added. /// </param> private void ProvideStandardHeaders(IHttpClientAbstraction httpClient) { if (this.credentials.UserName != null && this.credentials.Password != null) { var byteArray = Encoding.ASCII.GetBytes(this.credentials.UserName + ":" + this.credentials.Password); httpClient.RequestHeaders.Add(HadoopRemoteRestConstants.Authorization, "Basic " + Convert.ToBase64String(byteArray)); } httpClient.RequestHeaders.Add("accept", "application/json"); httpClient.RequestHeaders.Add("useragent", this.GetUserAgentString()); httpClient.RequestHeaders.Add("User-Agent", this.GetUserAgentString()); } /// <summary> /// Sends a HttpCLient request, while checking for errors on the return value. /// </summary> /// <param name="httpClient">The HttpCLient instance to send.</param> /// <param name="expectedStatusCode">The status code expected for a succesful response.</param> /// <returns>The HttpResponse, after it has been checked for errors.</returns> private static async Task<IHttpResponseMessageAbstraction> SendRequestWithErrorChecking(IHttpClientAbstraction httpClient, HttpStatusCode expectedStatusCode) { var httpResponseMessage = await httpClient.SendAsync(); if (httpResponseMessage.StatusCode != expectedStatusCode) { throw new HttpLayerException(httpResponseMessage.StatusCode, httpResponseMessage.Content); } return httpResponseMessage; } } }
using System.Linq; using System; using System.Collections.Generic; public enum RuleResult { Done, Working } namespace Casanova.Prelude { public class Tuple<T,E> { public T Item1 { get; set;} public E Item2 { get; set;} public Tuple(T item1, E item2) { Item1 = item1; Item2 = item2; } } public static class MyExtensions { //public T this[List<T> list] //{ // get { return list.ElementAt(0); } //} public static bool CompareStruct<T>(this List<T> list1, List<T> list2) { if (list1.Count != list2.Count) return false; for (int i = 0; i < list1.Count; i++) { if (!list1[i].Equals(list2[i])) return false; } return true; } public static T Head<T>(this List<T> list) { return list.ElementAt(0); } public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); } public static List<T> Tail<T>(this List<T> list) { return list.Skip(1).ToList<T>(); } public static IEnumerable<T> Tail<T>(this IEnumerable<T> list) { return list.Skip(1); } public static int Length<T>(this List<T> list) { return list.Count; } public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; } } public class Cons<T> : IEnumerable<T> { public class Enumerator : IEnumerator<T> { public Enumerator(Cons<T> parent) { firstEnumerated = 0; this.parent = parent; tailEnumerator = parent.tail.GetEnumerator(); } byte firstEnumerated; Cons<T> parent; IEnumerator<T> tailEnumerator; public T Current { get { if (firstEnumerated == 0) return default(T); if (firstEnumerated == 1) return parent.head; else return tailEnumerator.Current; } } object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } } public bool MoveNext() { if (firstEnumerated == 0) { if (parent.head == null) return false; firstEnumerated++; return true; } if (firstEnumerated == 1) firstEnumerated++; return tailEnumerator.MoveNext(); } public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); } public void Dispose() { } } T head; IEnumerable<T> tail; public Cons(T head, IEnumerable<T> tail) { this.head = head; this.tail = tail; } public IEnumerator<T> GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } } public class Empty<T> : IEnumerable<T> { public Empty() { } public class Enumerator : IEnumerator<T> { public T Current { get { throw new Exception("Empty sequence has no elements"); } } object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } } public bool MoveNext() { return false; } public void Reset() { } public void Dispose() { } } public IEnumerator<T> GetEnumerator() { return new Enumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(); } } public abstract class Option<T> : IComparable, IEquatable<Option<T>> { public bool IsSome; public bool IsNone { get { return !IsSome; } } protected abstract Just<T> Some { get; } public U Match<U>(Func<T,U> f, Func<U> g) { if (this.IsSome) return f(this.Some.Value); else return g(); } public bool Equals(Option<T> b) { return this.Match( x => b.Match( y => x.Equals(y), () => false), () => b.Match( y => false, () => true)); } public override bool Equals(System.Object other) { if (other == null) return false; if (other is Option<T>) { var other1 = other as Option<T>; return this.Equals(other1); } return false; } public override int GetHashCode() { return this.GetHashCode(); } public static bool operator ==(Option<T> a, Option<T> b) { if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b); return a.Equals(b); } public static bool operator !=(Option<T> a, Option<T> b) { if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b); return !(a.Equals(b)); } public int CompareTo(object obj) { if (obj == null) return 1; if (obj is Option<T>) { var obj1 = obj as Option<T>; if (this.Equals(obj1)) return 0; } return -1; } abstract public T Value { get; } public override string ToString() { return "Option<" + typeof(T).ToString() + ">"; } } public class Just<T> : Option<T> { T elem; public Just(T elem) { this.elem = elem; this.IsSome = true; } protected override Just<T> Some { get { return this; } } public override T Value { get { return elem; } } } public class Nothing<T> : Option<T> { public Nothing() { this.IsSome = false; } protected override Just<T> Some { get { return null; } } public override T Value { get { throw new Exception("Cant get a value from a None object"); } } } public class Utils { public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e) { if (c()) return t(); else return e(); } } } public class FastStack { public int[] Elements; public int Top; public FastStack(int elems) { Top = 0; Elements = new int[elems]; } public void Clear() { Top = 0; } public void Push(int x) { Elements[Top++] = x; } } public class RuleTable { public RuleTable(int elems) { ActiveIndices = new FastStack(elems); SupportStack = new FastStack(elems); ActiveSlots = new bool[elems]; SupportSlots = new bool[elems]; } public FastStack ActiveIndices; public FastStack SupportStack; public bool[] ActiveSlots; public bool[] SupportSlots; public void Clear() { for (int i = 0; i < ActiveSlots.Length; i++) { ActiveSlots[i] = false; } } public void Add(int i) { if (!ActiveSlots[i]) { ActiveSlots[i] = true; ActiveIndices.Push(i); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesDeleteAlias2 { public partial class IndicesDeleteAlias2YamlTests { public class IndicesDeleteAlias2AllPathOptionsYamlBase : YamlTestsBase { public IndicesDeleteAlias2AllPathOptionsYamlBase() : base() { //do indices.create this.Do(()=> _client.IndicesCreate("test_index1", null)); //do indices.create this.Do(()=> _client.IndicesCreate("test_index2", null)); //do indices.create this.Do(()=> _client.IndicesCreate("foo", null)); //do indices.put_alias _body = new { routing= "routing value" }; this.Do(()=> _client.IndicesPutAliasForAll("alias1", _body)); //do indices.put_alias _body = new { routing= "routing value" }; this.Do(()=> _client.IndicesPutAliasForAll("alias2", _body)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithAllIndex3Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void CheckDeleteWithAllIndex3Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("_all", "alias1")); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias1"), shouldCatch: @"missing"); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias2")); //match _response.test_index1.aliases.alias2.search_routing: this.IsMatch(_response.test_index1.aliases.alias2.search_routing, @"routing value"); //match _response.test_index2.aliases.alias2.search_routing: this.IsMatch(_response.test_index2.aliases.alias2.search_routing, @"routing value"); //match _response.foo.aliases.alias2.search_routing: this.IsMatch(_response.foo.aliases.alias2.search_routing, @"routing value"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndex4Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndex4Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("*", "alias1")); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias1"), shouldCatch: @"missing"); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias2")); //match _response.test_index1.aliases.alias2.search_routing: this.IsMatch(_response.test_index1.aliases.alias2.search_routing, @"routing value"); //match _response.test_index2.aliases.alias2.search_routing: this.IsMatch(_response.test_index2.aliases.alias2.search_routing, @"routing value"); //match _response.foo.aliases.alias2.search_routing: this.IsMatch(_response.foo.aliases.alias2.search_routing, @"routing value"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndexList5Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndexList5Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("test_index1,test_index2", "alias1")); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias1")); //match _response.foo.aliases.alias1.search_routing: this.IsMatch(_response.foo.aliases.alias1.search_routing, @"routing value"); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias2")); //match _response.test_index1.aliases.alias2.search_routing: this.IsMatch(_response.test_index1.aliases.alias2.search_routing, @"routing value"); //match _response.test_index2.aliases.alias2.search_routing: this.IsMatch(_response.test_index2.aliases.alias2.search_routing, @"routing value"); //match _response.foo.aliases.alias2.search_routing: this.IsMatch(_response.foo.aliases.alias2.search_routing, @"routing value"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithPrefixIndex6Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void CheckDeleteWithPrefixIndex6Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("test_*", "alias1")); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias1")); //match _response.foo.aliases.alias1.search_routing: this.IsMatch(_response.foo.aliases.alias1.search_routing, @"routing value"); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias2")); //match _response.test_index1.aliases.alias2.search_routing: this.IsMatch(_response.test_index1.aliases.alias2.search_routing, @"routing value"); //match _response.test_index2.aliases.alias2.search_routing: this.IsMatch(_response.test_index2.aliases.alias2.search_routing, @"routing value"); //match _response.foo.aliases.alias2.search_routing: this.IsMatch(_response.foo.aliases.alias2.search_routing, @"routing value"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndexListAndAliases7Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndexListAndAliases7Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("test_index1,test_index2", "*")); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias1")); //match _response.foo.aliases.alias1.search_routing: this.IsMatch(_response.foo.aliases.alias1.search_routing, @"routing value"); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias2")); //match _response.foo.aliases.alias2.search_routing: this.IsMatch(_response.foo.aliases.alias2.search_routing, @"routing value"); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndexListAndAllAliases8Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndexListAndAllAliases8Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("test_index1,test_index2", "_all")); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias1")); //match _response.foo.aliases.alias1.search_routing: this.IsMatch(_response.foo.aliases.alias1.search_routing, @"routing value"); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias2")); //match _response.foo.aliases.alias2.search_routing: this.IsMatch(_response.foo.aliases.alias2.search_routing, @"routing value"); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndexListAndWildcardAliases9Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndexListAndWildcardAliases9Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("test_index1,test_index2", "*1")); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias1")); //match _response.foo.aliases.alias1.search_routing: this.IsMatch(_response.foo.aliases.alias1.search_routing, @"routing value"); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("alias2")); //match _response.test_index1.aliases.alias2.search_routing: this.IsMatch(_response.test_index1.aliases.alias2.search_routing, @"routing value"); //match _response.test_index2.aliases.alias2.search_routing: this.IsMatch(_response.test_index2.aliases.alias2.search_routing, @"routing value"); //match _response.foo.aliases.alias2.search_routing: this.IsMatch(_response.foo.aliases.alias2.search_routing, @"routing value"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class Check404OnNoMatchingAlias10Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void Check404OnNoMatchingAlias10Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("*", "non_existent"), shouldCatch: @"missing"); //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("non_existent", "alias1"), shouldCatch: @"missing"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithBlankIndexAndBlankAlias11Tests : IndicesDeleteAlias2AllPathOptionsYamlBase { [Test] public void CheckDeleteWithBlankIndexAndBlankAlias11Test() { //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("", "alias1"), shouldCatch: @"param"); //do indices.delete_alias this.Do(()=> _client.IndicesDeleteAlias("test_index1", ""), shouldCatch: @"param"); } } } }
using System; using System.Collections.Specialized; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Web; namespace Netco.Net { /// <summary> /// Submits post data to a url. /// </summary> /// <seealso href="http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx"/> /// <example>Example on how to POST /// <code> /// PostSubmitter post=new PostSubmitter(); /// post.Url="http://seeker.dice.com/jobsearch/servlet/JobSearch"; /// post.PostItems.Add("op","100"); /// post.PostItems.Add("rel_code","1102"); /// post.PostItems.Add("FREE_TEXT","c# jobs"); /// post.PostItems.Add("SEARCH",""); /// post.Type=PostSubmitter.PostTypeEnum.Post; /// string result=post.Post();</code></example> public class PostSubmitter { #region Config private string _url = string.Empty; private NameValueCollection _values = new NameValueCollection(); private PostTypeEnum _type = PostTypeEnum.Post; /// <summary> /// Gets or sets a value indicating whether to ignore errors, or throw exception. /// </summary> /// <value><c>true</c> if errors should be ignored; otherwise, <c>false</c>.</value> public bool IgnoreErrors { get; set; } /// <summary> /// Gets or sets the request timeout. /// </summary> /// <value>The request timeout.</value> /// <remarks><see cref="TimeSpan.MaxValue"/> indicates infinite timeout (never timeouts).</remarks> public TimeSpan? Timeout { get; set; } /// <summary> /// Gets or sets the read/write timeout. /// </summary> /// <value>The read/write timeout.</value> /// <remarks><see cref="TimeSpan.MaxValue"/> indicates infinite timeout (never timeouts).</remarks> public TimeSpan? ReadWriteTimeout { get; set; } /// <summary> /// Default constructor. /// </summary> public PostSubmitter() { this.Timeout = TimeSpan.FromSeconds( 100 ); this.ReadWriteTimeout = TimeSpan.FromMinutes( 5 ); } /// <summary> /// Constructor that accepts a url as a parameter /// </summary> /// <param name="url">The url where the post will be submitted to.</param> public PostSubmitter( string url ) : this() { this._url = url; } /// <summary> /// Constructor allowing the setting of the url and items to post. /// </summary> /// <param name="url">the url for the post.</param> /// <param name="values">The values for the post.</param> public PostSubmitter( string url, NameValueCollection values ) : this( url ) { this._values = values; } /// <summary> /// Gets or sets the url to submit the post to. /// </summary> public string Url { get { return this._url; } set { this._url = value; } } /// <summary> /// Gets or sets the name value collection of items to post. /// </summary> public NameValueCollection PostItems { get { return this._values; } set { this._values = value; } } /// <summary> /// Gets or sets the type of action to perform against the url. /// </summary> public PostTypeEnum Type { get { return this._type; } set { this._type = value; } } #endregion #region Sync Post /// <summary> /// Posts the supplied data to specified url. /// </summary> /// <returns>a string containing the result of the post.</returns> public string Post() { var result = this.PostData( this._url, this.GetParameters() ); return result; } /// <summary> /// Posts the supplied data to specified url. /// </summary> /// <param name="url">The url to post to.</param> /// <returns>a string containing the result of the post.</returns> public string Post( string url ) { this._url = url; return this.Post(); } /// <summary> /// Posts the supplied data to specified url. /// </summary> /// <param name="url">The url to post to.</param> /// <param name="values">The values to post.</param> /// <returns>a string containing the result of the post.</returns> public string Post( string url, NameValueCollection values ) { this._values = values; return this.Post( url ); } /// <summary> /// Posts data to a specified url. Note: this assumes that you have already url encoded the post data. /// </summary> /// <param name="postData">The data to post.</param> /// <param name="url">the url to post to.</param> /// <returns>Returns the result of the post.</returns> private string PostData( string url, string postData ) { try { HttpWebRequest request; if( this._type == PostTypeEnum.Post ) { var uri = new Uri( url ); request = ( HttpWebRequest )WebRequest.Create( uri ); request.Method = "POST"; this.SetTimeout( this.Timeout, x => request.Timeout = x ); this.SetTimeout( this.ReadWriteTimeout, x => request.ReadWriteTimeout = x ); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postData.Length; using( var writeStream = request.GetRequestStream() ) { var bytes = Encoding.UTF8.GetBytes( postData ); writeStream.Write( bytes, 0, bytes.Length ); } } else { // PostTypeEnum.Get var uri = new Uri( url + "?" + postData ); request = ( HttpWebRequest )WebRequest.Create( uri ); request.Method = "GET"; this.SetTimeout( this.Timeout, x => request.Timeout = x ); this.SetTimeout( this.ReadWriteTimeout, x => request.ReadWriteTimeout = x ); } string result; using( var response = ( HttpWebResponse )request.GetResponse() ) using( var responseStream = response.GetResponseStream() ) using( var readStream = new StreamReader( responseStream, Encoding.UTF8 ) ) result = readStream.ReadToEnd(); return result; } catch { if( this.IgnoreErrors ) return null; else throw; } } #endregion #region Async Post /// <summary> /// Raised when asynchronous post is finished. /// </summary> public event EventHandler< AsyncPostFinishedEventArgs > AsyncPostFinished; /// <summary> /// Posts the supplied data to specified url using async methods. /// </summary> public void BeginPost() { this.PostDataAsync( this._url, this.GetParameters() ); } /// <summary> /// Posts the supplied data to specified url using async methods. /// </summary> /// <param name="url">The url to post to.</param> public void BeginPost( string url ) { this._url = url; this.BeginPost(); } /// <summary> /// Posts the supplied data to specified url using async methods. /// </summary> /// <param name="url">The url to post to.</param> /// <param name="values">The values to post.</param> public void BeginPost( string url, NameValueCollection values ) { this._values = values; this.BeginPost( url ); } /// <summary> /// Posts data to a specified <paramref name="url"/>. /// </summary> /// <remarks>Assumes that you have already <paramref name="url"/> encoded the post data</remarks> /// <param name="postData">The data to post.</param> /// <param name="url">The <c>url</c> to post to.</param> private void PostDataAsync( string url, string postData ) { try { var requestSate = new RequestState { PostData = postData }; HttpWebRequest request; if( this._type == PostTypeEnum.Post ) { var uri = new Uri( url ); request = ( HttpWebRequest )WebRequest.Create( uri ); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postData.Length; this.SetTimeout( this.Timeout, x => request.Timeout = x ); this.SetTimeout( this.ReadWriteTimeout, x => request.ReadWriteTimeout = x ); requestSate.Request = request; request.BeginGetRequestStream( this.RequestWriteCallback, requestSate ); } else { var uri = new Uri( url + "?" + postData ); request = ( HttpWebRequest )WebRequest.Create( uri ); request.Method = "GET"; this.SetTimeout( this.Timeout, x => request.Timeout = x ); this.SetTimeout( this.ReadWriteTimeout, x => request.ReadWriteTimeout = x ); requestSate.Request = request; this.BeginHandlingResponse( requestSate ); } } catch { if( !this.IgnoreErrors ) throw; } } private void RequestWriteCallback( IAsyncResult asynchronousResult ) { try { var requestState = ( RequestState )asynchronousResult.AsyncState; // End the operation. using( var writeStream = requestState.Request.EndGetRequestStream( asynchronousResult ) ) { var bytes = Encoding.UTF8.GetBytes( requestState.PostData ); writeStream.Write( bytes, 0, bytes.Length ); } this.BeginHandlingResponse( requestState ); } catch { if( !this.IgnoreErrors ) throw; } } #region Get Async Response private void BeginHandlingResponse( RequestState requestState ) { try { // Start the asynchronous request. var asyncResult = requestState.Request.BeginGetResponse( this.ResponseCallback, requestState ); // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted ThreadPool.RegisterWaitForSingleObject( asyncResult.AsyncWaitHandle, TimeoutCallback, requestState, DefaultTimeout, true ); } catch { if( !this.IgnoreErrors ) throw; } } private void ResponseCallback( IAsyncResult asynchronousResult ) { try { // State of request is asynchronous. var requestState = ( RequestState )asynchronousResult.AsyncState; var httpWebRequest = requestState.Request; requestState.Response = ( HttpWebResponse )httpWebRequest.EndGetResponse( asynchronousResult ); // Read the response into a Stream object. using( var responseStream = requestState.Response.GetResponseStream() ) using( var readStream = new StreamReader( responseStream, Encoding.UTF8 ) ) { var result = readStream.ReadToEnd(); var asyncPostFinished = this.AsyncPostFinished; if( asyncPostFinished != null ) asyncPostFinished.Invoke( this, new AsyncPostFinishedEventArgs( result ) ); } } catch { if( !this.IgnoreErrors ) throw; } } // Abort the request if the timer fires. private static void TimeoutCallback( object state, bool timedOut ) { if( timedOut ) { var request = state as HttpWebRequest; if( request != null ) request.Abort(); } } private const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout #endregion #endregion #region Misc methods /// <summary> /// Gets parameters string. /// </summary> /// <returns>All parameters encoded in a single string.</returns> private string GetParameters() { var parameters = new StringBuilder(); for( var i = 0; i < this._values.Count; i++ ) { this.EncodeAndAddItem( ref parameters, this._values.GetKey( i ), this._values[ i ] ); } return parameters.ToString(); } /// <summary> /// Encodes an item and ads it to the string. /// </summary> /// <param name="baseRequest">The previously encoded data.</param> /// <param name="key">Param key.</param> /// <param name="dataItem">The data to encode.</param> /// <returns>A string containing the old data and the previously encoded data.</returns> private void EncodeAndAddItem( ref StringBuilder baseRequest, string key, string dataItem ) { if( baseRequest == null ) baseRequest = new StringBuilder(); if( baseRequest.Length != 0 ) baseRequest.Append( "&" ); baseRequest.Append( key ); baseRequest.Append( "=" ); baseRequest.Append( HttpUtility.UrlEncode( dataItem ) ); } /// <summary> /// Sets the timeout. /// </summary> /// <param name="timeout">The timeout.</param> /// <param name="methodToSetTimout">The method to set timout.</param> private void SetTimeout( TimeSpan? timeout, Action< int > methodToSetTimout ) { if( !timeout.HasValue ) return; methodToSetTimout( timeout.Value != TimeSpan.MaxValue ? Convert.ToInt32( timeout.Value.TotalMilliseconds ) : System.Threading.Timeout.Infinite ); } #endregion #region Misc Data Types /// <summary> /// determines what type of post to perform. /// </summary> public enum PostTypeEnum { /// <summary> /// Does a get against the source. /// </summary> Get, /// <summary> /// Does a post against the source. /// </summary> Post } private class RequestState { // This class stores the State of the request. public const int BufferSize = 1024; public StringBuilder RequestData { get; private set; } public byte[] BufferRead { get; private set; } public HttpWebRequest Request { get; set; } public HttpWebResponse Response { get; set; } public Stream StreamResponse { get; set; } public string PostData { get; set; } public RequestState() { this.BufferRead = new byte[ BufferSize ]; this.RequestData = new StringBuilder( string.Empty ); this.Request = null; this.StreamResponse = null; this.PostData = string.Empty; } } /// <summary> /// Event arguments for <see cref="PostSubmitter.AsyncPostFinished"/> /// </summary> public class AsyncPostFinishedEventArgs : EventArgs { internal AsyncPostFinishedEventArgs( string result ) { this.Result = result; } /// <summary>Gets the result of asynchronous post.</summary> public string Result { get; private set; } } #endregion } }
#region File Description //----------------------------------------------------------------------------- // PlayingScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace Pickture { /// <summary> /// The main game screen. This is where the player spends most of his or her time, /// trying to solve the puzzle! /// </summary> class PlayingScreen : GameScreen { Board board; // Coordinates of the chip focused for GamePad input int activeChipX; int activeChipY; /// <summary> /// The chip focused for GamePad input. /// </summary> public Chip ActiveChip { get { return board.GetChip(activeChipX, activeChipY); } } public PlayingScreen(Board board) { this.board = board; // Always start the active chip on the top row activeChipY = board.Height - 1; // And the left most chip on that row if (board.TwoSided) { // When two sided, the Shuffling screen will have flipped the board, so // the left side of the view is really the high end of the board activeChipX = board.Width - 1; if (ActiveChip == null) activeChipX--; } else { activeChipX = 0; if (ActiveChip == null) activeChipX++; } // Show through to the BoardScreen IsPopup = true; } public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (ActiveChip != null) { // Highlight the active chip with a pulsating glow double elapsed = gameTime.TotalRealTime.TotalSeconds; ActiveChip.GlowScale = ((float)Math.Sin(elapsed * Math.PI) + 1.0f) / 2.0f; } } public override void HandleInput(InputState input) { if (input.MenuCancel) { MessageBoxScreen messageBox = new MessageBoxScreen( "Are you sure you want to quit this game?\nYour progress will be lost"); messageBox.Accepted += QuitMessageBoxAccepted; ScreenManager.AddScreen(messageBox); } // Do not handle controls while the camera is flipping if (board.Camera.IsFlipping) return; // Some controls only apply when the puzzle is two sided if (board.TwoSided) { // Handle flipping camera to other side of board if (input.FlipCameraLeft) { board.Camera.Flip(Camera.FlipDirection.Left); } else if (input.FlipCameraRight) { board.Camera.Flip(Camera.FlipDirection.Right); } // Handle flipping the active chip else if (input.FlipUp) { if (board.Camera.Side == Camera.BoardSide.Front) ActiveChip.Flip(Chip.RevolveDirection.Up); else ActiveChip.Flip(Chip.RevolveDirection.Down); } else if (input.FlipDown) { if (board.Camera.Side == Camera.BoardSide.Front) ActiveChip.Flip(Chip.RevolveDirection.Down); else ActiveChip.Flip(Chip.RevolveDirection.Up); } else if (input.FlipLeft) { ActiveChip.Flip(Chip.RevolveDirection.Left); } else if (input.FlipRight) { ActiveChip.Flip(Chip.RevolveDirection.Right); } } // Handle selecting a new active chip HandleChipSelection(input); // Handle shifting if (input.ShiftActiveChip && !board.IsShifting) { board.Shift(activeChipX, activeChipY); if (board.IsShifting) { // When a shift occurs, the active chip moves with the shift SetActiveChip(activeChipX + board.ShiftX, activeChipY + board.ShiftY); } } // Did any moves during this update result in the puzzle being sovled? if (this.board.IsPuzzleComplete()) { // Transition to the CompletedScreen ExitScreen(); foreach (GameScreen screen in ScreenManager.GetScreens()) { if (screen is BoardScreen) screen.ExitScreen(); } ScreenManager.AddScreen(new CompletedScreen(board.CurrentPictureSet)); } } /// <summary> /// Event handler for when the user selects ok on the "are you sure /// you want to quit" message box. /// </summary> void QuitMessageBoxAccepted(object sender, EventArgs e) { ExitToMenu(); } /// <summary> /// Exits this screen and the board screen below it. /// </summary> void ExitToMenu() { ExitScreen(); foreach (GameScreen screen in ScreenManager.GetScreens()) { if (screen is BoardScreen) screen.ExitScreen(); } ScreenManager.AddScreen(new MainMenuScreen()); } void HandleChipSelection(InputState input) { int moveX = 0; int moveY = 0; // Determine a movement vector if (input.MenuUp) moveY = 1; else if (input.MenuDown) moveY = -1; else if (input.MenuLeft) moveX = -1; else if (input.MenuRight) moveX = 1; // Reflect the X axis when looking at the back side of the board if (board.Camera.Side == Camera.BoardSide.Back) moveX *= -1; // Try to move in the desired direction. Attempts up to two steps to // support skipping over the blank space. for (int i = 1; i <= 2; i++) { int x = activeChipX + moveX * i; int y = activeChipY + moveY * i; if (0 <= x && x < board.Width && 0 <= y && y < board.Height && board.GetChip(x, y) != null) { SetActiveChip(x, y); break; } } } void SetActiveChip(int x, int y) { if (activeChipX == x && activeChipY == y) return; // Remove any glow from the no-longer active chip if (ActiveChip != null) ActiveChip.GlowScale = 0.0f; activeChipX = x; activeChipY = y; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForAccessorsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyForAccessorsDiagnosticAnalyzer(), new UseExpressionBodyForAccessorsCodeFixProvider()); private IDictionary<OptionKey, object> UseExpressionBody => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement)); private IDictionary<OptionKey, object> UseExpressionBodyIncludingPropertiesAndIndexers => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement)); private IDictionary<OptionKey, object> UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { await TestInRegularAndScriptAsync( @"class C { int Foo { get { [|return|] Bar(); } } }", @"class C { int Foo { get => Bar(); } }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingIfPropertyIsOn() { await TestMissingInRegularAndScriptAsync( @"class C { int Foo { get { [|return|] Bar(); } } }", new TestParameters(options: UseExpressionBodyIncludingPropertiesAndIndexers)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnIndexer1() { await TestInRegularAndScriptAsync( @"class C { int this[int i] { get { [|return|] Bar(); } } }", @"class C { int this[int i] { get => Bar(); } }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingIfIndexerIsOn() { await TestMissingInRegularAndScriptAsync( @"class C { int this[int i] { get { [|return|] Bar(); } } }", new TestParameters(options: UseExpressionBodyIncludingPropertiesAndIndexers)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnSetter1() { await TestInRegularAndScriptAsync( @"class C { int Foo { set { [|Bar|](); } } }", @"class C { int Foo { set => [|Bar|](); } }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlySetter() { await TestActionCountAsync( @"class C { int Foo { set => [|Bar|](); } }", count: 1, parameters: new TestParameters(options: UseExpressionBody)); // There is a hidden diagnostic that still offers to convert expression-body to block-body. await TestInRegularAndScriptAsync( @"class C { int Foo { set => [|Bar|](); } }", @"class C { int Foo { set { Bar(); } } }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { await TestInRegularAndScriptAsync( @"class C { int Foo { get { [|throw|] new NotImplementedException(); } } }", @"class C { int Foo { get => throw new NotImplementedException(); } }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { await TestInRegularAndScriptAsync( @"class C { int Foo { get { [|throw|] new NotImplementedException(); // comment } } }", @"class C { int Foo { get => throw new NotImplementedException(); // comment } }", ignoreTrivia: false, options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { await TestInRegularAndScriptAsync( @"class C { int Foo { get [|=>|] Bar(); } }", @"class C { int Foo { get { return Bar(); } } }", options: UseBlockBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForSetter1() { await TestInRegularAndScriptAsync( @"class C { int Foo { set [|=>|] Bar(); } }", @"class C { int Foo { set { Bar(); } } }", options: UseBlockBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { await TestInRegularAndScriptAsync( @"class C { int Foo { get [|=>|] throw new NotImplementedException(); } }", @"class C { int Foo { get { throw new NotImplementedException(); } } }", options: UseBlockBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { await TestInRegularAndScriptAsync( @"class C { int Foo { get [|=>|] throw new NotImplementedException(); // comment } }", @"class C { int Foo { get { throw new NotImplementedException(); // comment } } }", ignoreTrivia: false, options: UseBlockBody); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using GitTfs.Commands; using GitTfs.Core; using GitTfs.Core.TfsInterop; using GitTfs.Util; using StructureMap; namespace GitTfs.VsFake { public class MockBranchObject : IBranchObject { public string Path { get; set; } public string ParentPath { get; set; } public bool IsRoot { get; set; } } public class TfsHelper : ITfsHelper { #region misc/null private readonly IContainer _container; private readonly Script _script; private readonly FakeVersionControlServer _versionControlServer; public TfsHelper(IContainer container, Script script) { _container = container; _script = script; _versionControlServer = new FakeVersionControlServer(_script); } public string TfsClientLibraryVersion { get { return "(FAKE)"; } } public string Url { get; set; } public string Username { get; set; } public string Password { get; set; } public void EnsureAuthenticated() { } public void SetPathResolver() { } public bool CanShowCheckinDialog { get { return false; } } public int ShowCheckinDialog(IWorkspace workspace, IPendingChange[] pendingChanges, IEnumerable<IWorkItemCheckedInfo> checkedInfos, string checkinComment) { throw new NotImplementedException(); } public IIdentity GetIdentity(string username) { if (username == "vtccds_cp") return new FakeIdentity { DisplayName = username, MailAddress = "b8d46dada4dd62d2ab98a2bda7310285c42e46f6qvabajY2" }; return new NullIdentity(); } #endregion #region read changesets public ITfsChangeset GetLatestChangeset(IGitTfsRemote remote) { return _script.Changesets.LastOrDefault().Try(x => BuildTfsChangeset(x, remote)); } public int GetLatestChangesetId(IGitTfsRemote remote) { return _script.Changesets.LastOrDefault().Id; } public IEnumerable<ITfsChangeset> GetChangesets(string path, int startVersion, IGitTfsRemote remote, int lastVersion = -1, bool byLots = false) { if (!_script.Changesets.Any(c => c.IsBranchChangeset) && _script.Changesets.Any(c => c.IsMergeChangeset)) return _script.Changesets.Where(x => x.Id >= startVersion).Select(x => BuildTfsChangeset(x, remote)); var branchPath = path + "/"; return _script.Changesets .Where(x => x.Id >= startVersion && x.Changes.Any(c => c.RepositoryPath.IndexOf(branchPath, StringComparison.CurrentCultureIgnoreCase) == 0 || branchPath.IndexOf(c.RepositoryPath, StringComparison.CurrentCultureIgnoreCase) == 0)) .Select(x => BuildTfsChangeset(x, remote)); } public int FindMergeChangesetParent(string path, int firstChangeset, GitTfsRemote remote) { var firstChangesetOfBranch = _script.Changesets.FirstOrDefault(c => c.IsMergeChangeset && c.MergeChangesetDatas.MergeIntoBranch == path && c.MergeChangesetDatas.BeforeMergeChangesetId < firstChangeset); if (firstChangesetOfBranch != null) return firstChangesetOfBranch.MergeChangesetDatas.BeforeMergeChangesetId; return -1; } private ITfsChangeset BuildTfsChangeset(ScriptedChangeset changeset, IGitTfsRemote remote) { var tfsChangeset = _container.With<ITfsHelper>(this).With<IChangeset>(new Changeset(_versionControlServer, changeset)).GetInstance<TfsChangeset>(); tfsChangeset.Summary = new TfsChangesetInfo { ChangesetId = changeset.Id, Remote = remote }; return tfsChangeset; } private class Changeset : IChangeset { private readonly IVersionControlServer _versionControlServer; private readonly ScriptedChangeset _changeset; public Changeset(IVersionControlServer versionControlServer, ScriptedChangeset changeset) { _versionControlServer = versionControlServer; _changeset = changeset; } public IChange[] Changes { get { return _changeset.Changes.Select(x => new Change(_versionControlServer, _changeset, x)).ToArray(); } } public string Committer { get { return _changeset.Committer ?? "todo"; } } public DateTime CreationDate { get { return _changeset.CheckinDate; } } public string Comment { get { return _changeset.Comment.Replace("\n", "\r\n"); } } public int ChangesetId { get { return _changeset.Id; } } public IVersionControlServer VersionControlServer { get { throw new NotImplementedException(); } } public void Get(ITfsWorkspace workspace, IEnumerable<IChange> changes, Action<Exception> ignorableErrorHandler) { workspace.Get(ChangesetId, changes); } } private class Change : IChange, IItem { private readonly IVersionControlServer _versionControlServer; private readonly ScriptedChangeset _changeset; private readonly ScriptedChange _change; public Change(IVersionControlServer versionControlServer, ScriptedChangeset changeset, ScriptedChange change) { _versionControlServer = versionControlServer; _changeset = changeset; _change = change; } TfsChangeType IChange.ChangeType { get { return _change.ChangeType; } } IItem IChange.Item { get { return this; } } IVersionControlServer IItem.VersionControlServer { get { return _versionControlServer; } } int IItem.ChangesetId { get { return _changeset.Id; } } string IItem.ServerItem { get { return _change.RepositoryPath; } } int IItem.DeletionId { get { return 0; } } TfsItemType IItem.ItemType { get { return _change.ItemType; } } int IItem.ItemId { get { return _change.ItemId.Value; } } long IItem.ContentLength { get { using (var temp = ((IItem)this).DownloadFile()) return new FileInfo(temp).Length; } } TemporaryFile IItem.DownloadFile() { var temp = new TemporaryFile(); using (var stream = File.Create(temp)) using (var writer = new BinaryWriter(stream)) writer.Write(_change.Content); return temp; } } #endregion #region workspaces public void WithWorkspace(string localDirectory, IGitTfsRemote remote, IEnumerable<Tuple<string, string>> mappings, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action) { Trace.WriteLine("Setting up a TFS workspace at " + localDirectory); var fakeWorkspace = new FakeWorkspace(localDirectory, remote.TfsRepositoryPath); var workspace = _container.With("localDirectory").EqualTo(localDirectory) .With("remote").EqualTo(remote) .With("contextVersion").EqualTo(versionToFetch) .With("workspace").EqualTo(fakeWorkspace) .With("tfsHelper").EqualTo(this) .GetInstance<TfsWorkspace>(); action(workspace); } public void WithWorkspace(string directory, IGitTfsRemote remote, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action) { Trace.WriteLine("Setting up a TFS workspace at " + directory); var fakeWorkspace = new FakeWorkspace(directory, remote.TfsRepositoryPath); var workspace = _container.With("localDirectory").EqualTo(directory) .With("remote").EqualTo(remote) .With("contextVersion").EqualTo(versionToFetch) .With("workspace").EqualTo(fakeWorkspace) .With("tfsHelper").EqualTo(this) .GetInstance<TfsWorkspace>(); action(workspace); } private class FakeWorkspace : IWorkspace { private readonly string _directory; private readonly string _repositoryRoot; public FakeWorkspace(string directory, string repositoryRoot) { _directory = directory; _repositoryRoot = repositoryRoot; } public void GetSpecificVersion(int changesetId, IEnumerable<IItem> items) { throw new NotImplementedException(); } public void GetSpecificVersion(IChangeset changeset) { GetSpecificVersion(changeset.ChangesetId, changeset.Changes); } public void GetSpecificVersion(int changeset, IEnumerable<IChange> changes) { var repositoryRoot = _repositoryRoot.ToLower(); if (!repositoryRoot.EndsWith("/")) repositoryRoot += "/"; foreach (var change in changes) { if (change.Item.ItemType == TfsItemType.File) { var outPath = Path.Combine(_directory, change.Item.ServerItem.ToLower().Replace(repositoryRoot, "")); var outDir = Path.GetDirectoryName(outPath); if (!Directory.Exists(outDir)) Directory.CreateDirectory(outDir); using (var download = change.Item.DownloadFile()) File.WriteAllText(outPath, File.ReadAllText(download.Path)); } } } #region unimplemented public void Merge(string sourceTfsPath, string tfsRepositoryPath) { throw new NotImplementedException(); } public IPendingChange[] GetPendingChanges() { throw new NotImplementedException(); } public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges) { throw new NotImplementedException(); } public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, string authors, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges) { throw new NotImplementedException(); } public void Shelve(IShelveset shelveset, IPendingChange[] changes, TfsShelvingOptions options) { throw new NotImplementedException(); } public int Checkin(IPendingChange[] changes, string comment, string author, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges, TfsPolicyOverrideInfo policyOverrideInfo, bool overrideGatedCheckIn) { throw new NotImplementedException(); } public int PendAdd(string path) { throw new NotImplementedException(); } public int PendEdit(string path) { throw new NotImplementedException(); } public int PendDelete(string path) { throw new NotImplementedException(); } public int PendRename(string pathFrom, string pathTo) { throw new NotImplementedException(); } public void ForceGetFile(string path, int changeset) { throw new NotImplementedException(); } public void GetSpecificVersion(int changeset) { throw new NotImplementedException(); } public string GetLocalItemForServerItem(string serverItem) { throw new NotImplementedException(); } public string GetServerItemForLocalItem(string localItem) { throw new NotImplementedException(); } public string OwnerName { get { throw new NotImplementedException(); } } #endregion } public void CleanupWorkspaces(string workingDirectory) { } public bool IsExistingInTfs(string path) { var exists = false; foreach (var changeset in _script.Changesets) { foreach (var change in changeset.Changes) { if (change.RepositoryPath == path) { exists = !change.ChangeType.IncludesOneOf(TfsChangeType.Delete); } } } return exists; } public bool CanGetBranchInformation { get { return true; } } public IChangeset GetChangeset(int changesetId) { return new Changeset(_versionControlServer, _script.Changesets.First(c => c.Id == changesetId)); } public IList<RootBranch> GetRootChangesetForBranch(string tfsPathBranchToCreate, int lastChangesetIdToCheck = -1, string tfsPathParentBranch = null) { var branchChangesets = _script.Changesets.Where(c => c.IsBranchChangeset); var firstBranchChangeset = branchChangesets.FirstOrDefault(c => c.BranchChangesetDatas.BranchPath == tfsPathBranchToCreate); var rootBranches = new List<RootBranch>(); if (firstBranchChangeset != null) { do { var rootBranch = new RootBranch( firstBranchChangeset.BranchChangesetDatas.RootChangesetId, firstBranchChangeset.Id, firstBranchChangeset.BranchChangesetDatas.BranchPath ); rootBranch.IsRenamedBranch = DeletedBranchesPathes.Contains(rootBranch.TfsBranchPath); rootBranches.Add(rootBranch); firstBranchChangeset = branchChangesets.FirstOrDefault(c => c.BranchChangesetDatas.BranchPath == firstBranchChangeset.BranchChangesetDatas.ParentBranch); } while (firstBranchChangeset != null); rootBranches.Reverse(); return rootBranches; } rootBranches.Add(new RootBranch(-1, tfsPathBranchToCreate)); return rootBranches; } private List<string> _deletedBranchesPathes; private List<string> DeletedBranchesPathes { get { return _deletedBranchesPathes ?? (_deletedBranchesPathes = _script.Changesets.Where(c => c.IsBranchChangeset && c.Changes.Any(ch => ch.ChangeType == TfsChangeType.Delete && ch.RepositoryPath == c.BranchChangesetDatas.ParentBranch)) .Select(b => b.BranchChangesetDatas.ParentBranch).ToList()); } } public IEnumerable<IBranchObject> GetBranches(bool getDeletedBranches = false) { var renamings = _script.Changesets.Where( c => c.IsBranchChangeset && DeletedBranchesPathes.Any(b => b == c.BranchChangesetDatas.BranchPath)).ToList(); var branches = new List<IBranchObject>(); branches.AddRange(_script.RootBranches.Select(b => new MockBranchObject { IsRoot = true, Path = b.BranchPath, ParentPath = null })); branches.AddRange(_script.Changesets.Where(c => c.IsBranchChangeset).Select(c => new MockBranchObject { IsRoot = false, Path = c.BranchChangesetDatas.BranchPath, ParentPath = GetRealRootBranch(renamings, c.BranchChangesetDatas.ParentBranch) })); if (!getDeletedBranches) branches.RemoveAll(b => DeletedBranchesPathes.Contains(b.Path)); return branches; } private string GetRealRootBranch(List<ScriptedChangeset> deletedBranches, string branchPath) { var realRoot = branchPath; while (true) { var parent = deletedBranches.FirstOrDefault(b => b.BranchChangesetDatas.BranchPath == realRoot); if (parent == null) return realRoot; realRoot = parent.BranchChangesetDatas.ParentBranch; } } #endregion #region unimplemented public IShelveset CreateShelveset(IWorkspace workspace, string shelvesetName) { throw new NotImplementedException(); } public IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction) { throw new NotImplementedException(); } public IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction) { throw new NotImplementedException(); } public ICheckinNote CreateCheckinNote(Dictionary<string, string> checkinNotes) { throw new NotImplementedException(); } public ITfsChangeset GetChangeset(int changesetId, IGitTfsRemote remote) { throw new NotImplementedException(); } public bool HasShelveset(string shelvesetName) { throw new NotImplementedException(); } public ITfsChangeset GetShelvesetData(IGitTfsRemote remote, string shelvesetOwner, string shelvesetName) { throw new NotImplementedException(); } public int ListShelvesets(ShelveList shelveList, IGitTfsRemote remote) { throw new NotImplementedException(); } public IEnumerable<string> GetAllTfsRootBranchesOrderedByCreation() { return new List<string>(); } public IEnumerable<TfsLabel> GetLabels(string tfsPathBranch, string nameFilter = null) { throw new NotImplementedException(); } public void CreateBranch(string sourcePath, string targetPath, int changesetId, string comment = null) { throw new NotImplementedException(); } public void CreateTfsRootBranch(string projectName, string mainBranch, string gitRepositoryPath, bool createTeamProjectFolder) { throw new NotImplementedException(); } public int QueueGatedCheckinBuild(Uri value, string buildDefinitionName, string shelvesetName, string checkInTicket) { throw new NotImplementedException(); } public void DeleteShelveset(IWorkspace workspace, string shelvesetName) { throw new NotImplementedException(); } #endregion private class FakeVersionControlServer : IVersionControlServer { private readonly Script _script; public FakeVersionControlServer(Script script) { _script = script; } public IItem GetItem(int itemId, int changesetNumber) { var match = _script.Changesets.AsEnumerable().Reverse() .SkipWhile(cs => cs.Id > changesetNumber) .Select(cs => new { Changeset = cs, Change = cs.Changes.SingleOrDefault(change => change.ItemId == itemId) }) .First(x => x.Change != null); return new Change(this, match.Changeset, match.Change); } public IItem GetItem(string itemPath, int changesetNumber) { throw new NotImplementedException(); } public IItem[] GetItems(string itemPath, int changesetNumber, TfsRecursionType recursionType) { throw new NotImplementedException(); } public IEnumerable<IChangeset> QueryHistory(string path, int version, int deletionId, TfsRecursionType recursion, string user, int versionFrom, int versionTo, int maxCount, bool includeChanges, bool slotMode, bool includeDownloadInfo) { throw new NotImplementedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Int16 : IComparable, IConvertible, IFormattable, IComparable<short>, IEquatable<short>, ISpanFormattable { private readonly short m_value; // Do not rename (binary serialization) public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked((short)0x8000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int16, this method throws an ArgumentException. // public int CompareTo(object value) { if (value == null) { return 1; } if (value is short) { return m_value - ((short)value).m_value; } throw new ArgumentException(SR.Arg_MustBeInt16); } public int CompareTo(short value) { return m_value - value; } public override bool Equals(object obj) { if (!(obj is short)) { return false; } return m_value == ((short)obj).m_value; } [NonVersionable] public bool Equals(short obj) { return m_value == obj; } // Returns a HashCode for the Int16 public override int GetHashCode() { return ((int)((ushort)m_value) | (((int)m_value) << 16)); } public override string ToString() { return Number.FormatInt32(m_value, null, null); } public string ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider provider) { if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x0000FFFF); return Number.FormatUInt32(temp, format, provider); } return Number.FormatInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) { if (m_value < 0 && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x0000FFFF); return Number.TryFormatUInt32(temp, format, provider, destination, out charsWritten); } return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } public static short Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static short Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo); } public static short Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static short Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider)); } public static short Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static short Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_Int16, e); } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || (i > ushort.MaxValue)) { throw new OverflowException(SR.Overflow_Int16); } return (short)i; } if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Int16); return (short)i; } public static bool TryParse(string s, out short result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out short result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out short result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out short result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out short result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || i > ushort.MaxValue) { return false; } result = (short)i; return true; } if (i < MinValue || i > MaxValue) { return false; } result = (short)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int16; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return m_value; } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using UnityEditor; using UnityEditorInternal; using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Rotorz.ReorderableList; using System.IO; using System.Reflection; namespace Fungus { [CustomEditor (typeof(Block))] public class BlockEditor : Editor { protected class SetEventHandlerOperation { public Block block; public Type eventHandlerType; } protected class AddCommandOperation { public Block block; public Type commandType; public int index; } public static List<Action> actionList = new List<Action>(); protected Texture2D upIcon; protected Texture2D downIcon; protected Texture2D addIcon; protected Texture2D duplicateIcon; protected Texture2D deleteIcon; protected virtual void OnEnable() { upIcon = Resources.Load("Icons/up") as Texture2D; downIcon = Resources.Load("Icons/down") as Texture2D; addIcon = Resources.Load("Icons/add") as Texture2D; duplicateIcon = Resources.Load("Icons/duplicate") as Texture2D; deleteIcon = Resources.Load("Icons/delete") as Texture2D; } public virtual void DrawBlockName(Flowchart flowchart) { serializedObject.Update(); SerializedProperty blockNameProperty = serializedObject.FindProperty("blockName"); Rect blockLabelRect = new Rect(45, 5, 120, 16); EditorGUI.LabelField(blockLabelRect, new GUIContent("Block Name")); Rect blockNameRect = new Rect(45, 21, 180, 16); EditorGUI.PropertyField(blockNameRect, blockNameProperty, new GUIContent("")); // Ensure block name is unique for this Flowchart Block block = target as Block; string uniqueName = flowchart.GetUniqueBlockKey(blockNameProperty.stringValue, block); if (uniqueName != block.blockName) { blockNameProperty.stringValue = uniqueName; } serializedObject.ApplyModifiedProperties(); } public virtual void DrawBlockGUI(Flowchart flowchart) { serializedObject.Update(); // Execute any queued cut, copy, paste, etc. operations from the prevous GUI update // We need to defer applying these operations until the following update because // the ReorderableList control emits GUI errors if you clear the list in the same frame // as drawing the control (e.g. select all and then delete) if (Event.current.type == EventType.Layout) { foreach (Action action in actionList) { if (action != null) { action(); } } actionList.Clear(); } Block block = target as Block; SerializedProperty commandListProperty = serializedObject.FindProperty("commandList"); if (block == flowchart.selectedBlock) { SerializedProperty descriptionProp = serializedObject.FindProperty("description"); EditorGUILayout.PropertyField(descriptionProp); DrawEventHandlerGUI(flowchart); UpdateIndentLevels(block); // Make sure each command has a reference to its parent block foreach (Command command in block.commandList) { if (command == null) // Will be deleted from the list later on { continue; } command.parentBlock = block; } ReorderableListGUI.Title("Commands"); CommandListAdaptor adaptor = new CommandListAdaptor(commandListProperty, 0); adaptor.nodeRect = block.nodeRect; ReorderableListFlags flags = ReorderableListFlags.HideAddButton | ReorderableListFlags.HideRemoveButtons | ReorderableListFlags.DisableContextMenu; if (block.commandList.Count == 0) { EditorGUILayout.HelpBox("Press the + button below to add a command to the list.", MessageType.Info); } else { ReorderableListControl.DrawControlFromState(adaptor, null, flags); } // EventType.contextClick doesn't register since we moved the Block Editor to be inside // a GUI Area, no idea why. As a workaround we just check for right click instead. if (Event.current.type == EventType.mouseUp && Event.current.button == 1) { ShowContextMenu(); Event.current.Use(); } if (GUIUtility.keyboardControl == 0) //Only call keyboard shortcuts when not typing in a text field { Event e = Event.current; // Copy keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Copy") { if (flowchart.selectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Copy") { actionList.Add(Copy); e.Use(); } // Cut keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Cut") { if (flowchart.selectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Cut") { actionList.Add(Cut); e.Use(); } // Paste keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Paste") { CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); if (commandCopyBuffer.HasCommands()) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Paste") { actionList.Add(Paste); e.Use(); } // Duplicate keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Duplicate") { if (flowchart.selectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Duplicate") { actionList.Add(Copy); actionList.Add(Paste); e.Use(); } // Delete keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Delete") { if (flowchart.selectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Delete") { actionList.Add(Delete); e.Use(); } // SelectAll keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "SelectAll") { e.Use(); } if (e.type == EventType.ExecuteCommand && e.commandName == "SelectAll") { actionList.Add(SelectAll); e.Use(); } } } // Remove any null entries in the command list. // This can happen when a command class is deleted or renamed. for (int i = commandListProperty.arraySize - 1; i >= 0; --i) { SerializedProperty commandProperty = commandListProperty.GetArrayElementAtIndex(i); if (commandProperty.objectReferenceValue == null) { commandListProperty.DeleteArrayElementAtIndex(i); } } serializedObject.ApplyModifiedProperties(); } public virtual void DrawButtonToolbar() { GUILayout.BeginHorizontal(); // Previous Command if ((Event.current.type == EventType.keyDown) && (Event.current.keyCode == KeyCode.PageUp)) { SelectPrevious(); GUI.FocusControl("dummycontrol"); Event.current.Use(); } // Next Command if ((Event.current.type == EventType.keyDown) && (Event.current.keyCode == KeyCode.PageDown)) { SelectNext(); GUI.FocusControl("dummycontrol"); Event.current.Use(); } if (GUILayout.Button(upIcon)) { SelectPrevious(); } // Down Button if (GUILayout.Button(downIcon)) { SelectNext(); } GUILayout.FlexibleSpace(); // Add Button if (GUILayout.Button(addIcon)) { ShowCommandMenu(); } // Duplicate Button if (GUILayout.Button(duplicateIcon)) { Copy(); Paste(); } // Delete Button if (GUILayout.Button(deleteIcon)) { Delete(); } GUILayout.EndHorizontal(); } protected virtual void DrawEventHandlerGUI(Flowchart flowchart) { // Show available Event Handlers in a drop down list with type of current // event handler selected. List<System.Type> eventHandlerTypes = EditorExtensions.FindDerivedTypes(typeof(EventHandler)).ToList(); Block block = target as Block; System.Type currentType = null; if (block.eventHandler != null) { currentType = block.eventHandler.GetType(); } string currentHandlerName = "<None>"; if (currentType != null) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(currentType); if (info != null) { currentHandlerName = info.EventHandlerName; } } EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(new GUIContent("Execute On Event")); if (GUILayout.Button(new GUIContent(currentHandlerName), EditorStyles.popup)) { SetEventHandlerOperation noneOperation = new SetEventHandlerOperation(); noneOperation.block = block; noneOperation.eventHandlerType = null; GenericMenu eventHandlerMenu = new GenericMenu(); eventHandlerMenu.AddItem(new GUIContent("None"), false, OnSelectEventHandler, noneOperation); // Add event handlers with no category first foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info.Category.Length == 0) { SetEventHandlerOperation operation = new SetEventHandlerOperation(); operation.block = block; operation.eventHandlerType = type; eventHandlerMenu.AddItem(new GUIContent(info.EventHandlerName), false, OnSelectEventHandler, operation); } } // Add event handlers with a category afterwards foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info.Category.Length > 0) { SetEventHandlerOperation operation = new SetEventHandlerOperation(); operation.block = block; operation.eventHandlerType = type; string typeName = info.Category + "/" + info.EventHandlerName; eventHandlerMenu.AddItem(new GUIContent(typeName), false, OnSelectEventHandler, operation); } } eventHandlerMenu.ShowAsContext(); } EditorGUILayout.EndHorizontal(); if (block.eventHandler != null) { EventHandlerEditor eventHandlerEditor = Editor.CreateEditor(block.eventHandler) as EventHandlerEditor; if (eventHandlerEditor != null) { eventHandlerEditor.DrawInspectorGUI(); DestroyImmediate(eventHandlerEditor); } } } protected void OnSelectEventHandler(object obj) { SetEventHandlerOperation operation = obj as SetEventHandlerOperation; Block block = operation.block; System.Type selectedType = operation.eventHandlerType; if (block == null) { return; } Undo.RecordObject(block, "Set Event Handler"); if (block.eventHandler != null) { Undo.DestroyObjectImmediate(block.eventHandler); } if (selectedType != null) { EventHandler newHandler = Undo.AddComponent(block.gameObject, selectedType) as EventHandler; newHandler.parentBlock = block; block.eventHandler = newHandler; } // Because this is an async call, we need to force prefab instances to record changes PrefabUtility.RecordPrefabInstancePropertyModifications(block); } protected virtual void UpdateIndentLevels(Block block) { int indentLevel = 0; foreach(Command command in block.commandList) { if (command == null) { continue; } if (command.CloseBlock()) { indentLevel--; } // Negative indent level is not permitted indentLevel = Math.Max(indentLevel, 0); command.indentLevel = indentLevel; if (command.OpenBlock()) { indentLevel++; } } } static public void BlockField(SerializedProperty property, GUIContent label, GUIContent nullLabel, Flowchart flowchart) { if (flowchart == null) { return; } Block block = property.objectReferenceValue as Block; // Build dictionary of child blocks List<GUIContent> blockNames = new List<GUIContent>(); int selectedIndex = 0; blockNames.Add(nullLabel); Block[] blocks = flowchart.GetComponentsInChildren<Block>(true); for (int i = 0; i < blocks.Length; ++i) { blockNames.Add(new GUIContent(blocks[i].blockName)); if (block == blocks[i]) { selectedIndex = i + 1; } } selectedIndex = EditorGUILayout.Popup(label, selectedIndex, blockNames.ToArray()); if (selectedIndex == 0) { block = null; // Option 'None' } else { block = blocks[selectedIndex - 1]; } property.objectReferenceValue = block; } static public Block BlockField(Rect position, GUIContent nullLabel, Flowchart flowchart, Block block) { if (flowchart == null) { return null; } Block result = block; // Build dictionary of child blocks List<GUIContent> blockNames = new List<GUIContent>(); int selectedIndex = 0; blockNames.Add(nullLabel); Block[] blocks = flowchart.GetComponentsInChildren<Block>(); for (int i = 0; i < blocks.Length; ++i) { blockNames.Add(new GUIContent(blocks[i].name)); if (block == blocks[i]) { selectedIndex = i + 1; } } selectedIndex = EditorGUI.Popup(position, selectedIndex, blockNames.ToArray()); if (selectedIndex == 0) { result = null; // Option 'None' } else { result = blocks[selectedIndex - 1]; } return result; } // Compare delegate for sorting the list of command attributes protected static int CompareCommandAttributes(KeyValuePair<System.Type, CommandInfoAttribute> x, KeyValuePair<System.Type, CommandInfoAttribute> y) { int compare = (x.Value.Category.CompareTo(y.Value.Category)); if (compare == 0) { compare = (x.Value.CommandName.CompareTo(y.Value.CommandName)); } return compare; } [MenuItem("Tools/Fungus/Utilities/Export Reference Docs")] protected static void ExportReferenceDocs() { string path = EditorUtility.SaveFolderPanel("Export Reference Docs", "", ""); if(path.Length == 0) { return; } ExportCommandInfo(path); ExportEventHandlerInfo(path); FlowchartWindow.ShowNotification("Exported Reference Documentation"); } protected static void ExportCommandInfo(string path) { // Dump command info List<System.Type> menuTypes = EditorExtensions.FindDerivedTypes(typeof(Command)).ToList(); List<KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = GetFilteredCommandInfoAttribute(menuTypes); filteredAttributes.Sort( CompareCommandAttributes ); // Build list of command categories List<string> commandCategories = new List<string>(); foreach(var keyPair in filteredAttributes) { CommandInfoAttribute info = keyPair.Value; if (info.Category != "" && !commandCategories.Contains(info.Category)) { commandCategories.Add (info.Category); } } commandCategories.Sort(); // Output the commands in each category foreach (string category in commandCategories) { string markdown = ""; foreach(var keyPair in filteredAttributes) { CommandInfoAttribute info = keyPair.Value; if (info.Category == category || info.Category == "" && category == "Scripting") { markdown += "## " + info.CommandName + "\n"; markdown += info.HelpText + "\n"; markdown += GetPropertyInfo(keyPair.Key); } } string filePath = path + "/commands/" + category.ToLower() + "_commands.md"; Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.WriteAllText(filePath, markdown); } } protected static void ExportEventHandlerInfo(string path) { List<System.Type> eventHandlerTypes = EditorExtensions.FindDerivedTypes(typeof(EventHandler)).ToList(); List<string> eventHandlerCategories = new List<string>(); eventHandlerCategories.Add("Core"); foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info.Category != "" && !eventHandlerCategories.Contains(info.Category)) { eventHandlerCategories.Add(info.Category); } } eventHandlerCategories.Sort(); // Output the commands in each category foreach (string category in eventHandlerCategories) { string markdown = ""; foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info.Category == category || info.Category == "" && category == "Core") { markdown += "## " + info.EventHandlerName + "\n"; markdown += info.HelpText + "\n"; markdown += GetPropertyInfo(type); } } string filePath = path + "/event_handlers/" + category.ToLower() + "_events.md"; Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.WriteAllText(filePath, markdown); } } protected static string GetPropertyInfo(System.Type type) { string markdown = ""; foreach(FieldInfo field in type.GetFields() ) { TooltipAttribute attribute = (TooltipAttribute)Attribute.GetCustomAttribute(field, typeof(TooltipAttribute)); if (attribute == null ) { continue; } // Change field name to how it's displayed in the inspector string propertyName = Regex.Replace(field.Name, "(\\B[A-Z])", " $1"); if (propertyName.Length > 1) { propertyName = propertyName.Substring(0,1).ToUpper() + propertyName.Substring(1); } else { propertyName = propertyName.ToUpper(); } markdown += propertyName + " | " + field.FieldType + " | " + attribute.tooltip + "\n"; } if (markdown.Length > 0) { markdown = "\nProperty | Type | Description\n --- | --- | ---\n" + markdown + "\n"; } return markdown; } protected virtual void ShowCommandMenu() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); // Use index of last selected command in list, or end of list if nothing selected. int index = -1; foreach (Command command in flowchart.selectedCommands) { if (command.commandIndex + 1 > index) { index = command.commandIndex + 1; } } if (index == -1) { index = block.commandList.Count; } GenericMenu commandMenu = new GenericMenu(); // Build menu list List<System.Type> menuTypes = EditorExtensions.FindDerivedTypes(typeof(Command)).ToList(); List<KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = GetFilteredCommandInfoAttribute(menuTypes); filteredAttributes.Sort( CompareCommandAttributes ); foreach(var keyPair in filteredAttributes) { // Skip command type if the Flowchart doesn't support it if (!flowchart.IsCommandSupported(keyPair.Value)) { continue; } AddCommandOperation commandOperation = new AddCommandOperation(); commandOperation.block = block; commandOperation.commandType = keyPair.Key; commandOperation.index = index; GUIContent menuItem; if (keyPair.Value.Category == "") { menuItem = new GUIContent(keyPair.Value.CommandName); } else { menuItem = new GUIContent (keyPair.Value.Category + "/" + keyPair.Value.CommandName); } commandMenu.AddItem(menuItem, false, AddCommandCallback, commandOperation); } commandMenu.ShowAsContext(); } protected static List<KeyValuePair<System.Type,CommandInfoAttribute>> GetFilteredCommandInfoAttribute(List<System.Type> menuTypes) { Dictionary<string, KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = new Dictionary<string, KeyValuePair<System.Type, CommandInfoAttribute>>(); foreach (System.Type type in menuTypes) { object[] attributes = type.GetCustomAttributes(false); foreach (object obj in attributes) { CommandInfoAttribute infoAttr = obj as CommandInfoAttribute; if (infoAttr != null) { string dictionaryName = string.Format("{0}/{1}", infoAttr.Category, infoAttr.CommandName); int existingItemPriority = -1; if (filteredAttributes.ContainsKey(dictionaryName)) { existingItemPriority = filteredAttributes[dictionaryName].Value.Priority; } if (infoAttr.Priority > existingItemPriority) { KeyValuePair<System.Type, CommandInfoAttribute> keyValuePair = new KeyValuePair<System.Type, CommandInfoAttribute>(type, infoAttr); filteredAttributes[dictionaryName] = keyValuePair; } } } } return filteredAttributes.Values.ToList<KeyValuePair<System.Type,CommandInfoAttribute>>(); } protected static void AddCommandCallback(object obj) { AddCommandOperation commandOperation = obj as AddCommandOperation; Block block = commandOperation.block; if (block == null) { return; } Flowchart flowchart = block.GetFlowchart(); flowchart.ClearSelectedCommands(); Command newCommand = Undo.AddComponent(block.gameObject, commandOperation.commandType) as Command; block.GetFlowchart().AddSelectedCommand(newCommand); newCommand.parentBlock = block; newCommand.itemId = flowchart.NextItemId(); // Let command know it has just been added to the block newCommand.OnCommandAdded(block); Undo.RecordObject(block, "Set command type"); if (commandOperation.index < block.commandList.Count - 1) { block.commandList.Insert(commandOperation.index, newCommand); } else { block.commandList.Add(newCommand); } // Because this is an async call, we need to force prefab instances to record changes PrefabUtility.RecordPrefabInstancePropertyModifications(block); } public virtual void ShowContextMenu() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null) { return; } bool showCut = false; bool showCopy = false; bool showDelete = false; bool showPaste = false; if (flowchart.selectedCommands.Count > 0) { showCut = true; showCopy = true; showDelete = true; } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); if (commandCopyBuffer.HasCommands()) { showPaste = true; } GenericMenu commandMenu = new GenericMenu(); if (showCut) { commandMenu.AddItem (new GUIContent ("Cut"), false, Cut); } else { commandMenu.AddDisabledItem(new GUIContent ("Cut")); } if (showCopy) { commandMenu.AddItem (new GUIContent ("Copy"), false, Copy); } else { commandMenu.AddDisabledItem(new GUIContent ("Copy")); } if (showPaste) { commandMenu.AddItem (new GUIContent ("Paste"), false, Paste); } else { commandMenu.AddDisabledItem(new GUIContent ("Paste")); } if (showDelete) { commandMenu.AddItem (new GUIContent ("Delete"), false, Delete); } else { commandMenu.AddDisabledItem(new GUIContent ("Delete")); } commandMenu.AddSeparator(""); commandMenu.AddItem (new GUIContent ("Select All"), false, SelectAll); commandMenu.AddItem (new GUIContent ("Select None"), false, SelectNone); commandMenu.ShowAsContext(); } protected void SelectAll() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } flowchart.ClearSelectedCommands(); Undo.RecordObject(flowchart, "Select All"); foreach (Command command in flowchart.selectedBlock.commandList) { flowchart.AddSelectedCommand(command); } Repaint(); } protected void SelectNone() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } Undo.RecordObject(flowchart, "Select None"); flowchart.ClearSelectedCommands(); Repaint(); } protected void Cut() { Copy(); Delete(); } protected void Copy() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); commandCopyBuffer.Clear(); // Scan through all commands in execution order to see if each needs to be copied foreach (Command command in flowchart.selectedBlock.commandList) { if (flowchart.selectedCommands.Contains(command)) { System.Type type = command.GetType(); Command newCommand = Undo.AddComponent(commandCopyBuffer.gameObject, type) as Command; System.Reflection.FieldInfo[] fields = type.GetFields(); foreach (System.Reflection.FieldInfo field in fields) { field.SetValue(newCommand, field.GetValue(command)); } } } } protected void Paste() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); // Find where to paste commands in block (either at end or after last selected command) int pasteIndex = flowchart.selectedBlock.commandList.Count; if (flowchart.selectedCommands.Count > 0) { for (int i = 0; i < flowchart.selectedBlock.commandList.Count; ++i) { Command command = flowchart.selectedBlock.commandList[i]; foreach (Command selectedCommand in flowchart.selectedCommands) { if (command == selectedCommand) { pasteIndex = i + 1; } } } } foreach (Command command in commandCopyBuffer.GetCommands()) { // Using the Editor copy / paste functionality instead instead of reflection // because this does a deep copy of the command properties. if (ComponentUtility.CopyComponent(command)) { if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject)) { Command[] commands = flowchart.GetComponents<Command>(); Command pastedCommand = commands.Last<Command>(); if (pastedCommand != null) { pastedCommand.itemId = flowchart.NextItemId(); flowchart.selectedBlock.commandList.Insert(pasteIndex++, pastedCommand); } } // This stops the user pasting the command manually into another game object. ComponentUtility.CopyComponent(flowchart.transform); } } // Because this is an async call, we need to force prefab instances to record changes PrefabUtility.RecordPrefabInstancePropertyModifications(block); Repaint(); } protected void Delete() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } int lastSelectedIndex = 0; for (int i = flowchart.selectedBlock.commandList.Count - 1; i >= 0; --i) { Command command = flowchart.selectedBlock.commandList[i]; foreach (Command selectedCommand in flowchart.selectedCommands) { if (command == selectedCommand) { command.OnCommandRemoved(block); // Order of destruction is important here for undo to work Undo.DestroyObjectImmediate(command); Undo.RecordObject(flowchart.selectedBlock, "Delete"); flowchart.selectedBlock.commandList.RemoveAt(i); lastSelectedIndex = i; break; } } } Undo.RecordObject(flowchart, "Delete"); flowchart.ClearSelectedCommands(); if (lastSelectedIndex < flowchart.selectedBlock.commandList.Count) { Command nextCommand = flowchart.selectedBlock.commandList[lastSelectedIndex]; block.GetFlowchart().AddSelectedCommand(nextCommand); } Repaint(); } protected void SelectPrevious() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); int firstSelectedIndex = flowchart.selectedBlock.commandList.Count; bool firstSelectedCommandFound = false; if (flowchart.selectedCommands.Count > 0) { for (int i = 0; i < flowchart.selectedBlock.commandList.Count; i++) { Command commandInBlock = flowchart.selectedBlock.commandList[i]; foreach (Command selectedCommand in flowchart.selectedCommands) { if (commandInBlock == selectedCommand) { if (!firstSelectedCommandFound) { firstSelectedIndex = i; firstSelectedCommandFound = true; break; } } } if (firstSelectedCommandFound) { break; } } } if (firstSelectedIndex > 0) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(flowchart.selectedBlock.commandList[firstSelectedIndex-1]); } Repaint(); } protected void SelectNext() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); int lastSelectedIndex = -1; if (flowchart.selectedCommands.Count > 0) { for (int i = 0; i < flowchart.selectedBlock.commandList.Count; i++) { Command commandInBlock = flowchart.selectedBlock.commandList[i]; foreach (Command selectedCommand in flowchart.selectedCommands) { if (commandInBlock == selectedCommand) { lastSelectedIndex = i; } } } } if (lastSelectedIndex < flowchart.selectedBlock.commandList.Count-1) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(flowchart.selectedBlock.commandList[lastSelectedIndex+1]); } Repaint(); } } }
using Prism.Windows.AppModel; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Windows.ApplicationModel.Resources; using Windows.UI.Xaml; using Windows.UI.Xaml.Navigation; namespace Prism.Windows.Navigation { /// <summary> /// The <see cref="FrameNavigationService"/> interface is used for navigating across the pages of your Windows Store app. /// The <see cref="FrameNavigationService"/> class, uses a class that implements the <see cref="IFrameFacade"/> interface to provide page navigation. /// </summary> public class FrameNavigationService : INavigationService { private const string LastNavigationParameterKey = "LastNavigationParameter"; private const string LastNavigationPageKey = "LastNavigationPageKey"; private readonly IFrameFacade _frame; private readonly Func<string, Type> _navigationResolver; private readonly ISessionStateService _sessionStateService; /// <summary> /// Initializes a new instance of the <see cref="FrameNavigationService"/> class. /// </summary> /// <param name="frame">The frame.</param> /// <param name="navigationResolver">The navigation resolver.</param> /// <param name="sessionStateService">The session state service.</param> public FrameNavigationService(IFrameFacade frame, Func<string, Type> navigationResolver, ISessionStateService sessionStateService) { _frame = frame; _navigationResolver = navigationResolver; _sessionStateService = sessionStateService; if (frame != null) { _frame.NavigatingFrom += OnFrameNavigatingFrom; _frame.NavigatedTo += OnFrameNavigatedTo; } } /// <summary> /// Navigates to the page with the specified page token, passing the specified parameter. /// </summary> /// <param name="pageToken">The page token.</param> /// <param name="parameter">The parameter.</param> /// <returns>Returns <c>true</c> if the navigation succeeds: otherwise, <c>false</c>.</returns> public bool Navigate(string pageToken, object parameter) { Type pageType = _navigationResolver(pageToken); if (pageType == null) { var resourceLoader = ResourceLoader.GetForCurrentView(Constants.InfrastructureResourceMapId); var error = string.Format(CultureInfo.CurrentCulture, resourceLoader.GetString("FrameNavigationServiceUnableResolveMessage"), pageToken); throw new ArgumentException(error, nameof(pageToken)); } // Get the page type and parameter of the last navigation to check if we // are trying to navigate to the exact same page that we are currently on var lastNavigationParameter = _sessionStateService.SessionState.ContainsKey(LastNavigationParameterKey) ? _sessionStateService.SessionState[LastNavigationParameterKey] : null; var lastPageTypeFullName = _sessionStateService.SessionState.ContainsKey(LastNavigationPageKey) ? _sessionStateService.SessionState[LastNavigationPageKey] as string : string.Empty; if (lastPageTypeFullName != pageType.FullName || !AreEquals(lastNavigationParameter, parameter)) { return _frame.Navigate(pageType, parameter); } return false; } /// <summary> /// Goes to the previous page in the navigation stack. /// </summary> public void GoBack() { _frame.GoBack(); } /// <summary> /// Determines whether the navigation service can navigate to the previous page or not. /// </summary> /// <returns> /// <c>true</c> if the navigation service can go back; otherwise, <c>false</c>. /// </returns> public bool CanGoBack() { return _frame.CanGoBack; } /// <summary> /// Goes to the next page in the navigation stack. /// </summary> public void GoForward() { _frame.GoForward(); } /// <summary> /// Determines whether the navigation service can navigate to the next page or not. /// </summary> /// <returns> /// <c>true</c> if the navigation service can go forward; otherwise, <c>false</c>. /// </returns> public bool CanGoForward() { return _frame.CanGoForward(); } /// <summary> /// Clears the navigation history. /// </summary> public void ClearHistory() { _frame.ClearBackStack(); } /// <summary> /// Remove the first page of the backstack with optional pageToken and parameter /// </summary> /// <param name="pageToken"></param> /// <param name="parameter"></param> public void RemoveFirstPage(string pageToken = null, object parameter = null) { PageStackEntry page; if (pageToken != null) { var pageType = _navigationResolver(pageToken); if (parameter != null) { page = _frame.BackStack.FirstOrDefault(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter)); } else { page = _frame.BackStack.FirstOrDefault(x => x.SourcePageType == pageType); } } else { page = _frame.BackStack.FirstOrDefault(); } if (page != null) { _frame.RemoveBackStackEntry(page); } } /// <summary> /// Remove the last page of the backstack with optional pageToken and parameter /// </summary> /// <param name="pageToken"></param> /// <param name="parameter"></param> public void RemoveLastPage(string pageToken = null, object parameter = null) { PageStackEntry page; if (pageToken != null) { var pageType = _navigationResolver(pageToken); if (parameter != null) { page = _frame.BackStack.LastOrDefault(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter)); } else { page = _frame.BackStack.LastOrDefault(x => x.SourcePageType == pageType); } } else { page = _frame.BackStack.LastOrDefault(); } if (page != null) { _frame.RemoveBackStackEntry(page); } } /// <summary> /// Remove the all pages of the backstack with optional pageToken and parameter /// </summary> /// <param name="pageToken"></param> /// <param name="parameter"></param> public void RemoveAllPages(string pageToken = null, object parameter = null) { if (pageToken != null) { IEnumerable<PageStackEntry> pages; var pageType = _navigationResolver(pageToken); if (parameter != null) { pages = _frame.BackStack.Where(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter)); } else { pages = _frame.BackStack.Where(x => x.SourcePageType == pageType); } foreach (var page in pages) { _frame.RemoveBackStackEntry(page); } } else { _frame.ClearBackStack(); } } /// <summary> /// Restores the saved navigation. /// </summary> public void RestoreSavedNavigation() { NavigateToCurrentViewModel(new NavigatedToEventArgs() { NavigationMode = NavigationMode.Refresh, Parameter = _sessionStateService.SessionState[LastNavigationParameterKey] }); } /// <summary> /// Used for navigating away from the current view model due to a suspension event, in this way you can execute additional logic to handle suspensions. /// </summary> public void Suspending() { NavigateFromCurrentViewModel(new NavigatingFromEventArgs(), true); } /// <summary> /// This method is triggered after navigating to a view model. It is used to load the view model state that was saved previously. /// </summary> /// <param name="e">The <see cref="NavigatedToEventArgs"/> instance containing the event data.</param> private void NavigateToCurrentViewModel(NavigatedToEventArgs e) { var frameState = _sessionStateService.GetSessionStateForFrame(_frame); var viewModelKey = "ViewModel-" + _frame.BackStackDepth; if (e.NavigationMode == NavigationMode.New) { // Clear existing state for forward navigation when adding a new page/view model to the // navigation stack var nextViewModelKey = viewModelKey; int nextViewModelIndex = _frame.BackStackDepth; while (frameState.Remove(nextViewModelKey)) { nextViewModelIndex++; nextViewModelKey = "ViewModel-" + nextViewModelIndex; } } var newView = _frame.Content as FrameworkElement; if (newView == null) return; var newViewModel = newView.DataContext as INavigationAware; if (newViewModel != null) { Dictionary<string, object> viewModelState; if (frameState.ContainsKey(viewModelKey)) { viewModelState = frameState[viewModelKey] as Dictionary<string, object>; } else { viewModelState = new Dictionary<string, object>(); } newViewModel.OnNavigatedTo(e, viewModelState); frameState[viewModelKey] = viewModelState; } } /// <summary> /// Navigates away from the current viewmodel. /// </summary> /// <param name="e">The <see cref="NavigatingFromEventArgs"/> instance containing the event data.</param> /// <param name="suspending">True if it is navigating away from the viewmodel due to a suspend event.</param> private void NavigateFromCurrentViewModel(NavigatingFromEventArgs e, bool suspending) { var departingView = _frame.Content as FrameworkElement; if (departingView == null) return; var frameState = _sessionStateService.GetSessionStateForFrame(_frame); var departingViewModel = departingView.DataContext as INavigationAware; var viewModelKey = "ViewModel-" + _frame.BackStackDepth; if (departingViewModel != null) { var viewModelState = frameState.ContainsKey(viewModelKey) ? frameState[viewModelKey] as Dictionary<string, object> : null; departingViewModel.OnNavigatingFrom(e, viewModelState, suspending); } } /// <summary> /// Handles the Navigating event of the Frame control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="NavigatingFromEventArgs"/> instance containing the event data.</param> private void OnFrameNavigatingFrom(object sender, NavigatingFromEventArgs e) { NavigateFromCurrentViewModel(e, false); } /// <summary> /// Handles the Navigated event of the Frame control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="NavigatedToEventArgs"/> instance containing the event data.</param> private void OnFrameNavigatedTo(object sender, NavigatedToEventArgs e) { // Update the page type and parameter of the last navigation _sessionStateService.SessionState[LastNavigationPageKey] = _frame.Content.GetType().FullName; _sessionStateService.SessionState[LastNavigationParameterKey] = e.Parameter; NavigateToCurrentViewModel(e); } /// <summary> /// Returns <c>true</c> if both objects are equal. Two objects are equal if they are null or the same string object. /// </summary> /// <param name="obj1">First object to compare.</param> /// <param name="obj2">Second object to compare.</param> /// <returns>Returns <c>true</c> if both parameters are equal; otherwise, <c>false</c>.</returns> private static bool AreEquals(object obj1, object obj2) { if (obj1 != null) { return obj1.Equals(obj2); } return obj2 == null; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; #if !(NET20 || NET35 || PORTABLE) using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Tests.TestObjects.Organization; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Linq; using System.IO; using System.Collections; #if !(DNXCORE50) using System.Web.UI; #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JObjectTests : TestFixtureBase { #if !(NET35 || NET20 || PORTABLE40) [Test] public void EmbedJValueStringInNewJObject() { string s = null; var v = new JValue(s); dynamic o = JObject.FromObject(new { title = v }); string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); Assert.AreEqual(null, v.Value); Assert.IsNull((string)o.title); } #endif [Test] public void ReadWithSupportMultipleContent() { string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }"; IList<JObject> roles = new List<JObject>(); JsonTextReader reader = new JsonTextReader(new StringReader(json)); reader.SupportMultipleContent = true; while (true) { JObject role = (JObject)JToken.ReadFrom(reader); roles.Add(role); if (!reader.Read()) { break; } } Assert.AreEqual(2, roles.Count); Assert.AreEqual("Admin", (string)roles[0]["name"]); Assert.AreEqual("Publisher", (string)roles[1]["name"]); } [Test] public void JObjectWithComments() { string json = @"{ /*comment2*/ ""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/ ""ExpiryDate"": ""\/Date(1230422400000)\/"", ""Price"": 3.99, ""Sizes"": /*comment6*/ [ /*comment7*/ ""Small"", /*comment8*/ ""Medium"" /*comment9*/, /*comment10*/ ""Large"" /*comment11*/ ] /*comment12*/ } /*comment13*/"; JToken o = JToken.Parse(json); Assert.AreEqual("Apple", (string)o["Name"]); } [Test] public void WritePropertyWithNoValue() { var o = new JObject(); o.Add(new JProperty("novalue")); StringAssert.AreEqual(@"{ ""novalue"": null }", o.ToString()); } [Test] public void Keys() { var o = new JObject(); var d = (IDictionary<string, JToken>)o; Assert.AreEqual(0, d.Keys.Count); o["value"] = true; Assert.AreEqual(1, d.Keys.Count); } [Test] public void TryGetValue() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(false, o.TryGetValue("sdf", out t)); Assert.AreEqual(null, t); Assert.AreEqual(false, o.TryGetValue(null, out t)); Assert.AreEqual(null, t); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); } [Test] public void DictionaryItemShouldSet() { JObject o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(JValue.CreateNull(), t)); } [Test] public void Remove() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, o.Remove("sdf")); Assert.AreEqual(false, o.Remove(null)); Assert.AreEqual(true, o.Remove("PropertyNameValue")); Assert.AreEqual(0, o.Children().Count()); } [Test] public void GenericCollectionRemove() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.AreEqual(0, o.Children().Count()); } [Test] public void DuplicatePropertyNameShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null); }, "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericDictionaryAdd() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.AreEqual(2, o.Children().Count()); } [Test] public void GenericCollectionAdd() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(1, (int)o["PropertyNameValue"]); Assert.AreEqual(1, o.Children().Count()); } [Test] public void GenericCollectionClear() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.AreEqual(0, o.Children().Count()); Assert.AreEqual(null, p.Parent); } [Test] public void GenericCollectionContains() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.AreEqual(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.AreEqual(false, contains); } [Test] public void GenericDictionaryContains() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.AreEqual(true, contains); } [Test] public void GenericCollectionCopyTo() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.AreEqual(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[0]); Assert.AreEqual("PropertyNameValue", a[1].Key); Assert.AreEqual(1, (int)a[1].Value); Assert.AreEqual("PropertyNameValue2", a[2].Key); Assert.AreEqual(2, (int)a[2].Value); Assert.AreEqual("PropertyNameValue3", a[3].Key); Assert.AreEqual(3, (int)a[3].Value); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]); } [Test] public void GenericCollectionCopyToNullArrayShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); }, @"Value cannot be null. Parameter name: array"); } [Test] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); }, @"arrayIndex is less than 0. Parameter name: arrayIndex"); } [Test] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); }, @"arrayIndex is equal to or greater than the length of array."); } [Test] public void GenericCollectionCopyToInsufficientArrayCapacity() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); }, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } [Test] public void FromObjectRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); Assert.AreEqual("FirstNameValue", (string)o["first_name"]); Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type); Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]); Assert.AreEqual("LastNameValue", (string)o["last_name"]); } [Test] public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Raw, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.AreEqual("FirstNameValue", raw.FirstName); Assert.AreEqual("LastNameValue", raw.LastName); Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value); } [Test] public void Parse_ShouldThrowOnUnexpectedToken() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"[""prop""]"; JObject.Parse(json); }, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."); } [Test] public void ParseJavaScriptDate() { string json = @"[new Date(1207285200000)]"; JArray a = (JArray)JsonConvert.DeserializeObject(json); JValue v = (JValue)a[0]; Assert.AreEqual(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v); } [Test] public void GenericValueCast() { string json = @"{""foo"":true}"; JObject o = (JObject)JsonConvert.DeserializeObject(json); bool? value = o.Value<bool?>("foo"); Assert.AreEqual(true, value); json = @"{""foo"":null}"; o = (JObject)JsonConvert.DeserializeObject(json); value = o.Value<bool?>("foo"); Assert.AreEqual(null, value); } [Test] public void Blog() { ExceptionAssert.Throws<JsonReaderException>(() => { JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 4."); } [Test] public void RawChildValues() { JObject o = new JObject(); o["val1"] = new JRaw("1"); o["val2"] = new JRaw("1"); string json = o.ToString(); StringAssert.AreEqual(@"{ ""val1"": 1, ""val2"": 1 }", json); } [Test] public void Iterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); JToken t = o; int i = 1; foreach (JProperty property in t) { Assert.AreEqual("PropertyNameValue" + i, property.Name); Assert.AreEqual(i, (int)property.Value); i++; } } [Test] public void KeyValuePairIterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); int i = 1; foreach (KeyValuePair<string, JToken> pair in o) { Assert.AreEqual("PropertyNameValue" + i, pair.Key); Assert.AreEqual(i, (int)pair.Value); i++; } } [Test] public void WriteObjectNullStringValue() { string s = null; JValue v = new JValue(s); Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.String, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } [Test] public void Example() { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small Assert.AreEqual("Apple", name); Assert.AreEqual("Small", smallest); } [Test] public void DeserializeClassManually() { string jsonText = @"{ ""short"": { ""original"":""http://www.foo.com/"", ""short"":""krehqk"", ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Assert.AreEqual("http://www.foo.com/", shortie.Original); Assert.AreEqual("krehqk", shortie.Short); Assert.AreEqual(null, shortie.Shortened); Assert.AreEqual(0, shortie.Error.Code); Assert.AreEqual("No action taken", shortie.Error.ErrorMessage); } [Test] public void JObjectContainingHtml() { JObject o = new JObject(); o["rc"] = new JValue(200); o["m"] = new JValue(""); o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>"); StringAssert.AreEqual(@"{ ""rc"": 200, ""m"": """", ""o"": ""<div class='s1'>\r\n</div>"" }", o.ToString()); } [Test] public void ImplicitValueConversions() { JObject moss = new JObject(); moss["FirstName"] = new JValue("Maurice"); moss["LastName"] = new JValue("Moss"); moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30)); moss["Department"] = new JValue("IT"); moss["JobTitle"] = new JValue("Support"); StringAssert.AreEqual(@"{ ""FirstName"": ""Maurice"", ""LastName"": ""Moss"", ""BirthDate"": ""1977-12-30T00:00:00"", ""Department"": ""IT"", ""JobTitle"": ""Support"" }", moss.ToString()); JObject jen = new JObject(); jen["FirstName"] = "Jen"; jen["LastName"] = "Barber"; jen["BirthDate"] = new DateTime(1978, 3, 15); jen["Department"] = "IT"; jen["JobTitle"] = "Manager"; StringAssert.AreEqual(@"{ ""FirstName"": ""Jen"", ""LastName"": ""Barber"", ""BirthDate"": ""1978-03-15T00:00:00"", ""Department"": ""IT"", ""JobTitle"": ""Manager"" }", jen.ToString()); } [Test] public void ReplaceJPropertyWithJPropertyWithSameName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); IList l = o; Assert.AreEqual(p1, l[0]); Assert.AreEqual(p2, l[1]); JProperty p3 = new JProperty("Test1", "III"); p1.Replace(p3); Assert.AreEqual(null, p1.Parent); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); Assert.AreEqual(2, l.Count); Assert.AreEqual(2, o.Properties().Count()); JProperty p4 = new JProperty("Test4", "IV"); p2.Replace(p4); Assert.AreEqual(null, p2.Parent); Assert.AreEqual(l, p4.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p4, l[1]); } #if !(NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 [Test] public void PropertyChanging() { object changing = null; object changed = null; int changingCount = 0; int changedCount = 0; JObject o = new JObject(); o.PropertyChanging += (sender, args) => { JObject s = (JObject)sender; changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changingCount++; }; o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual(null, changing); Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value1", changing); Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changingCount); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual("value2", changing); Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changingCount); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changing); Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); } #endif [Test] public void PropertyChanged() { object changed = null; int changedCount = 0; JObject o = new JObject(); o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changedCount); } [Test] public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void IListIndexOf() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void IListClear() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void IListCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); object[] a = new object[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void IListAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void IListAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add("Bad!"); }, "Argument is not a JToken."); } [Test] public void IListAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.AreEqual(2, l.Count); l.Remove(p1); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); l.Remove(p2); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void IListRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void IListInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void IListIsReadOnly() { IList l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void IListIsFixedSize() { IList l = new JObject(); Assert.IsFalse(l.IsFixedSize); } [Test] public void IListSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void IListSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListSetItemInvalid() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l[0] = new JValue(true); }, @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListSyncRoot() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsNotNull(l.SyncRoot); } [Test] public void IListIsSynchronized() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsFalse(l.IsSynchronized); } [Test] public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void GenericListJTokenIndexOf() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void GenericListJTokenClear() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JToken[] a = new JToken[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void GenericListJTokenAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void GenericListJTokenAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // string is implicitly converted to JValue l.Add("Bad!"); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.IsFalse(l.Remove(p3)); Assert.AreEqual(2, l.Count); Assert.IsTrue(l.Remove(p1)); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); Assert.IsTrue(l.Remove(p2)); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void GenericListJTokenRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void GenericListJTokenIsReadOnly() { IList<JToken> l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void GenericListJTokenSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void GenericListJTokenSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void IBindingListSortDirection() { IBindingList l = new JObject(); Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection); } [Test] public void IBindingListSortProperty() { IBindingList l = new JObject(); Assert.AreEqual(null, l.SortProperty); } [Test] public void IBindingListSupportsChangeNotification() { IBindingList l = new JObject(); Assert.AreEqual(true, l.SupportsChangeNotification); } [Test] public void IBindingListSupportsSearching() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSearching); } [Test] public void IBindingListSupportsSorting() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSorting); } [Test] public void IBindingListAllowEdit() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowEdit); } [Test] public void IBindingListAllowNew() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowNew); } [Test] public void IBindingListAllowRemove() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowRemove); } [Test] public void IBindingListAddIndex() { IBindingList l = new JObject(); // do nothing l.AddIndex(null); } [Test] public void IBindingListApplySort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.ApplySort(null, ListSortDirection.Ascending); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveSort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.RemoveSort(); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveIndex() { IBindingList l = new JObject(); // do nothing l.RemoveIndex(null); } [Test] public void IBindingListFind() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.Find(null, null); }, "Specified method is not supported."); } [Test] public void IBindingListIsSorted() { IBindingList l = new JObject(); Assert.AreEqual(false, l.IsSorted); } [Test] public void IBindingListAddNew() { ExceptionAssert.Throws<JsonException>(() => { IBindingList l = new JObject(); l.AddNew(); }, "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'."); } [Test] public void IBindingListAddNewWithEvent() { JObject o = new JObject(); o._addingNew += (s, e) => e.NewObject = new JProperty("Property!"); IBindingList l = o; object newObject = l.AddNew(); Assert.IsNotNull(newObject); JProperty p = (JProperty)newObject; Assert.AreEqual("Property!", p.Name); Assert.AreEqual(o, p.Parent); } [Test] public void ITypedListGetListName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); Assert.AreEqual(string.Empty, l.GetListName(null)); } [Test] public void ITypedListGetItemProperties() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); Assert.IsNull(propertyDescriptors); } [Test] public void ListChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); ListChangedType? changedType = null; int? index = null; o.ListChanged += (s, a) => { changedType = a.ListChangedType; index = a.NewIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, ListChangedType.ItemAdded); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif #if !(NET20 || NET35 || PORTABLE40) [Test] public void CollectionChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); NotifyCollectionChangedAction? changedType = null; int? index = null; o._collectionChanged += (s, a) => { changedType = a.Action; index = a.NewStartingIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif [Test] public void GetGeocodeAddress() { string json = @"{ ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""id"": ""p1"", ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"", ""AddressDetails"": { ""Accuracy"" : 8, ""Country"" : { ""AdministrativeArea"" : { ""AdministrativeAreaName"" : ""IL"", ""SubAdministrativeArea"" : { ""Locality"" : { ""LocalityName"" : ""Rockford"", ""PostalCode"" : { ""PostalCodeNumber"" : ""61107"" }, ""Thoroughfare"" : { ""ThoroughfareName"" : ""435 N Mulford Rd"" } }, ""SubAdministrativeAreaName"" : ""Winnebago"" } }, ""CountryName"" : ""USA"", ""CountryNameCode"" : ""US"" } }, ""ExtendedData"": { ""LatLonBox"": { ""north"": 42.2753076, ""south"": 42.2690124, ""east"": -88.9964645, ""west"": -89.0027597 } }, ""Point"": { ""coordinates"": [ -88.9995886, 42.2721596, 0 ] } } ] }"; JObject o = JObject.Parse(json); string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"]; Assert.AreEqual("435 N Mulford Rd", searchAddress); } [Test] public void SetValueWithInvalidPropertyName() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o[0] = new JValue(3); }, "Set JObject values with invalid key value: 0. Object property name expected."); } [Test] public void SetValue() { object key = "TestKey"; JObject o = new JObject(); o[key] = new JValue(3); Assert.AreEqual(3, (int)o[key]); } [Test] public void ParseMultipleProperties() { string json = @"{ ""Name"": ""Name1"", ""Name"": ""Name2"" }"; JObject o = JObject.Parse(json); string value = (string)o["Name"]; Assert.AreEqual("Name2", value); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void WriteObjectNullDBNullValue() { DBNull dbNull = DBNull.Value; JValue v = new JValue(dbNull); Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } #endif [Test] public void InvalidValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o["responseData"]; }, "Can not convert Object to String."); } [Test] public void InvalidPropertyValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o.Property("responseData"); }, "Can not convert Object to String."); } [Test] public void ParseIncomplete() { ExceptionAssert.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6."); } [Test] public void LoadFromNestedObject() { string jsonText = @"{ ""short"": { ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JObject o = (JObject)JToken.ReadFrom(reader); Assert.IsNotNull(o); StringAssert.AreEqual(@"{ ""code"": 0, ""msg"": ""No action taken"" }", o.ToString(Formatting.Indented)); } [Test] public void LoadFromNestedObjectIncomplete() { ExceptionAssert.Throws<JsonReaderException>(() => { string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JToken.ReadFrom(reader); }, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 14."); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void GetProperties() { JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}"); ICustomTypeDescriptor descriptor = o; PropertyDescriptorCollection properties = descriptor.GetProperties(); Assert.AreEqual(4, properties.Count); PropertyDescriptor prop1 = properties[0]; Assert.AreEqual("prop1", prop1.Name); Assert.AreEqual(typeof(object), prop1.PropertyType); Assert.AreEqual(typeof(JObject), prop1.ComponentType); Assert.AreEqual(false, prop1.CanResetValue(o)); Assert.AreEqual(false, prop1.ShouldSerializeValue(o)); PropertyDescriptor prop2 = properties[1]; Assert.AreEqual("prop2", prop2.Name); Assert.AreEqual(typeof(object), prop2.PropertyType); Assert.AreEqual(typeof(JObject), prop2.ComponentType); Assert.AreEqual(false, prop2.CanResetValue(o)); Assert.AreEqual(false, prop2.ShouldSerializeValue(o)); PropertyDescriptor prop3 = properties[2]; Assert.AreEqual("prop3", prop3.Name); Assert.AreEqual(typeof(object), prop3.PropertyType); Assert.AreEqual(typeof(JObject), prop3.ComponentType); Assert.AreEqual(false, prop3.CanResetValue(o)); Assert.AreEqual(false, prop3.ShouldSerializeValue(o)); PropertyDescriptor prop4 = properties[3]; Assert.AreEqual("prop4", prop4.Name); Assert.AreEqual(typeof(object), prop4.PropertyType); Assert.AreEqual(typeof(JObject), prop4.ComponentType); Assert.AreEqual(false, prop4.CanResetValue(o)); Assert.AreEqual(false, prop4.ShouldSerializeValue(o)); } #endif [Test] public void ParseEmptyObjectWithComment() { JObject o = JObject.Parse("{ /* A Comment */ }"); Assert.AreEqual(0, o.Count); } [Test] public void FromObjectTimeSpan() { JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1)); Assert.AreEqual(v.Value, TimeSpan.FromDays(1)); Assert.AreEqual("1.00:00:00", v.ToString()); } [Test] public void FromObjectUri() { JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz")); Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz")); Assert.AreEqual("http://www.stuff.co.nz/", v.ToString()); } [Test] public void FromObjectGuid() { JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString()); } [Test] public void ParseAdditionalContent() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }, 987987"; JObject o = JObject.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 1."); } [Test] public void DeepEqualsIgnoreOrder() { JObject o1 = new JObject( new JProperty("null", null), new JProperty("integer", 1), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o1)); JObject o2 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o2)); JObject o3 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 2), new JProperty("array", new JArray(1, 2))); Assert.IsFalse(o1.DeepEquals(o3)); JObject o4 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(2, 1))); Assert.IsFalse(o1.DeepEquals(o4)); JObject o5 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1)); Assert.IsFalse(o1.DeepEquals(o5)); Assert.IsFalse(o1.DeepEquals(null)); } [Test] public void ToListOnEmptyObject() { JObject o = JObject.Parse(@"{}"); IList<JToken> l1 = o.ToList<JToken>(); Assert.AreEqual(0, l1.Count); IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(0, l2.Count); o = JObject.Parse(@"{'hi':null}"); l1 = o.ToList<JToken>(); Assert.AreEqual(1, l1.Count); l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(1, l2.Count); } [Test] public void EmptyObjectDeepEquals() { Assert.IsTrue(JToken.DeepEquals(new JObject(), new JObject())); JObject a = new JObject(); JObject b = new JObject(); b.Add("hi", "bye"); b.Remove("hi"); Assert.IsTrue(JToken.DeepEquals(a, b)); Assert.IsTrue(JToken.DeepEquals(b, a)); } [Test] public void GetValueBlogExample() { JObject o = JObject.Parse(@"{ 'name': 'Lower', 'NAME': 'Upper' }"); string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase); // Upper string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase); // Lower Assert.AreEqual("Upper", exactMatch); Assert.AreEqual("Lower", ignoreCase); } [Test] public void GetValue() { JObject a = new JObject(); a["Name"] = "Name!"; a["name"] = "name!"; a["title"] = "Title!"; Assert.AreEqual(null, a.GetValue("NAME", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue("NAME")); Assert.AreEqual(null, a.GetValue("TITLE")); Assert.AreEqual("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase)); Assert.AreEqual("name!", (string)a.GetValue("name", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null, StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null)); JToken v; Assert.IsFalse(a.TryGetValue("NAME", StringComparison.Ordinal, out v)); Assert.AreEqual(null, v); Assert.IsFalse(a.TryGetValue("NAME", out v)); Assert.IsFalse(a.TryGetValue("TITLE", out v)); Assert.IsTrue(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v)); Assert.AreEqual("Name!", (string)v); Assert.IsTrue(a.TryGetValue("name", StringComparison.Ordinal, out v)); Assert.AreEqual("name!", (string)v); Assert.IsFalse(a.TryGetValue(null, StringComparison.Ordinal, out v)); } public class FooJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var token = JToken.FromObject(value, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); if (token.Type == JTokenType.Object) { var o = (JObject)token; o.AddFirst(new JProperty("foo", "bar")); o.WriteTo(writer); } else { token.WriteTo(writer); } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException("This custom converter only supportes serialization and not deserialization."); } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return true; } } [Test] public void FromObjectInsideConverterWithCustomSerializer() { var p = new Person { Name = "Daniel Wertheim", }; var settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new FooJsonConverter() }, ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(p, settings); Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json); } [Test] public void Parse_NoComments() { string json = "{'prop':[1,2/*comment*/,3]}"; JObject o = JObject.Parse(json, new JsonLoadSettings { CommentHandling = CommentHandling.Ignore }); Assert.AreEqual(3, o["prop"].Count()); Assert.AreEqual(1, (int)o["prop"][0]); Assert.AreEqual(2, (int)o["prop"][1]); Assert.AreEqual(3, (int)o["prop"][2]); } [Test] public void Parse_ExcessiveContentJustComments() { string json = @"{'prop':[1,2,3]}/*comment*/ //Another comment."; JObject o = JObject.Parse(json); Assert.AreEqual(3, o["prop"].Count()); Assert.AreEqual(1, (int)o["prop"][0]); Assert.AreEqual(2, (int)o["prop"][1]); Assert.AreEqual(3, (int)o["prop"][2]); } [Test] public void Parse_ExcessiveContent() { string json = @"{'prop':[1,2,3]}/*comment*/ //Another comment. []"; ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(json), "Additional text encountered after finished reading JSON content: [. Path '', line 3, position 0."); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (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. // using System.IO; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using Xunit; namespace System.Data.Tests { public class DataTableReadXmlSchemaTest : RemoteExecutorTestBase { private DataSet CreateTestSet() { var ds = new DataSet(); ds.Tables.Add("Table1"); ds.Tables.Add("Table2"); ds.Tables[0].Columns.Add("Column1_1"); ds.Tables[0].Columns.Add("Column1_2"); ds.Tables[0].Columns.Add("Column1_3"); ds.Tables[1].Columns.Add("Column2_1"); ds.Tables[1].Columns.Add("Column2_2"); ds.Tables[1].Columns.Add("Column2_3"); ds.Tables[0].Rows.Add(new object[] { "ppp", "www", "xxx" }); ds.Relations.Add("Rel1", ds.Tables[0].Columns[2], ds.Tables[1].Columns[0]); return ds; } [Fact] public void SuspiciousDataSetElement() { string schema = @"<?xml version='1.0'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:attribute name='foo' type='xsd:string'/> <xsd:attribute name='bar' type='xsd:string'/> <xsd:complexType name='attRef'> <xsd:attribute name='att1' type='xsd:int'/> <xsd:attribute name='att2' type='xsd:string'/> </xsd:complexType> <xsd:element name='doc'> <xsd:complexType> <xsd:choice> <xsd:element name='elem' type='attRef'/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>"; var ds = new DataSet(); ds.Tables.Add(new DataTable("elem")); ds.Tables[0].ReadXmlSchema(new StringReader(schema)); DataSetAssertion.AssertDataTable("table", ds.Tables[0], "elem", 2, 0, 0, 0, 0, 0); } [Fact] public void UnusedComplexTypesIgnored() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'> <xs:element name='Root'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Orphan' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { var ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables.Add(new DataTable("unusedType")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataSetAssertion.AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // Here "unusedType" table is never imported. ds.Tables[1].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void IsDataSetAndTypeIgnored() { string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='{0}'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { // When explicit msdata:IsDataSet value is "false", then // treat as usual. string xs = string.Format(xsbase, "false"); var ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataSetAssertion.AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // Even if a global element uses a complexType, it will be // ignored if the element has msdata:IsDataSet='true' xs = string.Format(xsbase, "true"); ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void NestedReferenceNotAllowed() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='true'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> <xs:element name='Foo'> <xs:complexType> <xs:sequence> <xs:element ref='Root' /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { // DataSet element cannot be converted into a DataTable. // (i.e. cannot be referenced in any other elements) var ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void LocaleOnRootWithoutIsDataSet() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' msdata:Locale='ja-JP'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.Tables.Add("Root"); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("dt", dt, "Root", 2, 0, 0, 0, 0, 0); Assert.Equal("ja-JP", dt.Locale.Name); // DataTable's Locale comes from msdata:Locale DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("col2", dt.Columns[1], "Child", false, false, 0, 1, "Child", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void PrefixedTargetNS() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:x='urn:foo' targetNamespace='urn:foo' elementFormDefault='qualified'> <xs:element name='DS' msdata:IsDataSet='true'> <xs:complexType> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:key name='key'> <xs:selector xpath='./any/string_is_OK/x:R1'/> <xs:field xpath='x:Child2'/> </xs:key> <xs:keyref name='kref' refer='x:key'> <xs:selector xpath='.//x:R2'/> <xs:field xpath='x:Child2'/> </xs:keyref> </xs:element> <xs:element name='R3' type='x:RootType' /> <xs:complexType name='extracted'> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:element name='R1' type='x:RootType'> <xs:unique name='Rkey'> <xs:selector xpath='.//x:Child1'/> <xs:field xpath='.'/> </xs:unique> <xs:keyref name='Rkref' refer='x:Rkey'> <xs:selector xpath='.//x:Child2'/> <xs:field xpath='.'/> </xs:keyref> </xs:element> <xs:element name='R2' type='x:RootType'> </xs:element> <xs:complexType name='RootType'> <xs:choice> <xs:element name='Child1' type='xs:string'> </xs:element> <xs:element name='Child2' type='xs:string' /> </xs:choice> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:schema>"; // No prefixes on tables and columns var ds = new DataSet(); ds.Tables.Add(new DataTable("R3")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("R3", dt, "R3", 3, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); } private void ReadTest1Check(DataSet ds) { DataSetAssertion.AssertDataSet("dataset", ds, "NewDataSet", 2, 1); DataSetAssertion.AssertDataTable("tbl1", ds.Tables[0], "Table1", 3, 0, 0, 1, 1, 0); DataSetAssertion.AssertDataTable("tbl2", ds.Tables[1], "Table2", 3, 0, 1, 0, 1, 0); DataRelation rel = ds.Relations[0]; DataSetAssertion.AssertDataRelation("rel", rel, "Rel1", false, new string[] { "Column1_3" }, new string[] { "Column2_1" }, true, true); DataSetAssertion.AssertUniqueConstraint("uc", rel.ParentKeyConstraint, "Constraint1", false, new string[] { "Column1_3" }); DataSetAssertion.AssertForeignKeyConstraint("fk", rel.ChildKeyConstraint, "Rel1", AcceptRejectRule.None, Rule.Cascade, Rule.Cascade, new string[] { "Column2_1" }, new string[] { "Column1_3" }); } [Fact] public void TestSampleFileSimpleTables() { var ds = new DataSet(); ds.Tables.Add(new DataTable("foo")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='ct' /> <xs:complexType name='ct'> <xs:simpleContent> <xs:extension base='xs:integer'> <xs:attribute name='attr' /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>")); DataSetAssertion.AssertDataSet("005", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("attr", dt.Columns[0], "attr", true, false, 0, 1, "attr", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("text", dt.Columns[1], "foo_text", false, false, 0, 1, "foo_text", MappingType.SimpleContent, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); ds = new DataSet(); ds.Tables.Add(new DataTable("foo")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='st' /> <xs:complexType name='st'> <xs:attribute name='att1' /> <xs:attribute name='att2' type='xs:int' default='2' /> </xs:complexType> </xs:schema>")); DataSetAssertion.AssertDataSet("006", ds, "NewDataSet", 1, 0); dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("att1", dt.Columns["att1"], "att1", true, false, 0, 1, "att1", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, /*0*/-1, string.Empty, false, false); DataSetAssertion.AssertDataColumn("att2", dt.Columns["att2"], "att2", true, false, 0, 1, "att2", MappingType.Attribute, typeof(int), 2, string.Empty, -1, string.Empty, /*1*/-1, string.Empty, false, false); } [Fact] public void TestSampleFileComplexTables3() { var ds = new DataSet(); ds.Tables.Add(new DataTable("e")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<!-- Modified w3ctests attQ014.xsd --> <xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" targetNamespace=""http://xsdtesting"" xmlns:x=""http://xsdtesting""> <xsd:element name=""root""> <xsd:complexType> <xsd:sequence> <xsd:element name=""e""> <xsd:complexType> <xsd:simpleContent> <xsd:extension base=""xsd:decimal""> <xsd:attribute name=""a"" type=""xsd:string""/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>")); DataTable dt = ds.Tables[0]; DataSetAssertion.AssertDataTable("root", dt, "e", 2, 0, 0, 0, 0, 0); DataSetAssertion.AssertDataColumn("attr", dt.Columns[0], "a", true, false, 0, 1, "a", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); DataSetAssertion.AssertDataColumn("simple", dt.Columns[1], "e_text", false, false, 0, 1, "e_text", MappingType.SimpleContent, typeof(decimal), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void TestSampleFileXPath() { var ds = new DataSet(); ds.Tables.Add(new DataTable("Track")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <xs:schema targetNamespace=""http://neurosaudio.com/Tracks.xsd"" xmlns=""http://neurosaudio.com/Tracks.xsd"" xmlns:mstns=""http://neurosaudio.com/Tracks.xsd"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" elementFormDefault=""qualified"" id=""Tracks""> <xs:element name=""Tracks""> <xs:complexType> <xs:sequence> <xs:element name=""Track"" minOccurs=""0"" maxOccurs=""unbounded""> <xs:complexType> <xs:sequence> <xs:element name=""Title"" type=""xs:string"" /> <xs:element name=""Artist"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Album"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Performer"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Sequence"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Genre"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Comment"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Year"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Duration"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Path"" type=""xs:string"" /> <xs:element name=""DevicePath"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FileSize"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Source"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FlashStatus"" type=""xs:unsignedInt"" /> <xs:element name=""HDStatus"" type=""xs:unsignedInt"" /> </xs:sequence> <xs:attribute name=""ID"" type=""xs:unsignedInt"" msdata:AutoIncrement=""true"" msdata:AutoIncrementSeed=""1"" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:key name=""TrackPK"" msdata:PrimaryKey=""true""> <xs:selector xpath="".//mstns:Track"" /> <xs:field xpath=""@ID"" /> </xs:key> </xs:element> </xs:schema>")); } [Fact] public void ReadConstraints() { const string Schema = @"<?xml version=""1.0"" encoding=""utf-8""?> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:Locale=""en-US""> <xs:complexType> <xs:choice maxOccurs=""unbounded""> <xs:element name=""Table1""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""Table2""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name=""Constraint1""> <xs:selector xpath="".//Table1"" /> <xs:field xpath=""col1"" /> </xs:unique> <xs:keyref name=""fk1"" refer=""Constraint1"" msdata:ConstraintOnly=""true""> <xs:selector xpath="".//Table2"" /> <xs:field xpath=""col1"" /> </xs:keyref> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables.Add(new DataTable()); ds.Tables[0].ReadXmlSchema(new StringReader(Schema)); ds.Tables[1].ReadXmlSchema(new StringReader(Schema)); Assert.Equal(0, ds.Relations.Count); Assert.Equal(1, ds.Tables[0].Constraints.Count); Assert.Equal(0, ds.Tables[1].Constraints.Count); Assert.Equal("Constraint1", ds.Tables[0].Constraints[0].ConstraintName); } [Fact] public void XsdSchemaSerializationIgnoresLocale() { RemoteInvoke(() => { var serializer = new BinaryFormatter(); var table = new DataTable(); table.Columns.Add(new DataColumn("RowID", typeof(int)) { AutoIncrement = true, AutoIncrementSeed = -1, // These lines produce attributes within the schema portion of the underlying XML representation of the DataTable with the values "-1" and "-2". AutoIncrementStep = -2, }); table.Columns.Add("Value", typeof(string)); table.Rows.Add(1, "Test"); table.Rows.Add(2, "Data"); var buffer = new MemoryStream(); var savedCulture = CultureInfo.CurrentCulture; try { // Before serializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored. CultureInfo.CurrentCulture = new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }; serializer.Serialize(buffer, table); } finally { CultureInfo.CurrentCulture = savedCulture; } // The raw serialized data now contains an embedded XML schema. We need to verify that this embedded schema used "-1" for the numeric value // negative 1, instead of "()1" as indicated by the current culture. string rawSerializedData = System.Text.Encoding.ASCII.GetString(buffer.ToArray()); const string SchemaStartTag = "<xs:schema"; const string SchemaEndTag = "</xs:schema>"; int schemaStart = rawSerializedData.IndexOf(SchemaStartTag); int schemaEnd = rawSerializedData.IndexOf(SchemaEndTag); Assert.True(schemaStart >= 0); Assert.True(schemaEnd > schemaStart); Assert.True(rawSerializedData.IndexOf("<xs:schema", schemaStart + 1) < 0); schemaEnd += SchemaEndTag.Length; string rawSchemaXML = rawSerializedData.Substring( startIndex: schemaStart, length: schemaEnd - schemaStart); Assert.Contains(@"AutoIncrementSeed=""-1""", rawSchemaXML); Assert.Contains(@"AutoIncrementStep=""-2""", rawSchemaXML); Assert.DoesNotContain("()1", rawSchemaXML); Assert.DoesNotContain("()2", rawSchemaXML); }).Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework does not yet have the fix for this bug")] public void XsdSchemaDeserializationIgnoresLocale() { RemoteInvoke(() => { var serializer = new BinaryFormatter(); /* Test data generator: var table = new DataTable(); table.Columns.Add(new DataColumn("RowID", typeof(int)) { AutoIncrement = true, AutoIncrementSeed = -1, // These lines produce attributes within the schema portion of the underlying XML representation of the DataTable with the value "-1". AutoIncrementStep = -2, }); table.Columns.Add("Value", typeof(string)); table.Rows.Add(1, "Test"); table.Rows.Add(2, "Data"); var buffer = new MemoryStream(); serializer.Serialize(buffer, table); This test data (binary serializer output) embeds the following XML schema: <?xml version="1.0" encoding="utf-16"?> <xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="Table1"> <xs:complexType> <xs:sequence> <xs:element name="RowID" msdata:AutoIncrement="true" msdata:AutoIncrementSeed="-1" msdata:AutoIncrementStep="-2" type="xs:int" msdata:targetNamespace="" minOccurs="0" /> <xs:element name="Value" type="xs:string" msdata:targetNamespace="" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="tmpDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Table1" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded" /> </xs:complexType> </xs:element> </xs:schema> The bug being tested here is that the negative integer values in AutoInecrementSeed and AutoIncrementStep fail to parse because the deserialization code incorrectly uses the current culture instead of the invariant culture when parsing strings like "-1" and "-2". */ var buffer = new MemoryStream(new byte[] { 0,1,0,0,0,255,255,255,255,1,0,0,0,0,0,0,0,12,2,0,0,0,78,83,121,115,116,101,109,46,68,97,116,97,44,32,86,101,114,115,105,111,110,61,52,46,48,46,48,46,48,44,32,67,117, 108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,98,55,55,97,53,99,53,54,49,57,51,52,101,48,56,57,5,1,0, 0,0,21,83,121,115,116,101,109,46,68,97,116,97,46,68,97,116,97,84,97,98,108,101,3,0,0,0,25,68,97,116,97,84,97,98,108,101,46,82,101,109,111,116,105,110,103,86,101,114, 115,105,111,110,9,88,109,108,83,99,104,101,109,97,11,88,109,108,68,105,102,102,71,114,97,109,3,1,1,14,83,121,115,116,101,109,46,86,101,114,115,105,111,110,2,0,0,0,9, 3,0,0,0,6,4,0,0,0,177,6,60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,110,99,111,100,105,110,103,61,34,117,116,102,45,49,54,34,63,62,13, 10,60,120,115,58,115,99,104,101,109,97,32,120,109,108,110,115,61,34,34,32,120,109,108,110,115,58,120,115,61,34,104,116,116,112,58,47,47,119,119,119,46,119,51,46,111, 114,103,47,50,48,48,49,47,88,77,76,83,99,104,101,109,97,34,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105, 99,114,111,115,111,102,116,45,99,111,109,58,120,109,108,45,109,115,100,97,116,97,34,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34, 84,97,98,108,101,49,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,115,101,113,117,101,110, 99,101,62,13,10,32,32,32,32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,82,111,119,73,68,34,32,109,115,100,97,116,97,58,65,117,116, 111,73,110,99,114,101,109,101,110,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,101,101,100,61,34,45, 49,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,116,101,112,61,34,45,50,34,32,116,121,112,101,61,34,120,115,58,105,110,116,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,86,97,108,117,101,34,32,116,121,112,101,61,34,120,115,58,115,116,114,105,110,103,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,60,47,120,115,58,115,101,113,117,101,110,99,101,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47,120,115, 58,101,108,101,109,101,110,116,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,116,109,112,68,97,116,97,83,101,116,34,32,109,115,100, 97,116,97,58,73,115,68,97,116,97,83,101,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,77,97,105,110,68,97,116,97,84,97,98,108,101,61,34,84,97,98,108,101, 49,34,32,109,115,100,97,116,97,58,85,115,101,67,117,114,114,101,110,116,76,111,99,97,108,101,61,34,116,114,117,101,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109, 112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,99,104,111,105,99,101,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,109,97,120,79,99,99, 117,114,115,61,34,117,110,98,111,117,110,100,101,100,34,32,47,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47, 120,115,58,101,108,101,109,101,110,116,62,13,10,60,47,120,115,58,115,99,104,101,109,97,62,6,5,0,0,0,221,3,60,100,105,102,102,103,114,58,100,105,102,102,103,114,97, 109,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45,99,111,109,58,120,109,108, 45,109,115,100,97,116,97,34,32,120,109,108,110,115,58,100,105,102,102,103,114,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45, 99,111,109,58,120,109,108,45,100,105,102,102,103,114,97,109,45,118,49,34,62,13,10,32,32,60,116,109,112,68,97,116,97,83,101,116,62,13,10,32,32,32,32,60,84,97,98,108, 101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,49,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,48,34,32,100,105,102, 102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,49,60,47,82,111,119,73, 68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,84,101,115,116,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32,32,32,32,60, 84,97,98,108,101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,50,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,49,34,32, 100,105,102,102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,50,60,47, 82,111,119,73,68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,68,97,116,97,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32, 32,60,47,116,109,112,68,97,116,97,83,101,116,62,13,10,60,47,100,105,102,102,103,114,58,100,105,102,102,103,114,97,109,62,4,3,0,0,0,14,83,121,115,116,101,109,46,86, 101,114,115,105,111,110,4,0,0,0,6,95,77,97,106,111,114,6,95,77,105,110,111,114,6,95,66,117,105,108,100,9,95,82,101,118,105,115,105,111,110,0,0,0,0,8,8,8,8,2,0,0,0,0, 0,0,0,255,255,255,255,255,255,255,255,11 }); DataTable table; var savedCulture = CultureInfo.CurrentCulture; try { // Before deserializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored. // The bug this test is testing would cause "-1" to no longer be treated as a valid representation of the value -1, instead // only accepting the string "()1". CultureInfo.CurrentCulture = new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }; table = (DataTable)serializer.Deserialize(buffer); // BUG: System.Exception: "-1 is not a valid value for Int64." } } finally { CultureInfo.CurrentCulture = savedCulture; } DataColumn rowIDColumn = table.Columns["RowID"]; Assert.Equal(-1, rowIDColumn.AutoIncrementSeed); Assert.Equal(-2, rowIDColumn.AutoIncrementStep); }).Dispose(); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Exists to provide notification of when the full framework gets the bug fix, at which point the preceding test can be re-enabled")] public void XsdSchemaDeserializationOnFullFrameworkStillHasBug() { var serializer = new BinaryFormatter(); var buffer = new MemoryStream(new byte[] { 0,1,0,0,0,255,255,255,255,1,0,0,0,0,0,0,0,12,2,0,0,0,78,83,121,115,116,101,109,46,68,97,116,97,44,32,86,101,114,115,105,111,110,61,52,46,48,46,48,46,48,44,32,67,117, 108,116,117,114,101,61,110,101,117,116,114,97,108,44,32,80,117,98,108,105,99,75,101,121,84,111,107,101,110,61,98,55,55,97,53,99,53,54,49,57,51,52,101,48,56,57,5,1,0, 0,0,21,83,121,115,116,101,109,46,68,97,116,97,46,68,97,116,97,84,97,98,108,101,3,0,0,0,25,68,97,116,97,84,97,98,108,101,46,82,101,109,111,116,105,110,103,86,101,114, 115,105,111,110,9,88,109,108,83,99,104,101,109,97,11,88,109,108,68,105,102,102,71,114,97,109,3,1,1,14,83,121,115,116,101,109,46,86,101,114,115,105,111,110,2,0,0,0,9, 3,0,0,0,6,4,0,0,0,177,6,60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,110,99,111,100,105,110,103,61,34,117,116,102,45,49,54,34,63,62,13, 10,60,120,115,58,115,99,104,101,109,97,32,120,109,108,110,115,61,34,34,32,120,109,108,110,115,58,120,115,61,34,104,116,116,112,58,47,47,119,119,119,46,119,51,46,111, 114,103,47,50,48,48,49,47,88,77,76,83,99,104,101,109,97,34,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105, 99,114,111,115,111,102,116,45,99,111,109,58,120,109,108,45,109,115,100,97,116,97,34,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34, 84,97,98,108,101,49,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,115,101,113,117,101,110, 99,101,62,13,10,32,32,32,32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,82,111,119,73,68,34,32,109,115,100,97,116,97,58,65,117,116, 111,73,110,99,114,101,109,101,110,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,101,101,100,61,34,45, 49,34,32,109,115,100,97,116,97,58,65,117,116,111,73,110,99,114,101,109,101,110,116,83,116,101,112,61,34,45,50,34,32,116,121,112,101,61,34,120,115,58,105,110,116,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,86,97,108,117,101,34,32,116,121,112,101,61,34,120,115,58,115,116,114,105,110,103,34, 32,109,115,100,97,116,97,58,116,97,114,103,101,116,78,97,109,101,115,112,97,99,101,61,34,34,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,47,62,13,10,32,32,32, 32,32,32,60,47,120,115,58,115,101,113,117,101,110,99,101,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47,120,115, 58,101,108,101,109,101,110,116,62,13,10,32,32,60,120,115,58,101,108,101,109,101,110,116,32,110,97,109,101,61,34,116,109,112,68,97,116,97,83,101,116,34,32,109,115,100, 97,116,97,58,73,115,68,97,116,97,83,101,116,61,34,116,114,117,101,34,32,109,115,100,97,116,97,58,77,97,105,110,68,97,116,97,84,97,98,108,101,61,34,84,97,98,108,101, 49,34,32,109,115,100,97,116,97,58,85,115,101,67,117,114,114,101,110,116,76,111,99,97,108,101,61,34,116,114,117,101,34,62,13,10,32,32,32,32,60,120,115,58,99,111,109, 112,108,101,120,84,121,112,101,62,13,10,32,32,32,32,32,32,60,120,115,58,99,104,111,105,99,101,32,109,105,110,79,99,99,117,114,115,61,34,48,34,32,109,97,120,79,99,99, 117,114,115,61,34,117,110,98,111,117,110,100,101,100,34,32,47,62,13,10,32,32,32,32,60,47,120,115,58,99,111,109,112,108,101,120,84,121,112,101,62,13,10,32,32,60,47, 120,115,58,101,108,101,109,101,110,116,62,13,10,60,47,120,115,58,115,99,104,101,109,97,62,6,5,0,0,0,221,3,60,100,105,102,102,103,114,58,100,105,102,102,103,114,97, 109,32,120,109,108,110,115,58,109,115,100,97,116,97,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45,99,111,109,58,120,109,108, 45,109,115,100,97,116,97,34,32,120,109,108,110,115,58,100,105,102,102,103,114,61,34,117,114,110,58,115,99,104,101,109,97,115,45,109,105,99,114,111,115,111,102,116,45, 99,111,109,58,120,109,108,45,100,105,102,102,103,114,97,109,45,118,49,34,62,13,10,32,32,60,116,109,112,68,97,116,97,83,101,116,62,13,10,32,32,32,32,60,84,97,98,108, 101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,49,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,48,34,32,100,105,102, 102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,49,60,47,82,111,119,73, 68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,84,101,115,116,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32,32,32,32,60, 84,97,98,108,101,49,32,100,105,102,102,103,114,58,105,100,61,34,84,97,98,108,101,49,50,34,32,109,115,100,97,116,97,58,114,111,119,79,114,100,101,114,61,34,49,34,32, 100,105,102,102,103,114,58,104,97,115,67,104,97,110,103,101,115,61,34,105,110,115,101,114,116,101,100,34,62,13,10,32,32,32,32,32,32,60,82,111,119,73,68,62,50,60,47, 82,111,119,73,68,62,13,10,32,32,32,32,32,32,60,86,97,108,117,101,62,68,97,116,97,60,47,86,97,108,117,101,62,13,10,32,32,32,32,60,47,84,97,98,108,101,49,62,13,10,32, 32,60,47,116,109,112,68,97,116,97,83,101,116,62,13,10,60,47,100,105,102,102,103,114,58,100,105,102,102,103,114,97,109,62,4,3,0,0,0,14,83,121,115,116,101,109,46,86, 101,114,115,105,111,110,4,0,0,0,6,95,77,97,106,111,114,6,95,77,105,110,111,114,6,95,66,117,105,108,100,9,95,82,101,118,105,115,105,111,110,0,0,0,0,8,8,8,8,2,0,0,0,0, 0,0,0,255,255,255,255,255,255,255,255,11 }); Exception exception; CultureInfo savedCulture = CultureInfo.CurrentCulture; try { exception = Assert.Throws<TargetInvocationException>(() => { // Before deserializing, update the culture to use a weird negative number format. The bug this test is testing causes "-1" to no // longer be treated as a valid representation of the value -1, instead only accepting the string "()1". CultureInfo.CurrentCulture = new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }; serializer.Deserialize(buffer); // BUG: System.Exception: "-1 is not a valid value for Int64." }); } finally { CultureInfo.CurrentCulture = savedCulture; } Assert.IsAssignableFrom<FormatException>(exception.InnerException.InnerException); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class PublicKeyTests { private static PublicKey GetTestRsaKey() { using (var cert = new X509Certificate2(TestData.MsCertificate)) { return cert.PublicKey; } } private static PublicKey GetTestDsaKey() { using (var cert = new X509Certificate2(TestData.DssCer)) { return cert.PublicKey; } } [Fact] public static void TestOid_RSA() { PublicKey pk = GetTestRsaKey(); Assert.Equal("1.2.840.113549.1.1.1", pk.Oid.Value); } [Fact] public static void TestOid_DSA() { PublicKey pk = GetTestDsaKey(); Assert.Equal("1.2.840.10040.4.1", pk.Oid.Value); } [Fact] public static void TestEncodedKeyValue_RSA() { byte[] expectedPublicKey = ( "3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" + "407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" + "137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" + "b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" + "109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" + "2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" + "2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" + "84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" + "0b950005b14f6571c50203010001").HexToByteArray(); PublicKey pk = GetTestRsaKey(); Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData); } [Fact] public static void TestEncodedKeyValue_DSA() { byte[] expectedPublicKey = ( "028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371ebf07" + "bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a0707" + "ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638becca77" + "86312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3f2f8" + "bf0963").HexToByteArray(); PublicKey pk = GetTestDsaKey(); Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData); } [Fact] public static void TestEncodedParameters_RSA() { PublicKey pk = GetTestRsaKey(); // RSA has no key parameters, so the answer is always // DER:NULL (type 0x05, length 0x00) Assert.Equal(new byte[] { 0x05, 0x00 }, pk.EncodedParameters.RawData); } [Fact] public static void TestEncodedParameters_DSA() { byte[] expectedParameters = ( "3082011F02818100871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180" + "511D0DCEB8B979285708C800FC10CB15337A4AC1A48ED31394072015A7A6B525" + "986B49E5E1139737A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA4" + "1E8F0763AA613E29C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DF" + "B33C44D2F2DBE819021500E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D02" + "818100859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481" + "584413E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310F" + "EFD518AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0" + "DAFDA079BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D" + "05431D").HexToByteArray(); PublicKey pk = GetTestDsaKey(); Assert.Equal(expectedParameters, pk.EncodedParameters.RawData); } [Fact] public static void TestKey_RSA() { using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { RSA rsa = cert.GetRSAPublicKey(); RSAParameters rsaParameters = rsa.ExportParameters(false); byte[] expectedModulus = ( "E8AF5CA2200DF8287CBC057B7FADEEEB76AC28533F3ADB407DB38E33E6573FA5" + "51153454A5CFB48BA93FA837E12D50ED35164EEF4D7ADB137688B02CF0595CA9" + "EBE1D72975E41B85279BF3F82D9E41362B0B40FBBE3BBAB95C759316524BCA33" + "C537B0F3EB7EA8F541155C08651D2137F02CBA220B10B1109D772285847C4FB9" + "1B90B0F5A3FE8BF40C9A4EA0F5C90A21E2AAE3013647FD2F826A8103F5A935DC" + "94579DFB4BD40E82DB388F12FEE3D67A748864E162C4252E2AAE9D181F0E1EB6" + "C2AF24B40E50BCDE1C935C49A679B5B6DBCEF9707B280184B82A29CFBFA90505" + "E1E00F714DFDAD5C238329EBC7C54AC8E82784D37EC6430B950005B14F6571C5").HexToByteArray(); byte[] expectedExponent = new byte[] { 0x01, 0x00, 0x01 }; Assert.Equal(expectedModulus, rsaParameters.Modulus); Assert.Equal(expectedExponent, rsaParameters.Exponent); } } [Fact] public static void TestECDsaPublicKey() { byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(384, publicKey.KeySize); // The public key should be unable to sign. Assert.ThrowsAny<CryptographicException>(() => publicKey.SignData(helloBytes, HashAlgorithmName.SHA256)); } } [Fact] public static void TestECDsaPublicKey_ValidatesSignature() { // This signature was produced as the output of ECDsaCng.SignData with the same key // on .NET 4.6. Ensure it is verified here as a data compatibility test. // // Note that since ECDSA signatures contain randomness as an input, this value is unlikely // to be reproduced by another equivalent program. byte[] existingSignature = { // r: 0x7E, 0xD7, 0xEF, 0x46, 0x04, 0x92, 0x61, 0x27, 0x9F, 0xC9, 0x1B, 0x7B, 0x8A, 0x41, 0x6A, 0xC6, 0xCF, 0xD4, 0xD4, 0xD1, 0x73, 0x05, 0x1F, 0xF3, 0x75, 0xB2, 0x13, 0xFA, 0x82, 0x2B, 0x55, 0x11, 0xBE, 0x57, 0x4F, 0x20, 0x07, 0x24, 0xB7, 0xE5, 0x24, 0x44, 0x33, 0xC3, 0xB6, 0x8F, 0xBC, 0x1F, // s: 0x48, 0x57, 0x25, 0x39, 0xC0, 0x84, 0xB9, 0x0E, 0xDA, 0x32, 0x35, 0x16, 0xEF, 0xA0, 0xE2, 0x34, 0x35, 0x7E, 0x10, 0x38, 0xA5, 0xE4, 0x8B, 0xD3, 0xFC, 0xE7, 0x60, 0x25, 0x4E, 0x63, 0xF7, 0xDB, 0x7C, 0xBF, 0x18, 0xD6, 0xD3, 0x49, 0xD0, 0x93, 0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96, }; byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(384, publicKey.KeySize); bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256); Assert.True(isSignatureValid, "isSignatureValid"); } } [Fact] public static void TestECDsaPublicKey_NonSignatureCert() { using (var cert = new X509Certificate2(TestData.EccCert_KeyAgreement)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); // But, due to KeyUsage, it shouldn't be used for ECDSA. Assert.Null(publicKey); } } [Fact] public static void TestECDsa224PublicKey() { using (var cert = new X509Certificate2(TestData.ECDsa224Certificate)) { // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); ECDsa ecdsa; try { ecdsa = cert.GetECDsaPublicKey(); } catch (CryptographicException) { // Windows 7, Windows 8, CentOS. return; } // Other Unix using (ecdsa) { byte[] data = ByteUtils.AsciiBytes("Hello"); byte[] signature = ( // r "8ede5053d546d35c1aba829bca3ecf493eb7a73f751548bd4cf2ad10" + // s "5e3da9d359001a6be18e2b4e49205e5219f30a9daeb026159f41b9de").HexToByteArray(); Assert.True(ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA1)); } } } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void TestKey_ECDsaCng256() { TestKey_ECDsaCng(TestData.ECDsa256Certificate, TestData.ECDsaCng256PublicKey); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void TestKey_ECDsaCng384() { TestKey_ECDsaCng(TestData.ECDsa384Certificate, TestData.ECDsaCng384PublicKey); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void TestKey_ECDsaCng521() { TestKey_ECDsaCng(TestData.ECDsa521Certificate, TestData.ECDsaCng521PublicKey); } private static void TestKey_ECDsaCng(byte[] certBytes, TestData.ECDsaCngKeyValues expected) { #if !NETNATIVE using (X509Certificate2 cert = new X509Certificate2(certBytes)) { ECDsaCng e = (ECDsaCng)(cert.GetECDsaPublicKey()); CngKey k = e.Key; byte[] blob = k.Export(CngKeyBlobFormat.EccPublicBlob); using (BinaryReader br = new BinaryReader(new MemoryStream(blob))) { int magic = br.ReadInt32(); int cbKey = br.ReadInt32(); Assert.Equal(expected.QX.Length, cbKey); byte[] qx = br.ReadBytes(cbKey); byte[] qy = br.ReadBytes(cbKey); Assert.Equal<byte>(expected.QX, qx); Assert.Equal<byte>(expected.QY, qy); } } #endif //!NETNATIVE } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Xml.XPath; using System.Xml.Xsl.Qil; using System.Xml.Xsl.XPath; using System.Runtime.Versioning; namespace System.Xml.Xsl.Xslt { using TypeFactory = XmlQueryTypeFactory; #if DEBUG && FEATURE_COMPILED_XSL using XmlILTrace = System.Xml.Xsl.IlGen.XmlILTrace; #endif internal enum XslVersion { Version10 = 0, ForwardsCompatible = 1, Current = Version10, } // RootLevel is underdeveloped consept currently. I plane to move here more collections from Compiler. // Compiler is like a stylesheet in some sense. it has a lot of properties of stylesheet. Instead of // inhereting from Styleseet (or StylesheetLevel) I desided to aggregate special subclass of StylesheetLevel. // One more reason to for this design is to normolize apply-templates and apply-imports to one concept: // apply-templates is apply-imports(compiler.Root). // For now I don't create new files for these new classes to simplify integrations WebData <-> WebData_xsl internal class RootLevel : StylesheetLevel { public RootLevel(Stylesheet principal) { base.Imports = new Stylesheet[] { principal }; } } internal class Compiler { public XsltSettings Settings; public bool IsDebug; public string ScriptAssemblyPath; public int Version; // 0 - Auto; 1 - XSLT 1.0; 2 - XSLT 2.0 public string inputTypeAnnotations; // null - "unspecified"; "preserve"; "strip" public CompilerErrorCollection CompilerErrorColl; // Results of the compilation public int CurrentPrecedence = 0; // Decreases by 1 with each import public XslNode StartApplyTemplates; public RootLevel Root; public Scripts Scripts; public Output Output = new Output(); public List<VarPar> ExternalPars = new List<VarPar>(); public List<VarPar> GlobalVars = new List<VarPar>(); public List<WhitespaceRule> WhitespaceRules = new List<WhitespaceRule>(); public DecimalFormats DecimalFormats = new DecimalFormats(); public Keys Keys = new Keys(); public List<ProtoTemplate> AllTemplates = new List<ProtoTemplate>(); public Dictionary<QilName, VarPar> AllGlobalVarPars = new Dictionary<QilName, VarPar>(); public Dictionary<QilName, Template> NamedTemplates = new Dictionary<QilName, Template>(); public Dictionary<QilName, AttributeSet> AttributeSets = new Dictionary<QilName, AttributeSet>(); public Dictionary<string, NsAlias> NsAliases = new Dictionary<string, NsAlias>(); private Dictionary<string, int> _moduleOrder = new Dictionary<string, int>(); public Compiler(XsltSettings settings, bool debug, string scriptAssemblyPath) { Debug.Assert(CompilerErrorColl == null, "Compiler cannot be reused"); Settings = settings; IsDebug = settings.IncludeDebugInformation | debug; ScriptAssemblyPath = scriptAssemblyPath; CompilerErrorColl = new CompilerErrorCollection(); Scripts = new Scripts(this); } public CompilerErrorCollection Compile(object stylesheet, XmlResolver xmlResolver, out QilExpression qil) { Debug.Assert(stylesheet != null); Debug.Assert(Root == null, "Compiler cannot be reused"); new XsltLoader().Load(this, stylesheet, xmlResolver); qil = QilGenerator.CompileStylesheet(this); SortErrors(); return CompilerErrorColl; } public Stylesheet CreateStylesheet() { Stylesheet sheet = new Stylesheet(this, CurrentPrecedence); if (CurrentPrecedence-- == 0) { Root = new RootLevel(sheet); } return sheet; } public void AddModule(string baseUri) { if (!_moduleOrder.ContainsKey(baseUri)) { _moduleOrder[baseUri] = _moduleOrder.Count; } } public void ApplyNsAliases(ref string prefix, ref string nsUri) { NsAlias alias; if (NsAliases.TryGetValue(nsUri, out alias)) { nsUri = alias.ResultNsUri; prefix = alias.ResultPrefix; } } // Returns true in case of redefinition public bool SetNsAlias(string ssheetNsUri, string resultNsUri, string resultPrefix, int importPrecedence) { NsAlias oldNsAlias; if (NsAliases.TryGetValue(ssheetNsUri, out oldNsAlias)) { // Namespace alias for this stylesheet namespace URI has already been defined Debug.Assert(importPrecedence <= oldNsAlias.ImportPrecedence, "Stylesheets must be processed in the order of decreasing import precedence"); if (importPrecedence < oldNsAlias.ImportPrecedence || resultNsUri == oldNsAlias.ResultNsUri) { // Either the identical definition or lower precedence - ignore it return false; } // Recover by choosing the declaration that occurs later in the stylesheet } NsAliases[ssheetNsUri] = new NsAlias(resultNsUri, resultPrefix, importPrecedence); return oldNsAlias != null; } private void MergeWhitespaceRules(Stylesheet sheet) { for (int idx = 0; idx <= 2; idx++) { sheet.WhitespaceRules[idx].Reverse(); this.WhitespaceRules.AddRange(sheet.WhitespaceRules[idx]); } sheet.WhitespaceRules = null; } private void MergeAttributeSets(Stylesheet sheet) { foreach (QilName attSetName in sheet.AttributeSets.Keys) { AttributeSet attSet; if (!this.AttributeSets.TryGetValue(attSetName, out attSet)) { this.AttributeSets[attSetName] = sheet.AttributeSets[attSetName]; } else { // Lower import precedence - insert before all previous definitions attSet.MergeContent(sheet.AttributeSets[attSetName]); } } sheet.AttributeSets = null; } private void MergeGlobalVarPars(Stylesheet sheet) { foreach (VarPar var in sheet.GlobalVarPars) { Debug.Assert(var.NodeType == XslNodeType.Variable || var.NodeType == XslNodeType.Param); if (!AllGlobalVarPars.ContainsKey(var.Name)) { if (var.NodeType == XslNodeType.Variable) { GlobalVars.Add(var); } else { ExternalPars.Add(var); } AllGlobalVarPars[var.Name] = var; } } sheet.GlobalVarPars = null; } public void MergeWithStylesheet(Stylesheet sheet) { MergeWhitespaceRules(sheet); MergeAttributeSets(sheet); MergeGlobalVarPars(sheet); } public static string ConstructQName(string prefix, string localName) { if (prefix.Length == 0) { return localName; } else { return prefix + ':' + localName; } } public bool ParseQName(string qname, out string prefix, out string localName, IErrorHelper errorHelper) { Debug.Assert(qname != null); try { ValidateNames.ParseQNameThrow(qname, out prefix, out localName); return true; } catch (XmlException e) { errorHelper.ReportError(/*[XT_042]*/e.Message, null); prefix = PhantomNCName; localName = PhantomNCName; return false; } } public bool ParseNameTest(string nameTest, out string prefix, out string localName, IErrorHelper errorHelper) { Debug.Assert(nameTest != null); try { ValidateNames.ParseNameTestThrow(nameTest, out prefix, out localName); return true; } catch (XmlException e) { errorHelper.ReportError(/*[XT_043]*/e.Message, null); prefix = PhantomNCName; localName = PhantomNCName; return false; } } public void ValidatePiName(string name, IErrorHelper errorHelper) { Debug.Assert(name != null); try { ValidateNames.ValidateNameThrow( /*prefix:*/string.Empty, /*localName:*/name, /*ns:*/string.Empty, XPathNodeType.ProcessingInstruction, ValidateNames.Flags.AllExceptPrefixMapping ); } catch (XmlException e) { errorHelper.ReportError(/*[XT_044]*/e.Message, null); } } public readonly string PhantomNCName = "error"; private int _phantomNsCounter = 0; public string CreatePhantomNamespace() { // Prepend invalid XmlChar to ensure this name would not clash with any namespace name in the stylesheet return "\0namespace" + _phantomNsCounter++; } public bool IsPhantomNamespace(string namespaceName) { return namespaceName.Length > 0 && namespaceName[0] == '\0'; } public bool IsPhantomName(QilName qname) { string nsUri = qname.NamespaceUri; return nsUri.Length > 0 && nsUri[0] == '\0'; } // -------------------------------- Error Handling -------------------------------- private int ErrorCount { get { return CompilerErrorColl.Count; } set { Debug.Assert(value <= ErrorCount); for (int idx = ErrorCount - 1; idx >= value; idx--) { CompilerErrorColl.RemoveAt(idx); } } } private int _savedErrorCount = -1; public void EnterForwardsCompatible() { Debug.Assert(_savedErrorCount == -1, "Nested EnterForwardsCompatible calls"); _savedErrorCount = ErrorCount; } // Returns true if no errors were suppressed public bool ExitForwardsCompatible(bool fwdCompat) { Debug.Assert(_savedErrorCount != -1, "ExitForwardsCompatible without EnterForwardsCompatible"); if (fwdCompat && ErrorCount > _savedErrorCount) { ErrorCount = _savedErrorCount; Debug.Assert((_savedErrorCount = -1) < 0); return false; } Debug.Assert((_savedErrorCount = -1) < 0); return true; } public CompilerError CreateError(ISourceLineInfo lineInfo, string res, params string[] args) { AddModule(lineInfo.Uri); return new CompilerError( lineInfo.Uri, lineInfo.Start.Line, lineInfo.Start.Pos, /*errorNumber:*/string.Empty, /*errorText:*/XslTransformException.CreateMessage(res, args) ); } public void ReportError(ISourceLineInfo lineInfo, string res, params string[] args) { CompilerError error = CreateError(lineInfo, res, args); CompilerErrorColl.Add(error); } public void ReportWarning(ISourceLineInfo lineInfo, string res, params string[] args) { int warningLevel = 1; if (0 <= Settings.WarningLevel && Settings.WarningLevel < warningLevel) { // Ignore warning return; } CompilerError error = CreateError(lineInfo, res, args); if (Settings.TreatWarningsAsErrors) { error.ErrorText = XslTransformException.CreateMessage(SR.Xslt_WarningAsError, error.ErrorText); CompilerErrorColl.Add(error); } else { error.IsWarning = true; CompilerErrorColl.Add(error); } } private void SortErrors() { CompilerErrorCollection errorColl = this.CompilerErrorColl; if (errorColl.Count > 1) { CompilerError[] errors = new CompilerError[errorColl.Count]; errorColl.CopyTo(errors, 0); Array.Sort<CompilerError>(errors, new CompilerErrorComparer(_moduleOrder)); errorColl.Clear(); errorColl.AddRange(errors); } } private class CompilerErrorComparer : IComparer<CompilerError> { private Dictionary<string, int> _moduleOrder; public CompilerErrorComparer(Dictionary<string, int> moduleOrder) { _moduleOrder = moduleOrder; } public int Compare(CompilerError x, CompilerError y) { if ((object)x == (object)y) return 0; if (x == null) return -1; if (y == null) return 1; int result = _moduleOrder[x.FileName].CompareTo(_moduleOrder[y.FileName]); if (result != 0) return result; result = x.Line.CompareTo(y.Line); if (result != 0) return result; result = x.Column.CompareTo(y.Column); if (result != 0) return result; result = x.IsWarning.CompareTo(y.IsWarning); if (result != 0) return result; result = string.CompareOrdinal(x.ErrorNumber, y.ErrorNumber); if (result != 0) return result; return string.CompareOrdinal(x.ErrorText, y.ErrorText); } } } internal class Output { public XmlWriterSettings Settings; public string Version; public string Encoding; public XmlQualifiedName Method; // All the xsl:output elements occurring in a stylesheet are merged into a single effective xsl:output element. // We store the import precedence of each attribute value to catch redefinitions with the same import precedence. public const int NeverDeclaredPrec = int.MinValue; public int MethodPrec = NeverDeclaredPrec; public int VersionPrec = NeverDeclaredPrec; public int EncodingPrec = NeverDeclaredPrec; public int OmitXmlDeclarationPrec = NeverDeclaredPrec; public int StandalonePrec = NeverDeclaredPrec; public int DocTypePublicPrec = NeverDeclaredPrec; public int DocTypeSystemPrec = NeverDeclaredPrec; public int IndentPrec = NeverDeclaredPrec; public int MediaTypePrec = NeverDeclaredPrec; public Output() { Settings = new XmlWriterSettings(); Settings.OutputMethod = XmlOutputMethod.AutoDetect; Settings.AutoXmlDeclaration = true; Settings.ConformanceLevel = ConformanceLevel.Auto; Settings.MergeCDataSections = true; } } internal class DecimalFormats : KeyedCollection<XmlQualifiedName, DecimalFormatDecl> { protected override XmlQualifiedName GetKeyForItem(DecimalFormatDecl format) { return format.Name; } } internal class DecimalFormatDecl { public readonly XmlQualifiedName Name; public readonly string InfinitySymbol; public readonly string NanSymbol; public readonly char[] Characters; public static DecimalFormatDecl Default = new DecimalFormatDecl(new XmlQualifiedName(), "Infinity", "NaN", ".,%\u20300#;-"); public DecimalFormatDecl(XmlQualifiedName name, string infinitySymbol, string nanSymbol, string characters) { Debug.Assert(characters.Length == 8); this.Name = name; this.InfinitySymbol = infinitySymbol; this.NanSymbol = nanSymbol; this.Characters = characters.ToCharArray(); } } internal class NsAlias { public readonly string ResultNsUri; public readonly string ResultPrefix; public readonly int ImportPrecedence; public NsAlias(string resultNsUri, string resultPrefix, int importPrecedence) { this.ResultNsUri = resultNsUri; this.ResultPrefix = resultPrefix; this.ImportPrecedence = importPrecedence; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using FluentAssertions; using Its.Log.Instrumentation; using System.Linq; using System.Reactive.Disposables; using System.Threading.Tasks; using Microsoft.Its.Domain.Testing; using Microsoft.Its.Recipes; using NUnit.Framework; using Sample.Domain; using Sample.Domain.Ordering; using Sample.Domain.Ordering.Commands; namespace Microsoft.Its.Domain.Tests { [Category("Command scheduling")] [TestFixture] public class CommandSchedulingTests_EventSourced { private CompositeDisposable disposables; private Configuration configuration; private Guid customerAccountId; private IEventSourcedRepository<CustomerAccount> customerRepository; private IEventSourcedRepository<Order> orderRepository; [SetUp] public void SetUp() { disposables = new CompositeDisposable(); // disable authorization Command<Order>.AuthorizeDefault = (o, c) => true; Command<CustomerAccount>.AuthorizeDefault = (o, c) => true; disposables.Add(VirtualClock.Start()); customerAccountId = Any.Guid(); configuration = new Configuration() .UseInMemoryCommandScheduling() .UseInMemoryEventStore() .TraceScheduledCommands(); customerRepository = configuration.Repository<CustomerAccount>(); orderRepository = configuration.Repository<Order>(); customerRepository.Save(new CustomerAccount(customerAccountId) .Apply(new ChangeEmailAddress(Any.Email()))); disposables.Add(ConfigurationContext.Establish(configuration)); disposables.Add(configuration); } [TearDown] public void TearDown() { disposables.Dispose(); } [Test] public void When_a_command_is_scheduled_for_later_execution_then_a_CommandScheduled_event_is_added() { var order = CreateOrder(); order.Apply(new ShipOn(shipDate: Clock.Now().AddMonths(1).Date)); var lastEvent = order.PendingEvents.Last(); lastEvent.Should().BeOfType<CommandScheduled<Order>>(); lastEvent.As<CommandScheduled<Order>>().Command.Should().BeOfType<Ship>(); } [Test] public async Task CommandScheduler_executes_scheduled_commands_immediately_if_no_due_time_is_specified() { // arrange var repository = configuration.Repository<Order>(); var order = CreateOrder(); // act order.Apply(new ShipOn(Clock.Now().Subtract(TimeSpan.FromDays(2)))); await repository.Save(order); //assert order = await repository.GetLatest(order.Id); var lastEvent = order.Events().Last(); lastEvent.Should().BeOfType<Order.Shipped>(); } [Test] public async Task When_a_scheduled_command_fails_validation_then_a_failure_event_can_be_recorded_in_HandleScheduledCommandException_method() { // arrange var order = CreateOrder(customerAccountId: (await customerRepository.GetLatest(customerAccountId)).Id); // by the time Ship is applied, it will fail because of the cancellation order.Apply(new ShipOn(shipDate: Clock.Now().AddMonths(1).Date)); order.Apply(new Cancel()); await orderRepository.Save(order); // act VirtualClock.Current.AdvanceBy(TimeSpan.FromDays(32)); //assert order = await orderRepository.GetLatest(order.Id); var lastEvent = order.Events().Last(); lastEvent.Should().BeOfType<Order.ShipmentCancelled>(); } [Test] public async Task When_applying_a_scheduled_command_throws_then_further_command_scheduling_is_not_interrupted() { // arrange var order1 = CreateOrder(customerAccountId: customerAccountId) .Apply(new ShipOn(shipDate: Clock.Now().AddMonths(1).Date)) .Apply(new Cancel()); await orderRepository.Save(order1); var order2 = CreateOrder(customerAccountId: customerAccountId) .Apply(new ShipOn(shipDate: Clock.Now().AddMonths(1).Date)); await orderRepository.Save(order2); // act VirtualClock.Current.AdvanceBy(TimeSpan.FromDays(32)); // assert order1 = await orderRepository.GetLatest(order1.Id); var lastEvent = order1.Events().Last(); lastEvent.Should().BeOfType<Order.ShipmentCancelled>(); order2 = await orderRepository.GetLatest(order2.Id); lastEvent = order2.Events().Last(); lastEvent.Should().BeOfType<Order.Shipped>(); } [Test] public async Task A_command_can_be_scheduled_against_another_aggregate() { var order = new Order( new CreateOrder(Any.FullName()) { CustomerId = customerAccountId }) .Apply(new AddItem { ProductName = Any.Word(), Price = 12.99m }) .Apply(new Cancel()); await orderRepository.Save(order); var customerAccount = await customerRepository.GetLatest(customerAccountId); customerAccount.Events() .Last() .Should() .BeOfType<CustomerAccount.OrderCancelationConfirmationEmailSent>(); } [Test] public void If_Schedule_is_dependent_on_an_event_with_no_aggregate_id_then_it_throws() { var scheduler = configuration.CommandScheduler<CustomerAccount>(); Action schedule = () => scheduler.Schedule( Any.Guid(), new SendOrderConfirmationEmail(Any.Word()), deliveryDependsOn: new Order.Created { AggregateId = Guid.Empty, ETag = Any.Word() }).Wait(); schedule.ShouldThrow<ArgumentException>() .And .Message .Should() .Contain("An AggregateId must be set on the event on which the scheduled command depends."); } [Test] public async Task If_Schedule_is_dependent_on_an_event_with_no_ETag_then_it_sets_one() { var scheduler = new Configuration() .UseInMemoryEventStore() .UseInMemoryCommandScheduling() .CommandScheduler<CustomerAccount>(); var created = new Order.Created { AggregateId = Any.Guid(), ETag = null }; await scheduler.Schedule( Any.Guid(), new SendOrderConfirmationEmail(Any.Word()), deliveryDependsOn: created); created.ETag.Should().NotBeNullOrEmpty(); } [Test] public async Task Scheduled_commands_triggered_by_a_scheduled_command_are_idempotent() { var aggregate = new CommandSchedulerTestAggregate(); var repository = configuration.Repository<CommandSchedulerTestAggregate>(); await repository.Save(aggregate); var scheduler = configuration.CommandScheduler<CommandSchedulerTestAggregate>(); var dueTime = Clock.Now().AddMinutes(5); Console.WriteLine(new { dueTime }); var command = new CommandSchedulerTestAggregate.CommandThatSchedulesTwoOtherCommandsImmediately { NextCommand1AggregateId = aggregate.Id, NextCommand1 = new CommandSchedulerTestAggregate.Command { CommandId = Any.CamelCaseName() }, NextCommand2AggregateId = aggregate.Id, NextCommand2 = new CommandSchedulerTestAggregate.Command { CommandId = Any.CamelCaseName() } }; await scheduler.Schedule( aggregate.Id, dueTime: dueTime, command: command); await scheduler.Schedule( aggregate.Id, dueTime: dueTime, command: command); VirtualClock.Current.AdvanceBy(TimeSpan.FromDays(1)); aggregate = await repository.GetLatest(aggregate.Id); var events = aggregate.Events().ToArray(); events.Count().Should().Be(3); var succeededEvents = events.OfType<CommandSchedulerTestAggregate.CommandSucceeded>().ToArray(); succeededEvents.Count().Should().Be(2); succeededEvents.First().Command.CommandId .Should().NotBe(succeededEvents.Last().Command.CommandId); } [Test] public async Task Scatter_gather_produces_a_unique_etag_per_sent_command() { var repo = configuration.Repository<MarcoPoloPlayerWhoIsIt>(); var it = new MarcoPoloPlayerWhoIsIt(); await repo.Save(it); var numberOfPlayers = 6; var players = Enumerable.Range(1, numberOfPlayers) .Select(_ => new MarcoPoloPlayerWhoIsNotIt()); foreach (var player in players) { var joinGame = new MarcoPoloPlayerWhoIsNotIt.JoinGame { IdOfPlayerWhoIsIt = it.Id }; await player.ApplyAsync(joinGame).AndSave(); } await repo.Refresh(it); await it.ApplyAsync(new MarcoPoloPlayerWhoIsIt.SayMarco()).AndSave(); await repo.Refresh(it); it.Events() .OfType<MarcoPoloPlayerWhoIsIt.HeardPolo>() .Count() .Should() .Be(numberOfPlayers); } [Test] public async Task Multiple_scheduled_commands_having_the_some_causative_command_etag_have_repeatable_and_unique_etags() { var scheduled = new List<ICommand>(); configuration.AddToCommandSchedulerPipeline<MarcoPoloPlayerWhoIsIt>(async (cmd, next) => { scheduled.Add(cmd.Command); await next(cmd); }); configuration.AddToCommandSchedulerPipeline<MarcoPoloPlayerWhoIsNotIt>(async (cmd, next) => { scheduled.Add(cmd.Command); await next(cmd); }); var it = new MarcoPoloPlayerWhoIsIt() .Apply(new MarcoPoloPlayerWhoIsIt.AddPlayer { PlayerId = Any.Guid() }) .Apply(new MarcoPoloPlayerWhoIsIt.AddPlayer { PlayerId = Any.Guid() }); Console.WriteLine("[Saving]"); await configuration.Repository<MarcoPoloPlayerWhoIsIt>().Save(it); var sourceEtag = Any.Guid().ToString(); await it.ApplyAsync(new MarcoPoloPlayerWhoIsIt.KeepSayingMarcoOverAndOver { ETag = sourceEtag }); var firstPassEtags = scheduled.Select(c => c.ETag).ToArray(); Console.WriteLine(new { firstPassEtags }.ToLogString()); scheduled.Clear(); // revert the aggregate and do the same thing again it = await configuration.Repository<MarcoPoloPlayerWhoIsIt>().GetLatest(it.Id); await it.ApplyAsync(new MarcoPoloPlayerWhoIsIt.KeepSayingMarcoOverAndOver { ETag = sourceEtag }); Console.WriteLine("about to advance clock for the second time"); var secondPassEtags = scheduled.Select(c => c.ETag).ToArray(); Console.WriteLine(new { secondPassEtags }.ToLogString()); secondPassEtags.Should() .Equal(firstPassEtags); } [Test] public async Task Aggregates_can_schedule_commands_against_themselves_idempotently() { var it = new MarcoPoloPlayerWhoIsIt(); await configuration.Repository<MarcoPoloPlayerWhoIsIt>().Save(it); await it.ApplyAsync(new MarcoPoloPlayerWhoIsIt.KeepSayingMarcoOverAndOver()); VirtualClock.Current.AdvanceBy(TimeSpan.FromMinutes(1)); await configuration.Repository<MarcoPoloPlayerWhoIsIt>().Refresh(it); it.Events() .OfType<MarcoPoloPlayerWhoIsIt.SaidMarco>() .Count() .Should() .BeGreaterOrEqualTo(5); } public static Order CreateOrder( DateTimeOffset? deliveryBy = null, string customerName = null, Guid? orderId = null, Guid? customerAccountId = null) { return new Order( new CreateOrder(customerName ?? Any.FullName()) { AggregateId = orderId ?? Any.Guid(), CustomerId = customerAccountId ?? Any.Guid() }) .Apply(new AddItem { Price = 499.99m, ProductName = Any.Words(1, true).Single() }) .Apply(new SpecifyShippingInfo { Address = Any.Words(1, true).Single() + " St.", City = "Seattle", StateOrProvince = "WA", Country = "USA", DeliverBy = deliveryBy }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers; namespace Microsoft.AspNetCore.Mvc.ViewFeatures { /// <summary> /// A <see cref="HtmlHelper"/> for a specific model type. /// </summary> /// <typeparam name="TModel">The model type.</typeparam> public class HtmlHelper<TModel> : HtmlHelper, IHtmlHelper<TModel> { private readonly ModelExpressionProvider _modelExpressionProvider; /// <summary> /// Initializes a new instance of the <see cref="HtmlHelper{TModel}"/> class. /// </summary> public HtmlHelper( IHtmlGenerator htmlGenerator, ICompositeViewEngine viewEngine, IModelMetadataProvider metadataProvider, IViewBufferScope bufferScope, HtmlEncoder htmlEncoder, UrlEncoder urlEncoder, ModelExpressionProvider modelExpressionProvider) : base( htmlGenerator, viewEngine, metadataProvider, bufferScope, htmlEncoder, urlEncoder) { _modelExpressionProvider = modelExpressionProvider ?? throw new ArgumentNullException(nameof(modelExpressionProvider)); } /// <inheritdoc /> public new ViewDataDictionary<TModel> ViewData { get; private set; } /// <inheritdoc /> public override void Contextualize(ViewContext viewContext) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } if (viewContext.ViewData == null) { throw new ArgumentException(Resources.FormatPropertyOfTypeCannotBeNull( nameof(ViewContext.ViewData), typeof(ViewContext)), nameof(viewContext)); } ViewData = viewContext.ViewData as ViewDataDictionary<TModel>; if (ViewData == null) { // The view data that we have at this point might be of a more derived type than the one defined at compile time. // For example ViewDataDictionary<Derived> where our TModel is Base and Derived : Base. // This can't happen for regular views, but it can happen in razor pages if someone modified the model type through // the page application model. // In that case, we check if the type of the current view data, 'ViewDataDictionary<TRuntime>' is "covariant" with the // one defined at compile time 'ViewDataDictionary<TCompile>' var runtimeType = viewContext.ViewData.ModelMetadata.ModelType; if (runtimeType != null && typeof(TModel) != runtimeType && typeof(TModel).IsAssignableFrom(runtimeType)) { ViewData = new ViewDataDictionary<TModel>(viewContext.ViewData, viewContext.ViewData.Model); } } if (ViewData == null) { // viewContext may contain a base ViewDataDictionary instance. So complain about that type, not TModel. throw new ArgumentException(Resources.FormatArgumentPropertyUnexpectedType( nameof(ViewContext.ViewData), viewContext.ViewData.GetType().FullName, typeof(ViewDataDictionary<TModel>).FullName), nameof(viewContext)); } base.Contextualize(viewContext); } /// <inheritdoc /> public IHtmlContent CheckBoxFor( Expression<Func<TModel, bool>> expression, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateCheckBox( modelExpression.ModelExplorer, modelExpression.Name, isChecked: null, htmlAttributes: htmlAttributes); } /// <inheritdoc /> public IHtmlContent DropDownListFor<TResult>( Expression<Func<TModel, TResult>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateDropDown( modelExpression.ModelExplorer, modelExpression.Name, selectList, optionLabel, htmlAttributes); } /// <inheritdoc /> public IHtmlContent DisplayFor<TResult>( Expression<Func<TModel, TResult>> expression, string templateName, string htmlFieldName, object additionalViewData) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateDisplay( modelExpression.ModelExplorer, htmlFieldName ?? modelExpression.Name, templateName, additionalViewData); } /// <inheritdoc /> public string DisplayNameFor<TResult>(Expression<Func<TModel, TResult>> expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateDisplayName(modelExpression.ModelExplorer, modelExpression.Name); } /// <inheritdoc /> public string DisplayNameForInnerType<TModelItem, TResult>( Expression<Func<TModelItem, TResult>> expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = _modelExpressionProvider.CreateModelExpression( new ViewDataDictionary<TModelItem>(ViewData, model: null), expression); return GenerateDisplayName(modelExpression.ModelExplorer, modelExpression.Name); } /// <inheritdoc /> public string DisplayTextFor<TResult>(Expression<Func<TModel, TResult>> expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } return GenerateDisplayText(GetModelExplorer(expression)); } /// <inheritdoc /> public IHtmlContent EditorFor<TResult>( Expression<Func<TModel, TResult>> expression, string templateName, string htmlFieldName, object additionalViewData) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateEditor( modelExpression.ModelExplorer, htmlFieldName ?? modelExpression.Name, templateName, additionalViewData); } /// <inheritdoc /> public IHtmlContent HiddenFor<TResult>( Expression<Func<TModel, TResult>> expression, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateHidden( modelExpression.ModelExplorer, modelExpression.Name, modelExpression.Model, useViewData: false, htmlAttributes: htmlAttributes); } /// <inheritdoc /> public string IdFor<TResult>(Expression<Func<TModel, TResult>> expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } return GenerateId(GetExpressionName(expression)); } /// <inheritdoc /> public IHtmlContent LabelFor<TResult>( Expression<Func<TModel, TResult>> expression, string labelText, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateLabel(modelExpression.ModelExplorer, modelExpression.Name, labelText, htmlAttributes); } /// <inheritdoc /> public IHtmlContent ListBoxFor<TResult>( Expression<Func<TModel, TResult>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); var name = modelExpression.Name; return GenerateListBox(modelExpression.ModelExplorer, name, selectList, htmlAttributes); } /// <inheritdoc /> public string NameFor<TResult>(Expression<Func<TModel, TResult>> expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var expressionName = GetExpressionName(expression); return Name(expressionName); } /// <inheritdoc /> public IHtmlContent PasswordFor<TResult>( Expression<Func<TModel, TResult>> expression, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GeneratePassword( modelExpression.ModelExplorer, modelExpression.Name, value: null, htmlAttributes: htmlAttributes); } /// <inheritdoc /> public IHtmlContent RadioButtonFor<TResult>( Expression<Func<TModel, TResult>> expression, object value, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } var modelExpression = GetModelExpression(expression); return GenerateRadioButton( modelExpression.ModelExplorer, modelExpression.Name, value, isChecked: null, htmlAttributes: htmlAttributes); } /// <inheritdoc /> public IHtmlContent TextAreaFor<TResult>( Expression<Func<TModel, TResult>> expression, int rows, int columns, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateTextArea(modelExpression.ModelExplorer, modelExpression.Name, rows, columns, htmlAttributes); } /// <inheritdoc /> public IHtmlContent TextBoxFor<TResult>( Expression<Func<TModel, TResult>> expression, string format, object htmlAttributes) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateTextBox( modelExpression.ModelExplorer, modelExpression.Name, modelExpression.Model, format, htmlAttributes); } private ModelExpression GetModelExpression<TResult>(Expression<Func<TModel, TResult>> expression) { return _modelExpressionProvider.CreateModelExpression(ViewData, expression); } /// <summary> /// Gets the name for <paramref name="expression"/>. /// </summary> /// <param name="expression">The expression.</param> /// <returns>The expression name.</returns> protected string GetExpressionName<TResult>(Expression<Func<TModel, TResult>> expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } return _modelExpressionProvider.GetExpressionText(expression); } /// <summary> /// Gets the <see cref="ModelExplorer"/> for <paramref name="expression"/>. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="ModelExplorer"/>.</returns> protected ModelExplorer GetModelExplorer<TResult>(Expression<Func<TModel, TResult>> expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return modelExpression.ModelExplorer; } /// <inheritdoc /> public IHtmlContent ValidationMessageFor<TResult>( Expression<Func<TModel, TResult>> expression, string message, object htmlAttributes, string tag) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateValidationMessage( modelExpression.ModelExplorer, modelExpression.Name, message, tag, htmlAttributes); } /// <inheritdoc /> public string ValueFor<TResult>(Expression<Func<TModel, TResult>> expression, string format) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var modelExpression = GetModelExpression(expression); return GenerateValue(modelExpression.Name, modelExpression.Model, format, useViewData: false); } } }
// <copyright file="Control.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2015 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using MathNet.Numerics.Providers.LinearAlgebra; using System; using System.Threading.Tasks; namespace MathNet.Numerics { /// <summary> /// Sets parameters for the library. /// </summary> public static class Control { const string EnvVarLAProvider = "MathNetNumericsLAProvider"; static int _maxDegreeOfParallelism; static int _blockSize; static int _parallelizeOrder; static int _parallelizeElements; static ILinearAlgebraProvider _linearAlgebraProvider; static Control() { ConfigureAuto(); } public static void ConfigureAuto() { // Random Numbers & Distributions CheckDistributionParameters = true; // Parallelization & Threading ThreadSafeRandomNumberGenerators = true; _maxDegreeOfParallelism = Environment.ProcessorCount; _blockSize = 512; _parallelizeOrder = 64; _parallelizeElements = 300; TaskScheduler = TaskScheduler.Default; // Linear Algebra Provider #if PORTABLE LinearAlgebraProvider = new ManagedLinearAlgebraProvider(); #else try { var value = Environment.GetEnvironmentVariable(EnvVarLAProvider); switch (value != null ? value.ToUpperInvariant() : string.Empty) { #if NATIVE case "MKL": UseNativeMKL(); break; case "CUDA": UseNativeCUDA(); break; case "OPENBLAS": UseNativeOpenBLAS(); break; #endif default: if (!TryUseNative()) { UseManaged(); } break; } } catch { // We don't care about any failures here at all (because "auto") UseManaged(); } #endif } public static void UseManaged() { LinearAlgebraProvider = new ManagedLinearAlgebraProvider(); } #if NATIVE /// <summary> /// Use the Intel MKL native provider for linear algebra. /// Throws if it is not available or failed to initialize, in which case the previous provider is still active. /// </summary> public static void UseNativeMKL() { LinearAlgebraProvider = new Providers.LinearAlgebra.Mkl.MklLinearAlgebraProvider(); } /// <summary> /// Use the Intel MKL native provider for linear algebra, with the specified configuration parameters. /// Throws if it is not available or failed to initialize, in which case the previous provider is still active. /// </summary> [CLSCompliant(false)] public static void UseNativeMKL( Providers.LinearAlgebra.Mkl.MklConsistency consistency = Providers.LinearAlgebra.Mkl.MklConsistency.Auto, Providers.LinearAlgebra.Mkl.MklPrecision precision = Providers.LinearAlgebra.Mkl.MklPrecision.Double, Providers.LinearAlgebra.Mkl.MklAccuracy accuracy = Providers.LinearAlgebra.Mkl.MklAccuracy.High) { LinearAlgebraProvider = new Providers.LinearAlgebra.Mkl.MklLinearAlgebraProvider(consistency, precision, accuracy); } /// <summary> /// Try to use the Intel MKL native provider for linear algebra. /// </summary> /// <returns> /// True if the provider was found and initialized successfully. /// False if it failed and the previous provider is still active. /// </returns> public static bool TryUseNativeMKL() { return Try(UseNativeMKL); } /// <summary> /// Use the Nvidia CUDA native provider for linear algebra. /// Throws if it is not available or failed to initialize, in which case the previous provider is still active. /// </summary> public static void UseNativeCUDA() { LinearAlgebraProvider = new Providers.LinearAlgebra.Cuda.CudaLinearAlgebraProvider(); } /// <summary> /// Try to use the Nvidia CUDA native provider for linear algebra. /// </summary> /// <returns> /// True if the provider was found and initialized successfully. /// False if it failed and the previous provider is still active. /// </returns> public static bool TryUseNativeCUDA() { return Try(UseNativeCUDA); } /// <summary> /// Use the OpenBLAS native provider for linear algebra. /// Throws if it is not available or failed to initialize, in which case the previous provider is still active. /// </summary> public static void UseNativeOpenBLAS() { LinearAlgebraProvider = new Providers.LinearAlgebra.OpenBlas.OpenBlasLinearAlgebraProvider(); } /// <summary> /// Try to use the OpenBLAS native provider for linear algebra. /// </summary> /// <returns> /// True if the provider was found and initialized successfully. /// False if it failed and the previous provider is still active. /// </returns> public static bool TryUseNativeOpenBLAS() { return Try(UseNativeOpenBLAS); } /// <summary> /// Try to use any available native provider in an undefined order. /// </summary> /// <returns> /// True if one of the native providers was found and successfully initialized. /// False if it failed and the previous provider is still active. /// </returns> public static bool TryUseNative() { return TryUseNativeCUDA() || TryUseNativeMKL() || TryUseNativeOpenBLAS(); } static bool Try(Action action) { try { action(); return true; } catch { // intentionally swallow exceptions here - use the non-try variants if you're interested in why return false; } } #endif public static void UseSingleThread() { _maxDegreeOfParallelism = 1; ThreadSafeRandomNumberGenerators = false; LinearAlgebraProvider.InitializeVerify(); } public static void UseMultiThreading() { _maxDegreeOfParallelism = Environment.ProcessorCount; ThreadSafeRandomNumberGenerators = true; LinearAlgebraProvider.InitializeVerify(); } /// <summary> /// Gets or sets a value indicating whether the distribution classes check validate each parameter. /// For the multivariate distributions this could involve an expensive matrix factorization. /// The default setting of this property is <c>true</c>. /// </summary> public static bool CheckDistributionParameters { get; set; } /// <summary> /// Gets or sets a value indicating whether to use thread safe random number generators (RNG). /// Thread safe RNG about two and half time slower than non-thread safe RNG. /// </summary> /// <value> /// <c>true</c> to use thread safe random number generators ; otherwise, <c>false</c>. /// </value> public static bool ThreadSafeRandomNumberGenerators { get; set; } /// <summary> /// Optional path to try to load native provider binaries from. /// </summary> public static string NativeProviderPath { get; set; } /// <summary> /// Gets or sets the linear algebra provider. Consider to use UseNativeMKL or UseManaged instead. /// </summary> /// <value>The linear algebra provider.</value> public static ILinearAlgebraProvider LinearAlgebraProvider { get { return _linearAlgebraProvider; } set { value.InitializeVerify(); // only actually set if verification did not throw _linearAlgebraProvider = value; } } /// <summary> /// Gets or sets a value indicating how many parallel worker threads shall be used /// when parallelization is applicable. /// </summary> /// <remarks>Default to the number of processor cores, must be between 1 and 1024 (inclusive).</remarks> public static int MaxDegreeOfParallelism { get { return _maxDegreeOfParallelism; } set { _maxDegreeOfParallelism = Math.Max(1, Math.Min(1024, value)); // Reinitialize providers: LinearAlgebraProvider.InitializeVerify(); } } /// <summary> /// Gets or sets the TaskScheduler used to schedule the worker tasks. /// </summary> public static TaskScheduler TaskScheduler { get; set; } /// <summary> /// Gets or sets the the block size to use for /// the native linear algebra provider. /// </summary> /// <value>The block size. Default 512, must be at least 32.</value> public static int BlockSize { get { return _blockSize; } set { _blockSize = Math.Max(32, value); } } /// <summary> /// Gets or sets the order of the matrix when linear algebra provider /// must calculate multiply in parallel threads. /// </summary> /// <value>The order. Default 64, must be at least 3.</value> internal static int ParallelizeOrder { get { return _parallelizeOrder; } set { _parallelizeOrder = Math.Max(3, value); } } /// <summary> /// Gets or sets the number of elements a vector or matrix /// must contain before we multiply threads. /// </summary> /// <value>Number of elements. Default 300, must be at least 3.</value> internal static int ParallelizeElements { get { return _parallelizeElements; } set { _parallelizeElements = Math.Max(3, value); } } } }
// 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.ServiceBus { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// TopicsOperations operations. /// </summary> public partial interface ITopicsOperations { /// <summary> /// Gets all the topics in a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639388.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<TopicResource>>> ListAllWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a topic in the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639409.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a topic resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<TopicResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, TopicCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a topic from the specified namespace and resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639404.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a description for the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639399.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<TopicResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets authorization rules for a topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates an authorizatio rule for the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720678.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the specified authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720676.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a topic authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the primary and secondary connection strings for the topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720677.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates primary or secondary connection strings for the topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720679.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, RegenerateKeysParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the topics in a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639388.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<TopicResource>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets authorization rules for a topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt720681.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using AutomationSystemAPI.Areas.HelpPage.ModelDescriptions; using AutomationSystemAPI.Areas.HelpPage.Models; namespace AutomationSystemAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.IO.FileSystem.Tests { public class Directory_Delete_str : FileSystemTest { #region Utilities public virtual void Delete(string path) { Directory.Delete(path); } #endregion #region UniversalTests [Fact] public void NullParameters() { Assert.Throws<ArgumentNullException>(() => Delete(null)); } [Fact] public void InvalidParameters() { Assert.Throws<ArgumentException>(() => Delete(string.Empty)); } [Fact] public void ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName)); } Assert.True(testDir.Exists); } [Fact] public void ShouldThrowIOExceptionForDirectoryWithFiles() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] public void DirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [OuterLoop] public void DeleteRoot() { Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory()))); } [Fact] public void PositiveTest() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] public void ShouldThrowDirectoryNotFoundExceptionForNonexistentDirectory() { Assert.Throws<DirectoryNotFoundException>(() => Delete(GetTestFilePath())); } [Fact] public void ShouldThrowIOExceptionDeletingCurrentDirectory() { Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory())); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsExtendedDirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsLongPathExtendedDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500).FullPath); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsDeleteExtendedReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsShouldBeAbleToDeleteHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixShouldBeAbleToDeleteHiddenDirectory() { string testDir = "." + GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, testDir)); Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden)); Delete(Path.Combine(TestDirectory, testDir)); Assert.False(Directory.Exists(testDir)); } #endregion } public class Directory_Delete_str_bool : Directory_Delete_str { #region Utilities public override void Delete(string path) { Directory.Delete(path, false); } public virtual void Delete(string path, bool recursive) { Directory.Delete(path, recursive); } #endregion [Fact] public void RecursiveDelete() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); testDir.CreateSubdirectory(GetTestFileName()); Delete(testDir.FullName, true); Assert.False(testDir.Exists); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using Directory = Lucene.Net.Store.Directory; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { /// <summary>Test that BooleanQuery.setMinimumNumberShouldMatch works.</summary> [TestFixture] public class TestBooleanMinShouldMatch:LuceneTestCase { private class AnonymousClassCallback : TestBoolean2.Callback { public AnonymousClassCallback(System.Random rnd, TestBooleanMinShouldMatch enclosingInstance) { InitBlock(rnd, enclosingInstance); } private void InitBlock(System.Random rnd, TestBooleanMinShouldMatch enclosingInstance) { this.rnd = rnd; this.enclosingInstance = enclosingInstance; } private System.Random rnd; private TestBooleanMinShouldMatch enclosingInstance; public TestBooleanMinShouldMatch Enclosing_Instance { get { return enclosingInstance; } } public virtual void PostCreate(BooleanQuery q) { BooleanClause[] c = q.GetClauses(); int opt = 0; for (int i = 0; i < c.Length; i++) { if (c[i].GetOccur() == BooleanClause.Occur.SHOULD) opt++; } q.SetMinimumNumberShouldMatch(rnd.Next(opt + 2)); } } public Directory index; public IndexReader r; public IndexSearcher s; [SetUp] public override void SetUp() { base.SetUp(); System.String[] data = new System.String[]{"A 1 2 3 4 5 6", "Z 4 5 6", null, "B 2 4 5 6", "Y 3 5 6", null, "C 3 6", "X 4 5 6"}; index = new RAMDirectory(); IndexWriter writer = new IndexWriter(index, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < data.Length; i++) { Document doc = new Document(); doc.Add(new Field("id", System.Convert.ToString(i), Field.Store.YES, Field.Index.NOT_ANALYZED)); //Field.Keyword("id",String.valueOf(i))); doc.Add(new Field("all", "all", Field.Store.YES, Field.Index.NOT_ANALYZED)); //Field.Keyword("all","all")); if (null != data[i]) { doc.Add(new Field("data", data[i], Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("data",data[i])); } writer.AddDocument(doc); } writer.Optimize(); writer.Close(); r = IndexReader.Open(index); s = new IndexSearcher(r); //System.out.println("Set up " + getName()); } public virtual void VerifyNrHits(Query q, int expected) { ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs; if (expected != h.Length) { PrintHits(Lucene.Net.TestCase.GetName(), h, s); } Assert.AreEqual(expected, h.Length, "result count"); QueryUtils.Check(q, s); } [Test] public virtual void TestAllOptional() { BooleanQuery q = new BooleanQuery(); for (int i = 1; i <= 4; i++) { q.Add(new TermQuery(new Term("data", "" + i)), BooleanClause.Occur.SHOULD); //false, false); } q.SetMinimumNumberShouldMatch(2); // match at least two of 4 VerifyNrHits(q, 2); } [Test] public virtual void TestOneReqAndSomeOptional() { /* one required, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.SHOULD); //false, false); q.SetMinimumNumberShouldMatch(2); // 2 of 3 optional VerifyNrHits(q, 5); } [Test] public virtual void TestSomeReqAndSomeOptional() { /* two required, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.SHOULD); //false, false); q.SetMinimumNumberShouldMatch(2); // 2 of 3 optional VerifyNrHits(q, 5); } [Test] public virtual void TestOneProhibAndSomeOptional() { /* one prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.SetMinimumNumberShouldMatch(2); // 2 of 3 optional VerifyNrHits(q, 1); } [Test] public virtual void TestSomeProhibAndSomeOptional() { /* two prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "C")), BooleanClause.Occur.MUST_NOT); //false, true ); q.SetMinimumNumberShouldMatch(2); // 2 of 3 optional VerifyNrHits(q, 1); } [Test] public virtual void TestOneReqOneProhibAndSomeOptional() { /* one required, one prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); // true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.SetMinimumNumberShouldMatch(3); // 3 of 4 optional VerifyNrHits(q, 1); } [Test] public virtual void TestSomeReqOneProhibAndSomeOptional() { /* two required, one prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.SetMinimumNumberShouldMatch(3); // 3 of 4 optional VerifyNrHits(q, 1); } [Test] public virtual void TestOneReqSomeProhibAndSomeOptional() { /* one required, two prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "C")), BooleanClause.Occur.MUST_NOT); //false, true ); q.SetMinimumNumberShouldMatch(3); // 3 of 4 optional VerifyNrHits(q, 1); } [Test] public virtual void TestSomeReqSomeProhibAndSomeOptional() { /* two required, two prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "C")), BooleanClause.Occur.MUST_NOT); //false, true ); q.SetMinimumNumberShouldMatch(3); // 3 of 4 optional VerifyNrHits(q, 1); } [Test] public virtual void TestMinHigherThenNumOptional() { /* two required, two prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "C")), BooleanClause.Occur.MUST_NOT); //false, true ); q.SetMinimumNumberShouldMatch(90); // 90 of 4 optional ?!?!?! VerifyNrHits(q, 0); } [Test] public virtual void TestMinEqualToNumOptional() { /* two required, two optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.SetMinimumNumberShouldMatch(2); // 2 of 2 optional VerifyNrHits(q, 1); } [Test] public virtual void TestOneOptionalEqualToMin() { /* two required, one optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.MUST); //true, false); q.SetMinimumNumberShouldMatch(1); // 1 of 1 optional VerifyNrHits(q, 1); } [Test] public virtual void TestNoOptionalButMin() { /* two required, no optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.MUST); //true, false); q.SetMinimumNumberShouldMatch(1); // 1 of 0 optional VerifyNrHits(q, 0); } [Test] public virtual void TestNoOptionalButMin2() { /* one required, no optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.SetMinimumNumberShouldMatch(1); // 1 of 0 optional VerifyNrHits(q, 0); } [Test] public virtual void TestRandomQueries() { System.Random rnd = NewRandom(); System.String field = "data"; System.String[] vals = new System.String[]{"1", "2", "3", "4", "5", "6", "A", "Z", "B", "Y", "Z", "X", "foo"}; int maxLev = 4; // callback object to set a random setMinimumNumberShouldMatch TestBoolean2.Callback minNrCB = new AnonymousClassCallback(rnd, this); // increase number of iterations for more complete testing for (int i = 0; i < 1000; i++) { int lev = rnd.Next(maxLev); long seed = rnd.Next(System.Int32.MaxValue); BooleanQuery q1 = TestBoolean2.RandBoolQuery(new System.Random((System.Int32) seed), lev, field, vals, null); // BooleanQuery q2 = TestBoolean2.randBoolQuery(new Random(seed), lev, field, vals, minNrCB); BooleanQuery q2 = TestBoolean2.RandBoolQuery(new System.Random((System.Int32) seed), lev, field, vals, null); // only set minimumNumberShouldMatch on the top level query since setting // at a lower level can change the score. minNrCB.PostCreate(q2); // Can't use Hits because normalized scores will mess things // up. The non-sorting version of search() that returns TopDocs // will not normalize scores. TopDocs top1 = s.Search(q1, null, 100); TopDocs top2 = s.Search(q2, null, 100); QueryUtils.Check(q1, s); QueryUtils.Check(q2, s); // The constrained query // should be a superset to the unconstrained query. if (top2.TotalHits > top1.TotalHits) { //TestCase.fail("Constrained results not a subset:\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q2.ToString()); Assert.Fail("Constrained results not a subset:\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q2.ToString()); } for (int hit = 0; hit < top2.TotalHits; hit++) { int id = top2.ScoreDocs[hit].doc; float score = top2.ScoreDocs[hit].score; bool found = false; // find this doc in other hits for (int other = 0; other < top1.TotalHits; other++) { if (top1.ScoreDocs[other].doc == id) { found = true; float otherScore = top1.ScoreDocs[other].score; // check if scores match if (System.Math.Abs(otherScore - score) > 1.0e-6f) { //TestCase.fail("Doc " + id + " scores don't match\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q2.ToString()); Assert.Fail("Doc " + id + " scores don't match\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q2.ToString()); } } } // check if subset if (!found) { //TestCase.fail("Doc " + id + " not found\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q2.ToString()); Assert.Fail("Doc " + id + " not found\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q2.ToString()); } } } // System.out.println("Total hits:"+tot); } protected internal virtual void PrintHits(System.String test, ScoreDoc[] h, Searcher searcher) { System.Console.Error.WriteLine("------- " + test + " -------"); for (int i = 0; i < h.Length; i++) { Document d = searcher.Doc(h[i].doc); float score = h[i].score; System.Console.Error.WriteLine("#" + i + ": {0.000000}" + score + " - " + d.Get("id") + " - " + d.Get("data")); } } } }
using System.Net.Sockets; using MySqlConnector.Protocol.Serialization; using MySqlConnector.Utilities; namespace MySqlConnector; /// <summary> /// <see cref="MySqlTransaction"/> represents an in-progress transaction on a MySQL Server. /// </summary> public sealed class MySqlTransaction : DbTransaction { /// <summary> /// Commits the database transaction. /// </summary> public override void Commit() => CommitAsync(IOBehavior.Synchronous, default).GetAwaiter().GetResult(); /// <summary> /// Asynchronously commits the database transaction. /// </summary> /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER public override Task CommitAsync(CancellationToken cancellationToken = default) => CommitAsync(Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #else public Task CommitAsync(CancellationToken cancellationToken = default) => CommitAsync(Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #endif private async Task CommitAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { VerifyValid(); using var activity = Connection!.Session.StartActivity("Commit"); try { using (var cmd = new MySqlCommand("commit", Connection, this) { NoActivity = true }) await cmd.ExecuteNonQueryAsync(ioBehavior, cancellationToken).ConfigureAwait(false); Connection!.CurrentTransaction = null; Connection = null; activity?.SetSuccess(); } catch (Exception ex) when (activity is { IsAllDataRequested: true }) { activity.SetException(ex); throw; } } /// <summary> /// Rolls back the database transaction. /// </summary> public override void Rollback() => RollbackAsync(IOBehavior.Synchronous, default).GetAwaiter().GetResult(); /// <summary> /// Asynchronously rolls back the database transaction. /// </summary> /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER public override Task RollbackAsync(CancellationToken cancellationToken = default) => RollbackAsync(Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #else public Task RollbackAsync(CancellationToken cancellationToken = default) => RollbackAsync(Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #endif private async Task RollbackAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { VerifyValid(); await DoRollback(ioBehavior, cancellationToken).ConfigureAwait(false); Connection!.CurrentTransaction = null; Connection = null; } /// <summary> /// Removes the named transaction savepoint with the specified <paramref name="savepointName"/>. No commit or rollback occurs. /// </summary> /// <param name="savepointName">The savepoint name.</param> /// <remarks>The proposed ADO.NET API that this is based on is not finalized; this API may change in the future.</remarks> #if NET5_0_OR_GREATER public override void Release(string savepointName) => ExecuteSavepointAsync("release ", savepointName, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); #else public void Release(string savepointName) => ExecuteSavepointAsync("release ", savepointName, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); #endif /// <summary> /// Asynchronously removes the named transaction savepoint with the specified <paramref name="savepointName"/>. No commit or rollback occurs. /// </summary> /// <param name="savepointName">The savepoint name.</param> /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// <remarks>The proposed ADO.NET API that this is based on is not finalized; this API may change in the future.</remarks> #if NET5_0_OR_GREATER public override Task ReleaseAsync(string savepointName, CancellationToken cancellationToken = default) => ExecuteSavepointAsync("release ", savepointName, Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #else public Task ReleaseAsync(string savepointName, CancellationToken cancellationToken = default) => ExecuteSavepointAsync("release ", savepointName, Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #endif /// <summary> /// Rolls back the current transaction to the savepoint with the specified <paramref name="savepointName"/> without aborting the transaction. /// </summary> /// <param name="savepointName">The savepoint name.</param> /// <remarks><para>The name must have been created with <see cref="Save"/>, but not released by calling <see cref="Release"/>.</para> /// <para>The proposed ADO.NET API that this is based on is not finalized; this API may change in the future.</para></remarks> #if NET5_0_OR_GREATER public override void Rollback(string savepointName) => ExecuteSavepointAsync("rollback to ", savepointName, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); #else public void Rollback(string savepointName) => ExecuteSavepointAsync("rollback to ", savepointName, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); #endif /// <summary> /// Asynchronously rolls back the current transaction to the savepoint with the specified <paramref name="savepointName"/> without aborting the transaction. /// </summary> /// <param name="savepointName">The savepoint name.</param> /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// <remarks><para>The name must have been created with <see cref="SaveAsync"/>, but not released by calling <see cref="ReleaseAsync"/>.</para> /// <para>The proposed ADO.NET API that this is based on is not finalized; this API may change in the future.</para></remarks> #if NET5_0_OR_GREATER public override Task RollbackAsync(string savepointName, CancellationToken cancellationToken = default) => ExecuteSavepointAsync("rollback to ", savepointName, Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #else public Task RollbackAsync(string savepointName, CancellationToken cancellationToken = default) => ExecuteSavepointAsync("rollback to ", savepointName, Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #endif /// <summary> /// Sets a named transaction savepoint with the specified <paramref name="savepointName"/>. If the current transaction /// already has a savepoint with the same name, the old savepoint is deleted and a new one is set. /// </summary> /// <param name="savepointName">The savepoint name.</param> /// <remarks>The proposed ADO.NET API that this is based on is not finalized; this API may change in the future.</remarks> #if NET5_0_OR_GREATER public override void Save(string savepointName) => ExecuteSavepointAsync("", savepointName, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); #else public void Save(string savepointName) => ExecuteSavepointAsync("", savepointName, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); #endif /// <summary> /// Asynchronously sets a named transaction savepoint with the specified <paramref name="savepointName"/>. If the current transaction /// already has a savepoint with the same name, the old savepoint is deleted and a new one is set. /// </summary> /// <param name="savepointName">The savepoint name.</param> /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// <remarks>The proposed ADO.NET API that this is based on is not finalized; this API may change in the future.</remarks> #if NET5_0_OR_GREATER public override Task SaveAsync(string savepointName, CancellationToken cancellationToken = default) => ExecuteSavepointAsync("", savepointName, Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #else public Task SaveAsync(string savepointName, CancellationToken cancellationToken = default) => ExecuteSavepointAsync("", savepointName, Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, cancellationToken); #endif private async Task ExecuteSavepointAsync(string command, string savepointName, IOBehavior ioBehavior, CancellationToken cancellationToken) { VerifyValid(); if (savepointName is null) throw new ArgumentNullException(nameof(savepointName)); if (savepointName.Length == 0) throw new ArgumentException("savepointName must not be empty", nameof(savepointName)); using var cmd = new MySqlCommand(command + "savepoint " + QuoteIdentifier(savepointName), Connection, this) { NoActivity = true }; await cmd.ExecuteNonQueryAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the <see cref="MySqlConnection"/> that this transaction is associated with. /// </summary> public new MySqlConnection? Connection { get; private set; } /// <summary> /// Gets the <see cref="MySqlConnection"/> that this transaction is associated with. /// </summary> protected override DbConnection? DbConnection => Connection; /// <summary> /// Gets the <see cref="IsolationLevel"/> of this transaction. This value is set from <see cref="MySqlConnection.BeginTransaction(IsolationLevel)"/> /// or any other overload that specifies an <see cref="IsolationLevel"/>. /// </summary> public override IsolationLevel IsolationLevel { get; } /// <summary> /// Releases any resources associated with this transaction. If it was not committed, it will be rolled back. /// </summary> /// <param name="disposing"><c>true</c> if this method is being called from <c>Dispose</c>; <c>false</c> if being called from a finalizer.</param> protected override void Dispose(bool disposing) { try { #pragma warning disable CA2012 // Safe because method completes synchronously if (disposing) DisposeAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); #pragma warning restore CA2012 } finally { base.Dispose(disposing); } } /// <summary> /// Asynchronously releases any resources associated with this transaction. If it was not committed, it will be rolled back. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER public override ValueTask DisposeAsync() => DisposeAsync(Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, CancellationToken.None); #else public Task DisposeAsync() => DisposeAsync(Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous, CancellationToken.None); #endif #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER internal ValueTask DisposeAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) #else internal Task DisposeAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) #endif { m_isDisposed = true; if (Connection?.CurrentTransaction == this) return DoDisposeAsync(ioBehavior, cancellationToken); Connection = null; #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER return default; #else return Utility.CompletedTask; #endif } #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER private async ValueTask DoDisposeAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) #else private async Task DoDisposeAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) #endif { if (Connection?.CurrentTransaction == this) { if (Connection.State == ConnectionState.Open && Connection.Session.IsConnected) { try { await DoRollback(ioBehavior, cancellationToken).ConfigureAwait(false); } catch (IOException) { } catch (SocketException) { } } Connection.CurrentTransaction = null; } Connection = null; } internal MySqlTransaction(MySqlConnection connection, IsolationLevel isolationLevel) { Connection = connection; IsolationLevel = isolationLevel; } private async Task DoRollback(IOBehavior ioBehavior, CancellationToken cancellationToken) { using var activity = Connection!.Session.StartActivity("Rollback"); try { using var cmd = new MySqlCommand("rollback", Connection, this) { NoActivity = true }; await cmd.ExecuteNonQueryAsync(ioBehavior, cancellationToken).ConfigureAwait(false); activity?.SetSuccess(); } catch (Exception ex) when (activity is { IsAllDataRequested: true }) { activity.SetException(ex); throw; } } private void VerifyValid() { if (m_isDisposed) throw new ObjectDisposedException(nameof(MySqlTransaction)); if (Connection is null) throw new InvalidOperationException("Already committed or rolled back."); if (Connection.CurrentTransaction is null) throw new InvalidOperationException("There is no active transaction."); if (!object.ReferenceEquals(Connection.CurrentTransaction, this)) throw new InvalidOperationException("This is not the active transaction."); } private static string QuoteIdentifier(string identifier) => "`" + identifier.Replace("`", "``") + "`"; private bool m_isDisposed; }
/* * (c) 2008 MOSA - The Managed Operating System Alliance * * Licensed under the terms of the New BSD License. * * Authors: * Simon Wollwage (rootnode) <kintaro@think-in-co.de> */ namespace Pictor { //----------------------------------------------------------------BSpline // A very simple class of Bi-cubic Spline Interpolation. // First call Init(num, x[], y[]) where num - number of source points, // x, y - arrays of X and Y values respectively. Here Y must be a function // of X. It means that all the X-Coordinates must be arranged in the ascending // order. // Then call Get(x) that calculates a Value Y for the respective X. // The class supports extrapolation, i.e. you can call Get(x) where x is // outside the given with Init() X-range. Extrapolation is a simple linear // function. //------------------------------------------------------------------------ public sealed class BSpline { private int m_max; private int m_num; private int m_xOffset; private int m_yOffset; private ArrayPOD<double> m_am = new ArrayPOD<double>(16); private int m_last_idx; //------------------------------------------------------------------------ public BSpline() { m_max = (0); m_num = (0); m_xOffset = (0); m_yOffset = (0); m_last_idx = -1; } //------------------------------------------------------------------------ public BSpline(int num) { m_max = (0); m_num = (0); m_xOffset = (0); m_yOffset = (0); m_last_idx = -1; Init(num); } //------------------------------------------------------------------------ public BSpline(int num, double[] x, double[] y) { m_max = (0); m_num = (0); m_xOffset = (0); m_yOffset = (0); m_last_idx = -1; Init(num, x, y); } //------------------------------------------------------------------------ public void Init(int max) { if (max > 2 && max > m_max) { m_am.Resize(max * 3); m_max = max; m_xOffset = m_max; m_yOffset = m_max * 2; } m_num = 0; m_last_idx = -1; } //------------------------------------------------------------------------ public void AddPoint(double x, double y) { if (m_num < m_max) { m_am[m_xOffset + m_num] = x; m_am[m_yOffset + m_num] = y; ++m_num; } } //------------------------------------------------------------------------ public void Prepare() { if (m_num > 2) { int i, k; int r; int s; double h, p, d, f, e; for (k = 0; k < m_num; k++) { m_am[k] = 0.0; } int n1 = 3 * m_num; ArrayPOD<double> al = new ArrayPOD<double>(n1); for (k = 0; k < n1; k++) { al[k] = 0.0; } r = m_num; s = m_num * 2; n1 = m_num - 1; d = m_am[m_xOffset + 1] - m_am[m_xOffset + 0]; e = (m_am[m_yOffset + 1] - m_am[m_yOffset + 0]) / d; for (k = 1; k < n1; k++) { h = d; d = m_am[m_xOffset + k + 1] - m_am[m_xOffset + k]; f = e; e = (m_am[m_yOffset + k + 1] - m_am[m_yOffset + k]) / d; al[k] = d / (d + h); al[r + k] = 1.0 - al[k]; al[s + k] = 6.0 * (e - f) / (h + d); } for (k = 1; k < n1; k++) { p = 1.0 / (al[r + k] * al[k - 1] + 2.0); al[k] *= -p; al[s + k] = (al[s + k] - al[r + k] * al[s + k - 1]) * p; } m_am[n1] = 0.0; al[n1 - 1] = al[s + n1 - 1]; m_am[n1 - 1] = al[n1 - 1]; for (k = n1 - 2, i = 0; i < m_num - 2; i++, k--) { al[k] = al[k] * al[k + 1] + al[s + k]; m_am[k] = al[k]; } } m_last_idx = -1; } //------------------------------------------------------------------------ public void Init(int num, double[] x, double[] y) { if (num > 2) { Init(num); int i; for (i = 0; i < num; i++) { AddPoint(x[i], y[i]); } Prepare(); } m_last_idx = -1; } //------------------------------------------------------------------------ private void BSearch(int n, int xOffset, double x0, out int i) { int j = n - 1; int k; for (i = 0; (j - i) > 1; ) { k = (i + j) >> 1; if (x0 < m_am[xOffset + k]) j = k; else i = k; } } //------------------------------------------------------------------------ private double Interpolation(double x, int i) { int j = i + 1; double d = m_am[m_xOffset + i] - m_am[m_xOffset + j]; double h = x - m_am[m_xOffset + j]; double r = m_am[m_xOffset + i] - x; double p = d * d / 6.0; return (m_am[j] * r * r * r + m_am[i] * h * h * h) / 6.0 / d + ((m_am[m_yOffset + j] - m_am[j] * p) * r + (m_am[m_yOffset + i] - m_am[i] * p) * h) / d; } //------------------------------------------------------------------------ private double ExtrapolationLeft(double x) { double d = m_am[m_xOffset + 1] - m_am[m_xOffset + 0]; return (-d * m_am[1] / 6 + (m_am[m_yOffset + 1] - m_am[m_yOffset + 0]) / d) * (x - m_am[m_xOffset + 0]) + m_am[m_yOffset + 0]; } //------------------------------------------------------------------------ private double ExtrapolationRight(double x) { double d = m_am[m_xOffset + m_num - 1] - m_am[m_xOffset + m_num - 2]; return (d * m_am[m_num - 2] / 6 + (m_am[m_yOffset + m_num - 1] - m_am[m_yOffset + m_num - 2]) / d) * (x - m_am[m_xOffset + m_num - 1]) + m_am[m_yOffset + m_num - 1]; } //------------------------------------------------------------------------ public double Get(double x) { if (m_num > 2) { int i; // Extrapolation on the left if (x < m_am[m_xOffset + 0]) return ExtrapolationLeft(x); // Extrapolation on the right if (x >= m_am[m_xOffset + m_num - 1]) return ExtrapolationRight(x); // Interpolation BSearch(m_num, m_xOffset, x, out i); return Interpolation(x, i); } return 0.0; } //------------------------------------------------------------------------ public double GetStateful(double x) { if (m_num > 2) { // Extrapolation on the left if (x < m_am[m_xOffset + 0]) return ExtrapolationLeft(x); // Extrapolation on the right if (x >= m_am[m_xOffset + m_num - 1]) return ExtrapolationRight(x); if (m_last_idx >= 0) { // Check if x is not in current range if (x < m_am[m_xOffset + m_last_idx] || x > m_am[m_xOffset + m_last_idx + 1]) { // Check if x between next points (most probably) if (m_last_idx < m_num - 2 && x >= m_am[m_xOffset + m_last_idx + 1] && x <= m_am[m_xOffset + m_last_idx + 2]) { ++m_last_idx; } else if (m_last_idx > 0 && x >= m_am[m_xOffset + m_last_idx - 1] && x <= m_am[m_xOffset + m_last_idx]) { // x is between pevious points --m_last_idx; } else { // Else perform full search BSearch(m_num, m_xOffset, x, out m_last_idx); } } return Interpolation(x, m_last_idx); } else { // Interpolation BSearch(m_num, m_xOffset, x, out m_last_idx); return Interpolation(x, m_last_idx); } } return 0.0; } }; }
/* * 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 OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo; namespace OpenSim.Groups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsMessagingModule")] public class GroupsMessagingModule : ISharedRegionModule, IGroupsMessagingModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IPresenceService m_presenceService; private IMessageTransferModule m_msgTransferModule = null; private IUserManagement m_UserManagement = null; private IGroupsServicesConnector m_groupData = null; // Config Options private bool m_groupMessagingEnabled = false; private bool m_debugEnabled = true; /// <summary> /// If enabled, module only tries to send group IMs to online users by querying cached presence information. /// </summary> private bool m_messageOnlineAgentsOnly; /// <summary> /// Cache for online users. /// </summary> /// <remarks> /// Group ID is key, presence information for online members is value. /// Will only be non-null if m_messageOnlineAgentsOnly = true /// We cache here so that group messages don't constantly have to re-request the online user list to avoid /// attempted expensive sending of messages to offline users. /// The tradeoff is that a user that comes online will not receive messages consistently from all other users /// until caches have updated. /// Therefore, we set the cache expiry to just 20 seconds. /// </remarks> private ThreadedClasses.ExpiringCache<UUID, PresenceInfo[]> m_usersOnlineCache; private int m_usersOnlineCacheExpirySeconds = 20; private ThreadedClasses.RwLockedDictionary<UUID, ThreadedClasses.RwLockedList<string>> m_groupsAgentsDroppedFromChatSession = new ThreadedClasses.RwLockedDictionary<UUID, ThreadedClasses.RwLockedList<string>>(); private ThreadedClasses.RwLockedDictionary<UUID, ThreadedClasses.RwLockedList<string>> m_groupsAgentsInvitedToChatSession = new ThreadedClasses.RwLockedDictionary<UUID, ThreadedClasses.RwLockedList<string>>(); #region Region Module interfaceBase Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) // Do not run this module by default. return; // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("MessagingModule", "") != Name)) { m_groupMessagingEnabled = false; return; } m_groupMessagingEnabled = groupsConfig.GetBoolean("MessagingEnabled", true); if (!m_groupMessagingEnabled) return; m_messageOnlineAgentsOnly = groupsConfig.GetBoolean("MessageOnlineUsersOnly", true); if (m_messageOnlineAgentsOnly) { m_usersOnlineCache = new ThreadedClasses.ExpiringCache<UUID, PresenceInfo[]>(30); } else { m_log.Error("[Groups.Messaging]: GroupsMessagingModule V2 requires MessageOnlineUsersOnly = true"); m_groupMessagingEnabled = false; return; } m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true); m_log.InfoFormat( "[Groups.Messaging]: GroupsMessagingModule enabled with MessageOnlineOnly = {0}, DebugEnabled = {1}", m_messageOnlineAgentsOnly, m_debugEnabled); } public void AddRegion(Scene scene) { if (!m_groupMessagingEnabled) return; scene.RegisterModuleInterface<IGroupsMessagingModule>(this); m_sceneList.Add(scene); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; scene.EventManager.OnClientLogin += OnClientLogin; } public void RegionLoaded(Scene scene) { if (!m_groupMessagingEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>(); // No groups module, no groups messaging if (m_groupData == null) { m_log.Error("[Groups.Messaging]: Could not get IGroupsServicesConnector, GroupsMessagingModule is now disabled."); RemoveRegion(scene); return; } m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no groups messaging if (m_msgTransferModule == null) { m_log.Error("[Groups.Messaging]: Could not get MessageTransferModule"); RemoveRegion(scene); return; } m_UserManagement = scene.RequestModuleInterface<IUserManagement>(); // No groups module, no groups messaging if (m_UserManagement == null) { m_log.Error("[Groups.Messaging]: Could not get IUserManagement, GroupsMessagingModule is now disabled."); RemoveRegion(scene); return; } if (m_presenceService == null) m_presenceService = scene.PresenceService; } public void RemoveRegion(Scene scene) { if (!m_groupMessagingEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_sceneList.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; scene.EventManager.OnClientLogin -= OnClientLogin; scene.UnregisterModuleInterface<IGroupsMessagingModule>(this); } public void Close() { if (!m_groupMessagingEnabled) return; if (m_debugEnabled) m_log.Debug("[Groups.Messaging]: Shutting down GroupsMessagingModule module."); m_sceneList.Clear(); m_groupData = null; m_msgTransferModule = null; } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "Groups Messaging Module V2"; } } public void PostInitialise() { // NoOp } #endregion /// <summary> /// Not really needed, but does confirm that the group exists. /// </summary> public bool StartGroupChatSession(UUID agentID, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null); if (groupInfo != null) { return true; } else { return false; } } public void SendMessageToGroup(GridInstantMessage im, UUID groupID) { SendMessageToGroup(im, groupID, UUID.Zero, null); } public void SendMessageToGroup( GridInstantMessage im, UUID groupID, UUID sendingAgentForGroupCalls, Func<GroupMembersData, bool> sendCondition) { UUID fromAgentID = new UUID(im.fromAgentID); // Unlike current XmlRpcGroups, Groups V2 can accept UUID.Zero when a perms check for the requesting agent // is not necessary. List<GroupMembersData> groupMembers = m_groupData.GetGroupMembers(UUID.Zero.ToString(), groupID); int groupMembersCount = groupMembers.Count; PresenceInfo[] onlineAgents = null; // In V2 we always only send to online members. // Sending to offline members is not an option. string[] t1 = groupMembers.ConvertAll<string>(gmd => gmd.AgentID.ToString()).ToArray(); // We cache in order not to overwhelm the presence service on large grids with many groups. This does // mean that members coming online will not see all group members until after m_usersOnlineCacheExpirySeconds has elapsed. // (assuming this is the same across all grid simulators). if (!m_usersOnlineCache.TryGetValue(groupID, out onlineAgents)) { onlineAgents = m_presenceService.GetAgents(t1); m_usersOnlineCache.Add(groupID, onlineAgents, m_usersOnlineCacheExpirySeconds); } HashSet<string> onlineAgentsUuidSet = new HashSet<string>(); Array.ForEach<PresenceInfo>(onlineAgents, pi => onlineAgentsUuidSet.Add(pi.UserID)); groupMembers = groupMembers.Where(gmd => onlineAgentsUuidSet.Contains(gmd.AgentID.ToString())).ToList(); // if (m_debugEnabled) // m_log.DebugFormat( // "[Groups.Messaging]: SendMessageToGroup called for group {0} with {1} visible members, {2} online", // groupID, groupMembersCount, groupMembers.Count()); int requestStartTick = Environment.TickCount; im.imSessionID = groupID.Guid; im.fromGroup = true; IClientAPI thisClient = GetActiveClient(fromAgentID); if (thisClient != null) { im.RegionID = thisClient.Scene.RegionInfo.RegionID.Guid; } if ((im.binaryBucket == null) || (im.binaryBucket.Length == 0) || ((im.binaryBucket.Length == 1 && im.binaryBucket[0] == 0))) { ExtendedGroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), groupID, null); if (groupInfo != null) im.binaryBucket = Util.StringToBytes256(groupInfo.GroupName); } // Send to self first of all im.toAgentID = im.fromAgentID; im.fromGroup = true; ProcessMessageFromGroupSession(im); List<UUID> regions = new List<UUID>(); List<UUID> clientsAlreadySent = new List<UUID>(); // Then send to everybody else foreach (GroupMembersData member in groupMembers) { if (member.AgentID.Guid == im.fromAgentID) continue; if (clientsAlreadySent.Contains(member.AgentID)) continue; clientsAlreadySent.Add(member.AgentID); if (sendCondition != null) { if (!sendCondition(member)) { if (m_debugEnabled) m_log.DebugFormat( "[Groups.Messaging]: Not sending to {0} as they do not fulfill send condition", member.AgentID); continue; } } else if (hasAgentDroppedGroupChatSession(member.AgentID.ToString(), groupID)) { // Don't deliver messages to people who have dropped this session if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} has dropped session, not delivering to them", member.AgentID); continue; } im.toAgentID = member.AgentID.Guid; IClientAPI client = GetActiveClient(member.AgentID); if (client == null) { // If they're not local, forward across the grid // BUT do it only once per region, please! Sim would be even better! if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Delivering to {0} via Grid", member.AgentID); bool reallySend = true; if (onlineAgents != null) { PresenceInfo presence = onlineAgents.First(p => p.UserID == member.AgentID.ToString()); if (regions.Contains(presence.RegionID)) reallySend = false; else regions.Add(presence.RegionID); } if (reallySend) { // We have to create a new IM structure because the transfer module // uses async send GridInstantMessage msg = new GridInstantMessage(im, true); m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { }); } } else { // Deliver locally, directly if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name); ProcessMessageFromGroupSession(im); } } if (m_debugEnabled) m_log.DebugFormat( "[Groups.Messaging]: SendMessageToGroup for group {0} with {1} visible members, {2} online took {3}ms", groupID, groupMembersCount, groupMembers.Count(), Environment.TickCount - requestStartTick); } #region SimGridEventHandlers void OnClientLogin(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: OnInstantMessage registered for {0}", client.Name); } private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: OnInstantMessage registered for {0}", client.Name); ResetAgentGroupChatSessions(client.AgentId.ToString()); } void OnMakeRootAgent(ScenePresence sp) { sp.ControllingClient.OnInstantMessage += OnInstantMessage; } void OnMakeChildAgent(ScenePresence sp) { sp.ControllingClient.OnInstantMessage -= OnInstantMessage; } private void OnGridInstantMessage(GridInstantMessage msg) { // The instant message module will only deliver messages of dialog types: // MessageFromAgent, StartTyping, StopTyping, MessageFromObject // // Any other message type will not be delivered to a client by the // Instant Message Module UUID regionID = new UUID(msg.RegionID); if (m_debugEnabled) { m_log.DebugFormat("[Groups.Messaging]: {0} called, IM from region {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, regionID); DebugGridInstantMessage(msg); } // Incoming message from a group if ((msg.fromGroup == true) && (msg.dialog == (byte)InstantMessageDialog.SessionSend)) { // We have to redistribute the message across all members of the group who are here // on this sim UUID GroupID = new UUID(msg.imSessionID); Scene aScene = m_sceneList[0]; GridRegion regionOfOrigin = aScene.GridService.GetRegionByUUID(aScene.RegionInfo.ScopeID, regionID); List<GroupMembersData> groupMembers = m_groupData.GetGroupMembers(UUID.Zero.ToString(), GroupID); //if (m_debugEnabled) // foreach (GroupMembersData m in groupMembers) // m_log.DebugFormat("[Groups.Messaging]: member {0}", m.AgentID); foreach (Scene s in m_sceneList) { s.ForEachScenePresence(sp => { // If we got this via grid messaging, it's because the caller thinks // that the root agent is here. We should only send the IM to root agents. if (sp.IsChildAgent) return; GroupMembersData m = groupMembers.Find(gmd => { return gmd.AgentID == sp.UUID; }); if (m.AgentID == UUID.Zero) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: skipping agent {0} because he is not a member of the group", sp.UUID); return; } // Check if the user has an agent in the region where // the IM came from, and if so, skip it, because the IM // was already sent via that agent if (regionOfOrigin != null) { AgentCircuitData aCircuit = s.AuthenticateHandler.GetAgentCircuitData(sp.UUID); if (aCircuit != null) { if (aCircuit.ChildrenCapSeeds.Keys.Contains(regionOfOrigin.RegionHandle)) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: skipping agent {0} because he has an agent in region of origin", sp.UUID); return; } else { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: not skipping agent {0}", sp.UUID); } } } UUID AgentID = sp.UUID; msg.toAgentID = AgentID.Guid; if (!hasAgentDroppedGroupChatSession(AgentID.ToString(), GroupID)) { if (!hasAgentBeenInvitedToGroupChatSession(AgentID.ToString(), GroupID)) AddAgentToSession(AgentID, GroupID, msg); else { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", sp.Name); ProcessMessageFromGroupSession(msg); } } }); } } } private void ProcessMessageFromGroupSession(GridInstantMessage msg) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID); UUID AgentID = new UUID(msg.fromAgentID); UUID GroupID = new UUID(msg.imSessionID); UUID toAgentID = new UUID(msg.toAgentID); switch (msg.dialog) { case (byte)InstantMessageDialog.SessionAdd: AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID); break; case (byte)InstantMessageDialog.SessionDrop: AgentDroppedFromGroupChatSession(AgentID.ToString(), GroupID); break; case (byte)InstantMessageDialog.SessionSend: // User hasn't dropped, so they're in the session, // maybe we should deliver it. IClientAPI client = GetActiveClient(new UUID(msg.toAgentID)); if (client != null) { // Deliver locally, directly if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Delivering to {0} locally", client.Name); if (!hasAgentDroppedGroupChatSession(toAgentID.ToString(), GroupID)) { if (!hasAgentBeenInvitedToGroupChatSession(toAgentID.ToString(), GroupID)) // This actually sends the message too, so no need to resend it // with client.SendInstantMessage AddAgentToSession(toAgentID, GroupID, msg); else client.SendInstantMessage(msg); } } else { m_log.WarnFormat("[Groups.Messaging]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID); } break; default: m_log.WarnFormat("[Groups.Messaging]: I don't know how to proccess a {0} message.", ((InstantMessageDialog)msg.dialog).ToString()); break; } } private void AddAgentToSession(UUID AgentID, UUID GroupID, GridInstantMessage msg) { // Agent not in session and hasn't dropped from session // Add them to the session for now, and Invite them AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID); IClientAPI activeClient = GetActiveClient(AgentID); if (activeClient != null) { GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null); if (groupInfo != null) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Sending chatterbox invite instant message"); // Force? open the group session dialog??? // and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg); IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>(); eq.ChatterboxInvitation( GroupID , groupInfo.GroupName , new UUID(msg.fromAgentID) , msg.message , AgentID , msg.fromAgentName , msg.dialog , msg.timestamp , msg.offline == 1 , (int)msg.ParentEstateID , msg.Position , 1 , new UUID(msg.imSessionID) , msg.fromGroup , OpenMetaverse.Utils.StringToBytes(groupInfo.GroupName) ); eq.ChatterBoxSessionAgentListUpdates( new UUID(GroupID) , AgentID , new UUID(msg.toAgentID) , false //canVoiceChat , false //isModerator , false //text mute ); } } } #endregion #region ClientEvents private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { if (m_debugEnabled) { m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); DebugGridInstantMessage(im); } // Start group IM session if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart)) { if (m_debugEnabled) m_log.InfoFormat("[Groups.Messaging]: imSessionID({0}) toAgentID({1})", im.imSessionID, im.toAgentID); UUID GroupID = new UUID(im.imSessionID); UUID AgentID = new UUID(im.fromAgentID); GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null); if (groupInfo != null) { AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID); ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID); IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); queue.ChatterBoxSessionAgentListUpdates( GroupID , AgentID , new UUID(im.toAgentID) , false //canVoiceChat , false //isModerator , false //text mute ); } } // Send a message from locally connected client to a group if ((im.dialog == (byte)InstantMessageDialog.SessionSend)) { UUID GroupID = new UUID(im.imSessionID); UUID AgentID = new UUID(im.fromAgentID); if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Send message to session for group {0} with session ID {1}", GroupID, im.imSessionID.ToString()); //If this agent is sending a message, then they want to be in the session AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID); SendMessageToGroup(im, GroupID); } } #endregion void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap moderatedMap = new OSDMap(4); moderatedMap.Add("voice", OSD.FromBoolean(false)); OSDMap sessionMap = new OSDMap(4); sessionMap.Add("moderated_mode", moderatedMap); sessionMap.Add("session_name", OSD.FromString(groupName)); sessionMap.Add("type", OSD.FromInteger(0)); sessionMap.Add("voice_enabled", OSD.FromBoolean(false)); OSDMap bodyMap = new OSDMap(4); bodyMap.Add("session_id", OSD.FromUUID(groupID)); bodyMap.Add("temp_session_id", OSD.FromUUID(groupID)); bodyMap.Add("success", OSD.FromBoolean(true)); bodyMap.Add("session_info", sessionMap); IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); if (queue != null) { queue.Enqueue(queue.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId); } } private void DebugGridInstantMessage(GridInstantMessage im) { // Don't log any normal IMs (privacy!) if (m_debugEnabled && im.dialog != (byte)InstantMessageDialog.MessageFromAgent) { m_log.WarnFormat("[Groups.Messaging]: IM: fromGroup({0})", im.fromGroup ? "True" : "False"); m_log.WarnFormat("[Groups.Messaging]: IM: Dialog({0})", ((InstantMessageDialog)im.dialog).ToString()); m_log.WarnFormat("[Groups.Messaging]: IM: fromAgentID({0})", im.fromAgentID.ToString()); m_log.WarnFormat("[Groups.Messaging]: IM: fromAgentName({0})", im.fromAgentName.ToString()); m_log.WarnFormat("[Groups.Messaging]: IM: imSessionID({0})", im.imSessionID.ToString()); m_log.WarnFormat("[Groups.Messaging]: IM: message({0})", im.message.ToString()); m_log.WarnFormat("[Groups.Messaging]: IM: offline({0})", im.offline.ToString()); m_log.WarnFormat("[Groups.Messaging]: IM: toAgentID({0})", im.toAgentID.ToString()); m_log.WarnFormat("[Groups.Messaging]: IM: binaryBucket({0})", OpenMetaverse.Utils.BytesToHexString(im.binaryBucket, "BinaryBucket")); } } #region Client Tools /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Looking for local client {0}", agentID); IClientAPI child = null; // Try root avatar first foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); if (sp != null) { if (!sp.IsChildAgent) { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Found root agent for client : {0}", sp.ControllingClient.Name); return sp.ControllingClient; } else { if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Found child agent for client : {0}", sp.ControllingClient.Name); child = sp.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none if (child == null) { if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Could not find local client for agent : {0}", agentID); } else { if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Returning child agent for client : {0}", child.Name); } return child; } #endregion #region GroupSessionTracking public void ResetAgentGroupChatSessions(string agentID) { m_groupsAgentsDroppedFromChatSession.ForEach(delegate(KeyValuePair<UUID, ThreadedClasses.RwLockedList<string>> kvp) { kvp.Value.Remove(agentID); }); m_groupsAgentsInvitedToChatSession.ForEach(delegate(KeyValuePair<UUID, ThreadedClasses.RwLockedList<string>> kvp) { kvp.Value.Remove(agentID); }); } public bool hasAgentBeenInvitedToGroupChatSession(string agentID, UUID groupID) { // If we're tracking this group, and we can find them in the tracking, then they've been invited return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID) && m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID); } public bool hasAgentDroppedGroupChatSession(string agentID, UUID groupID) { // If we're tracking drops for this group, // and we find them, well... then they've dropped return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID) && m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID); } public void AgentDroppedFromGroupChatSession(string agentID, UUID groupID) { if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)) { // If not in dropped list, add if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID)) { m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID); } } } public void AgentInvitedToGroupChatSession(string agentID, UUID groupID) { // Add Session Status if it doesn't exist for this session CreateGroupChatSessionTracking(groupID); // If nessesary, remove from dropped list if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID)) { m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID); } // Add to invited if (!m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID)) m_groupsAgentsInvitedToChatSession[groupID].Add(agentID); } private void CreateGroupChatSessionTracking(UUID groupID) { if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)) { m_groupsAgentsDroppedFromChatSession.Add(groupID, new ThreadedClasses.RwLockedList<string>()); m_groupsAgentsInvitedToChatSession.Add(groupID, new ThreadedClasses.RwLockedList<string>()); } } #endregion } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Web; using ASC.FederatedLogin.Helpers; using ASC.FederatedLogin.Profile; using JWT; using Newtonsoft.Json.Linq; namespace ASC.FederatedLogin.LoginProviders { public class GosUslugiLoginProvider : BaseLoginProvider<GosUslugiLoginProvider> { public string BaseDomain { get { return this["gosUslugiDomain"]; } } public override string CodeUrl { get { return BaseDomain + "/aas/oauth2/ac"; } } public override string AccessTokenUrl { get { return BaseDomain + "/aas/oauth2/te"; } } public override string ClientID { get { return this["gosUslugiClientId"]; } } public override string ClientSecret { get { return this["gosUslugiCert"]; } } public override string RedirectUri { get { return this["gosUslugiRedirectUrl"]; } } public override string Scopes { get { return "fullname birthdate gender email"; } } private string GosUslugiProfileUrl { get { return BaseDomain + "/rs/prns/"; } } public GosUslugiLoginProvider() { } public GosUslugiLoginProvider(string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(name, order, props, additional) { } public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params) { try { var token = Auth(context, Scopes); if (token == null) { throw new Exception("Login failed"); } return GetLoginProfile(token.AccessToken); } catch (ThreadAbortException) { throw; } catch (Exception ex) { return LoginProfile.FromError(ex); } } protected override OAuth20Token Auth(HttpContext context, string scopes, Dictionary<string, string> additionalArgs = null) { var error = context.Request["error"]; if (!string.IsNullOrEmpty(error)) { if (error == "access_denied") { error = "Canceled at provider"; } throw new Exception(error); } var code = context.Request["code"]; if (string.IsNullOrEmpty(code)) { RequestCode(HttpContext.Current, scopes); return null; } var state = context.Request["state"]; return GetAccessToken(state, code); } private void RequestCode(HttpContext context, string scope = null) { var timestamp = DateTime.UtcNow.ToString("yyyy.MM.dd HH:mm:ss +0000"); var state = Guid.NewGuid().ToString();//HttpContext.Current.Request.GetUrlRewriter().AbsoluteUri; var msg = scope + timestamp + ClientID + state; var encodedSignature = SignMsg(msg); var clientSecret = HttpServerUtility.UrlTokenEncode(encodedSignature); var requestParams = new Dictionary<string, string> { { "client_id", ClientID }, { "client_secret", clientSecret }, { "redirect_uri", RedirectUri }, { "scope", scope }, { "response_type", "code" }, { "state", state }, { "timestamp", timestamp }, { "access_type", "online" }, { "display", "popup" } }; var requestQuery = string.Join("&", requestParams.Select(pair => pair.Key + "=" + HttpUtility.UrlEncode(pair.Value)));//.Replace("+", "%2b"); var redURL = CodeUrl + "?" + requestQuery; context.Response.Redirect(redURL, true); } private OAuth20Token GetAccessToken(string state, string code) { var timestamp = DateTime.UtcNow.ToString("yyyy.MM.dd HH:mm:ss +0000"); var msg = Scopes + timestamp + ClientID + state; var encodedSignature = SignMsg(msg); var clientSecret = HttpServerUtility.UrlTokenEncode(encodedSignature); var requestParams = new Dictionary<string, string> { { "client_id", ClientID }, { "code", code }, { "grant_type", "authorization_code" }, { "client_secret", clientSecret }, { "state", state }, { "redirect_uri", RedirectUri }, { "scope", Scopes }, { "timestamp", timestamp }, { "token_type", "Bearer" } }; var requestQuery = string.Join("&", requestParams.Select(pair => pair.Key + "=" + HttpUtility.UrlEncode(pair.Value))); var result = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", requestQuery); return OAuth20Token.FromJson(result); } public override LoginProfile GetLoginProfile(string accessToken) { var tokenPayloadString = JsonWebToken.Decode(accessToken, string.Empty, false); var tokenPayload = JObject.Parse(tokenPayloadString); if (tokenPayload == null) { throw new Exception("Payload is incorrect"); } var oid = tokenPayload.Value<string>("urn:esia:sbj_id"); var userInfoString = RequestHelper.PerformRequest(GosUslugiProfileUrl + oid, "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var userInfo = JObject.Parse(userInfoString); if (userInfo == null) { throw new Exception("userinfo is incorrect"); } var profile = new LoginProfile { Id = oid, FirstName = userInfo.Value<string>("firstName"), LastName = userInfo.Value<string>("lastName"), Provider = ProviderConstants.GosUslugi, }; var userContactsString = RequestHelper.PerformRequest(GosUslugiProfileUrl + oid + "/ctts", "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var userContacts = JObject.Parse(userContactsString); if (userContacts == null) { throw new Exception("usercontacts is incorrect"); } var contactElements = userContacts.Value<JArray>("elements"); if (contactElements == null) { throw new Exception("usercontacts elements is incorrect"); } foreach (var contactElement in contactElements.ToObject<List<string>>()) { var userContactString = RequestHelper.PerformRequest(contactElement, "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var userContact = JObject.Parse(userContactString); if (userContact == null) { throw new Exception("usercontacts is incorrect"); } var type = userContact.Value<string>("type"); if (type != "EML") continue; profile.EMail = userContact.Value<string>("value"); break; } return profile; } private X509Certificate2 GetSignerCert() { var storeMy = new X509Store(StoreName.Root, StoreLocation.LocalMachine); storeMy.Open(OpenFlags.ReadOnly); var certColl = storeMy.Certificates.Find(X509FindType.FindBySubjectKeyIdentifier, ClientSecret, false); storeMy.Close(); if (certColl.Count == 0) { throw new Exception("Certificate not found"); } return certColl[0]; } private byte[] SignMsg(string msg) { var signerCert = GetSignerCert(); var msgBytes = Encoding.UTF8.GetBytes(msg); var contentInfo = new ContentInfo(msgBytes); var signedCms = new SignedCms(contentInfo, true); var cmsSigner = new CmsSigner(signerCert); signedCms.ComputeSignature(cmsSigner); return signedCms.Encode(); } //private static bool VerifyMsg(Byte[] msg, byte[] encodedSignature) //{ // ContentInfo contentInfo = new ContentInfo(msg); // SignedCms signedCms = new SignedCms(contentInfo, true); // signedCms.Decode(encodedSignature); // try // { // signedCms.CheckSignature(true); // } // catch (System.Security.Cryptography.CryptographicException e) // { // return false; // } // return true; //} } }
using System; using System.Data; using System.Data.Common; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using NMaier.SimpleDlna.Server; using NMaier.SimpleDlna.Utilities; namespace NMaier.SimpleDlna.FileMediaServer { internal sealed class FileStore : Logging, IDisposable { private const uint SCHEMA = 0x20131101; private static readonly FileStoreVacuumer vacuumer = new FileStoreVacuumer(); private readonly static object globalLock = new object(); private readonly IDbConnection connection; private readonly IDbCommand insert; private readonly IDbDataParameter insertCover; private readonly IDbDataParameter insertData; private readonly IDbDataParameter insertKey; private readonly IDbDataParameter insertSize; private readonly IDbDataParameter insertTime; private readonly IDbCommand select; private readonly IDbDataParameter selectKey; private readonly IDbDataParameter selectSize; private readonly IDbDataParameter selectTime; private readonly IDbCommand selectCover; private readonly IDbDataParameter selectCoverKey; private readonly IDbDataParameter selectCoverSize; private readonly IDbDataParameter selectCoverTime; public readonly FileInfo StoreFile; internal FileStore(FileInfo storeFile) { StoreFile = storeFile; OpenConnection(storeFile, out connection); SetupDatabase(); select = connection.CreateCommand(); select.CommandText = "SELECT data FROM store WHERE key = ? AND size = ? AND time = ?"; select.Parameters.Add(selectKey = select.CreateParameter()); selectKey.DbType = DbType.String; select.Parameters.Add(selectSize = select.CreateParameter()); selectSize.DbType = DbType.Int64; select.Parameters.Add(selectTime = select.CreateParameter()); selectTime.DbType = DbType.Int64; selectCover = connection.CreateCommand(); selectCover.CommandText = "SELECT cover FROM store WHERE key = ? AND size = ? AND time = ?"; selectCover.Parameters.Add(selectCoverKey = select.CreateParameter()); selectCoverKey.DbType = DbType.String; selectCover.Parameters.Add(selectCoverSize = select.CreateParameter()); selectCoverSize.DbType = DbType.Int64; selectCover.Parameters.Add(selectCoverTime = select.CreateParameter()); selectCoverTime.DbType = DbType.Int64; insert = connection.CreateCommand(); insert.CommandText = "INSERT OR REPLACE INTO store VALUES(?,?,?,?,?)"; insert.Parameters.Add(insertKey = select.CreateParameter()); insertKey.DbType = DbType.String; insert.Parameters.Add(insertSize = select.CreateParameter()); insertSize.DbType = DbType.Int64; insert.Parameters.Add(insertTime = select.CreateParameter()); insertTime.DbType = DbType.Int64; insert.Parameters.Add(insertData = select.CreateParameter()); insertData.DbType = DbType.Binary; insert.Parameters.Add(insertCover = select.CreateParameter()); insertCover.DbType = DbType.Binary; InfoFormat("FileStore at {0} is ready", storeFile.FullName); vacuumer.Add(connection); } private void SetupDatabase() { using (var transaction = connection.BeginTransaction()) { using (var pragma = connection.CreateCommand()) { pragma.CommandText = string.Format("PRAGMA user_version = {0}", SCHEMA); pragma.ExecuteNonQuery(); pragma.CommandText = "PRAGMA journal_mode = MEMORY"; pragma.ExecuteNonQuery(); pragma.CommandText = "PRAGMA temp_store = MEMORY"; pragma.ExecuteNonQuery(); pragma.CommandText = "PRAGMA synchonous = OFF"; pragma.ExecuteNonQuery(); } using (var create = connection.CreateCommand()) { create.CommandText = "CREATE TABLE IF NOT EXISTS store (key TEXT PRIMARY KEY ON CONFLICT REPLACE, size INT, time INT, data BINARY, cover BINARY)"; create.ExecuteNonQuery(); } transaction.Commit(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] private void OpenConnection(FileInfo storeFile, out IDbConnection newConnection) { lock (globalLock) { newConnection = Sqlite.GetDatabaseConnection(storeFile); try { using (var ver = newConnection.CreateCommand()) { ver.CommandText = "PRAGMA user_version"; var currentVersion = (uint)(long)ver.ExecuteScalar(); if (!currentVersion.Equals(SCHEMA)) { throw new ArgumentOutOfRangeException("SCHEMA"); } } } catch (Exception ex) { NoticeFormat( "Recreating database, schema update. ({0})", ex.Message ); Sqlite.ClearPool(newConnection); newConnection.Close(); newConnection.Dispose(); newConnection = null; for (var i = 0; i < 10; ++i) { try { GC.Collect(); storeFile.Delete(); break; } catch (IOException) { Thread.Sleep(100); } } newConnection = Sqlite.GetDatabaseConnection(storeFile); } } } public void Dispose() { if (insert != null) { insert.Dispose(); } if (select != null) { select.Dispose(); } if (connection != null) { vacuumer.Remove(connection); Sqlite.ClearPool(connection); connection.Dispose(); } } internal BaseFile MaybeGetFile(FileServer server, FileInfo info, DlnaMime type) { if (connection == null) { return null; } byte[] data; lock (connection) { selectKey.Value = info.FullName; selectSize.Value = info.Length; selectTime.Value = info.LastWriteTimeUtc.Ticks; try { data = select.ExecuteScalar() as byte[]; } catch (DbException ex) { Error("Failed to lookup file from store", ex); return null; } } if (data == null) { return null; } try { using (var s = new MemoryStream(data)) { var ctx = new StreamingContext( StreamingContextStates.Persistence, new DeserializeInfo(server, info, type)); var formatter = new BinaryFormatter(null, ctx) { TypeFormat = FormatterTypeStyle.TypesWhenNeeded, AssemblyFormat = FormatterAssemblyStyle.Simple }; var rv = formatter.Deserialize(s) as BaseFile; rv.Item = info; return rv; } } catch (Exception ex) { if (ex is TargetInvocationException || ex is SerializationException) { Debug("Failed to deserialize an item", ex); return null; } throw; } } internal bool HasCover(BaseFile file) { if (connection == null) { return false; } var info = file.Item; lock (connection) { selectCoverKey.Value = info.FullName; selectCoverSize.Value = info.Length; selectCoverTime.Value = info.LastWriteTimeUtc.Ticks; try { var data = selectCover.ExecuteScalar(); return (data as byte[]) != null; } catch (DbException ex) { Error("Failed to lookup file cover existence from store", ex); return false; } } } internal Cover MaybeGetCover(BaseFile file) { if (connection == null) { return null; } var info = file.Item; byte[] data; lock (connection) { selectCoverKey.Value = info.FullName; selectCoverSize.Value = info.Length; selectCoverTime.Value = info.LastWriteTimeUtc.Ticks; try { data = selectCover.ExecuteScalar() as byte[]; } catch (DbException ex) { Error("Failed to lookup file cover from store", ex); return null; } } if (data == null) { return null; } try { using (var s = new MemoryStream(data)) { var ctx = new StreamingContext( StreamingContextStates.Persistence, new DeserializeInfo(null, info, DlnaMime.JPEG) ); var formatter = new BinaryFormatter(null, ctx) { TypeFormat = FormatterTypeStyle.TypesWhenNeeded, AssemblyFormat = FormatterAssemblyStyle.Simple }; var rv = formatter.Deserialize(s) as Cover; return rv; } } catch (SerializationException ex) { Debug("Failed to deserialize a cover", ex); return null; } catch (Exception ex) { Fatal("Failed to deserialize a cover", ex); throw; } } internal void MaybeStoreFile(BaseFile file) { if (connection == null) { return; } if (!file.GetType().Attributes.HasFlag(TypeAttributes.Serializable)) { return; } try { using (var s = new MemoryStream()) { var ctx = new StreamingContext( StreamingContextStates.Persistence, null ); var formatter = new BinaryFormatter(null, ctx) { TypeFormat = FormatterTypeStyle.TypesWhenNeeded, AssemblyFormat = FormatterAssemblyStyle.Simple }; formatter.Serialize(s, file); lock (connection) { insertKey.Value = file.Item.FullName; insertSize.Value = file.Item.Length; insertTime.Value = file.Item.LastWriteTimeUtc.Ticks; insertData.Value = s.ToArray(); var cover = file.MaybeGetCover(); if (cover != null) { using (var c = new MemoryStream()) { formatter.Serialize(c, cover); insertCover.Value = c.ToArray(); } } else { insertCover.Value = null; } try { insert.ExecuteNonQuery(); } catch (DbException ex) { Error("Failed to put file cover into store", ex); return; } } } } catch (Exception ex) { Error("Failed to serialize an object of type " + file.GetType(), ex); throw; } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// SMS Recipients Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SPREPLYDataSet : EduHubDataSet<SPREPLY> { /// <inheritdoc /> public override string Name { get { return "SPREPLY"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SPREPLYDataSet(EduHubContext Context) : base(Context) { Index_CODE = new Lazy<Dictionary<int, IReadOnlyList<SPREPLY>>>(() => this.ToGroupedDictionary(i => i.CODE)); Index_TID = new Lazy<Dictionary<int, SPREPLY>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SPREPLY" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SPREPLY" /> fields for each CSV column header</returns> internal override Action<SPREPLY, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SPREPLY, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "CODE": mapper[i] = (e, v) => e.CODE = int.Parse(v); break; case "SPRECIP_TID": mapper[i] = (e, v) => e.SPRECIP_TID = v == null ? (int?)null : int.Parse(v); break; case "MESSAGE": mapper[i] = (e, v) => e.MESSAGE = v; break; case "PHONE_NUMBER": mapper[i] = (e, v) => e.PHONE_NUMBER = v; break; case "RECEIVED_DATE": mapper[i] = (e, v) => e.RECEIVED_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SPREPLY" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SPREPLY" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SPREPLY" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SPREPLY}"/> of entities</returns> internal override IEnumerable<SPREPLY> ApplyDeltaEntities(IEnumerable<SPREPLY> Entities, List<SPREPLY> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.CODE; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.CODE.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, IReadOnlyList<SPREPLY>>> Index_CODE; private Lazy<Dictionary<int, SPREPLY>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SPREPLY by CODE field /// </summary> /// <param name="CODE">CODE value used to find SPREPLY</param> /// <returns>List of related SPREPLY entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SPREPLY> FindByCODE(int CODE) { return Index_CODE.Value[CODE]; } /// <summary> /// Attempt to find SPREPLY by CODE field /// </summary> /// <param name="CODE">CODE value used to find SPREPLY</param> /// <param name="Value">List of related SPREPLY entities</param> /// <returns>True if the list of related SPREPLY entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCODE(int CODE, out IReadOnlyList<SPREPLY> Value) { return Index_CODE.Value.TryGetValue(CODE, out Value); } /// <summary> /// Attempt to find SPREPLY by CODE field /// </summary> /// <param name="CODE">CODE value used to find SPREPLY</param> /// <returns>List of related SPREPLY entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SPREPLY> TryFindByCODE(int CODE) { IReadOnlyList<SPREPLY> value; if (Index_CODE.Value.TryGetValue(CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find SPREPLY by TID field /// </summary> /// <param name="TID">TID value used to find SPREPLY</param> /// <returns>Related SPREPLY entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SPREPLY FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SPREPLY by TID field /// </summary> /// <param name="TID">TID value used to find SPREPLY</param> /// <param name="Value">Related SPREPLY entity</param> /// <returns>True if the related SPREPLY entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SPREPLY Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SPREPLY by TID field /// </summary> /// <param name="TID">TID value used to find SPREPLY</param> /// <returns>Related SPREPLY entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SPREPLY TryFindByTID(int TID) { SPREPLY value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SPREPLY table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SPREPLY]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SPREPLY]( [TID] int IDENTITY NOT NULL, [CODE] int NOT NULL, [SPRECIP_TID] int NULL, [MESSAGE] varchar(255) NULL, [PHONE_NUMBER] varchar(20) NULL, [RECEIVED_DATE] datetime NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SPREPLY_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [SPREPLY_Index_CODE] ON [dbo].[SPREPLY] ( [CODE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SPREPLY]') AND name = N'SPREPLY_Index_TID') ALTER INDEX [SPREPLY_Index_TID] ON [dbo].[SPREPLY] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SPREPLY]') AND name = N'SPREPLY_Index_TID') ALTER INDEX [SPREPLY_Index_TID] ON [dbo].[SPREPLY] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SPREPLY"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SPREPLY"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SPREPLY> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SPREPLY] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SPREPLY data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SPREPLY data set</returns> public override EduHubDataSetDataReader<SPREPLY> GetDataSetDataReader() { return new SPREPLYDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SPREPLY data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SPREPLY data set</returns> public override EduHubDataSetDataReader<SPREPLY> GetDataSetDataReader(List<SPREPLY> Entities) { return new SPREPLYDataReader(new EduHubDataSetLoadedReader<SPREPLY>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SPREPLYDataReader : EduHubDataSetDataReader<SPREPLY> { public SPREPLYDataReader(IEduHubDataSetReader<SPREPLY> Reader) : base (Reader) { } public override int FieldCount { get { return 9; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // CODE return Current.CODE; case 2: // SPRECIP_TID return Current.SPRECIP_TID; case 3: // MESSAGE return Current.MESSAGE; case 4: // PHONE_NUMBER return Current.PHONE_NUMBER; case 5: // RECEIVED_DATE return Current.RECEIVED_DATE; case 6: // LW_DATE return Current.LW_DATE; case 7: // LW_TIME return Current.LW_TIME; case 8: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // SPRECIP_TID return Current.SPRECIP_TID == null; case 3: // MESSAGE return Current.MESSAGE == null; case 4: // PHONE_NUMBER return Current.PHONE_NUMBER == null; case 5: // RECEIVED_DATE return Current.RECEIVED_DATE == null; case 6: // LW_DATE return Current.LW_DATE == null; case 7: // LW_TIME return Current.LW_TIME == null; case 8: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // CODE return "CODE"; case 2: // SPRECIP_TID return "SPRECIP_TID"; case 3: // MESSAGE return "MESSAGE"; case 4: // PHONE_NUMBER return "PHONE_NUMBER"; case 5: // RECEIVED_DATE return "RECEIVED_DATE"; case 6: // LW_DATE return "LW_DATE"; case 7: // LW_TIME return "LW_TIME"; case 8: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "CODE": return 1; case "SPRECIP_TID": return 2; case "MESSAGE": return 3; case "PHONE_NUMBER": return 4; case "RECEIVED_DATE": return 5; case "LW_DATE": return 6; case "LW_TIME": return 7; case "LW_USER": return 8; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections.Generic; using fNbt; using fNbt.Serialization; using TrueCraft.API.World; using TrueCraft.API; using TrueCraft.Core.Logic.Blocks; namespace TrueCraft.Core.World { public class Chunk : INbtSerializable, IChunk { public const int Width = 16, Height = 128, Depth = 16; private static readonly NbtSerializer Serializer = new NbtSerializer(typeof(Chunk)); [NbtIgnore] public DateTime LastAccessed { get; set; } [NbtIgnore] public bool IsModified { get; set; } [NbtIgnore] public byte[] Blocks { get; set; } [NbtIgnore] public NibbleArray Metadata { get; set; } [NbtIgnore] public NibbleArray BlockLight { get; set; } [NbtIgnore] public NibbleArray SkyLight { get; set; } public byte[] Biomes { get; set; } public int[] HeightMap { get; set; } [TagName("xPos")] public int X { get; set; } [TagName("zPos")] public int Z { get; set; } public Dictionary<Coordinates3D, NbtCompound> TileEntities { get; set; } public Coordinates2D Coordinates { get { return new Coordinates2D(X, Z); } set { X = value.X; Z = value.Z; } } public long LastUpdate { get; set; } public bool TerrainPopulated { get; set; } [NbtIgnore] public Region ParentRegion { get; set; } public Chunk() { TerrainPopulated = true; Biomes = new byte[Width * Depth]; HeightMap = new int[Width * Depth]; LastAccessed = DateTime.Now; TileEntities = new Dictionary<Coordinates3D, NbtCompound>(); } public Chunk(Coordinates2D coordinates) : this() { X = coordinates.X; Z = coordinates.Z; const int size = Width * Height * Depth; Blocks = new byte[size]; Metadata = new NibbleArray(size); BlockLight = new NibbleArray(size); SkyLight = new NibbleArray(size); for (int i = 0; i < size; i++) SkyLight[i] = 0xFF; } public byte GetBlockID(Coordinates3D coordinates) { LastAccessed = DateTime.Now; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); return Blocks[index]; } public byte GetMetadata(Coordinates3D coordinates) { LastAccessed = DateTime.Now; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); return Metadata[index]; } public byte GetSkyLight(Coordinates3D coordinates) { LastAccessed = DateTime.Now; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); return SkyLight[index]; } public byte GetBlockLight(Coordinates3D coordinates) { LastAccessed = DateTime.Now; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); return BlockLight[index]; } /// <summary> /// Sets the block ID at specific coordinates relative to this chunk. /// Warning: The parent world's BlockChanged event handler does not get called. /// </summary> public void SetBlockID(Coordinates3D coordinates, byte value) { LastAccessed = DateTime.Now; IsModified = true; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); Blocks[index] = value; if (value == AirBlock.BlockID) Metadata[index] = 0x0; var oldHeight = GetHeight((byte)coordinates.X, (byte)coordinates.Z); if (value == AirBlock.BlockID) { if (oldHeight <= coordinates.Y) { // Shift height downwards while (coordinates.Y > 0) { coordinates.Y--; if (GetBlockID(coordinates) != 0) SetHeight((byte)coordinates.X, (byte)coordinates.Z, coordinates.Y); } } } else { if (oldHeight < coordinates.Y) SetHeight((byte)coordinates.X, (byte)coordinates.Z, coordinates.Y); } } /// <summary> /// Sets the metadata at specific coordinates relative to this chunk. /// Warning: The parent world's BlockChanged event handler does not get called. /// </summary> public void SetMetadata(Coordinates3D coordinates, byte value) { LastAccessed = DateTime.Now; IsModified = true; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); Metadata[index] = value; } /// <summary> /// Sets the sky light at specific coordinates relative to this chunk. /// Warning: The parent world's BlockChanged event handler does not get called. /// </summary> public void SetSkyLight(Coordinates3D coordinates, byte value) { LastAccessed = DateTime.Now; IsModified = true; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); SkyLight[index] = value; } /// <summary> /// Sets the block light at specific coordinates relative to this chunk. /// Warning: The parent world's BlockChanged event handler does not get called. /// </summary> public void SetBlockLight(Coordinates3D coordinates, byte value) { LastAccessed = DateTime.Now; IsModified = true; int index = coordinates.Y + (coordinates.Z * Height) + (coordinates.X * Height * Width); BlockLight[index] = value; } /// <summary> /// Gets the tile entity for the given coordinates. May return null. /// </summary> public NbtCompound GetTileEntity(Coordinates3D coordinates) { LastAccessed = DateTime.Now; if (TileEntities.ContainsKey(coordinates)) return TileEntities[coordinates]; return null; } /// <summary> /// Sets the tile entity at the given coordinates to the given value. /// </summary> public void SetTileEntity(Coordinates3D coordinates, NbtCompound value) { LastAccessed = DateTime.Now; TileEntities[coordinates] = value; IsModified = true; } /// <summary> /// Gets the height of the specified column. /// </summary> public int GetHeight(byte x, byte z) { LastAccessed = DateTime.Now; return HeightMap[(byte)(x * Width) + z]; } private void SetHeight(byte x, byte z, int value) { LastAccessed = DateTime.Now; IsModified = true; HeightMap[(byte)(x * Width) + z] = value; } public void UpdateHeightMap() { for (byte x = 0; x < Chunk.Width; x++) { for (byte z = 0; z < Chunk.Depth; z++) { int y; for (y = Chunk.Height - 1; y >= 0; y--) { int index = y + (z * Height) + (x * Height * Width); if (Blocks[index] != 0) { SetHeight(x, z, y); break; } } if (y == 0) SetHeight(x, z, 0); } } } public NbtFile ToNbt() { LastAccessed = DateTime.Now; var serializer = new NbtSerializer(typeof(Chunk)); var compound = serializer.Serialize(this, "Level") as NbtCompound; var file = new NbtFile(); file.RootTag.Add(compound); return file; } public static Chunk FromNbt(NbtFile nbt) { var serializer = new NbtSerializer(typeof(Chunk)); var chunk = (Chunk)serializer.Deserialize(nbt.RootTag["Level"]); return chunk; } public NbtTag Serialize(string tagName) { var chunk = new NbtCompound(tagName); var entities = new NbtList("Entities", NbtTagType.Compound); chunk.Add(entities); chunk.Add(new NbtInt("X", X)); chunk.Add(new NbtInt("Z", Z)); chunk.Add(new NbtByteArray("Blocks", Blocks)); chunk.Add(new NbtByteArray("Data", Metadata.Data)); chunk.Add(new NbtByteArray("SkyLight", SkyLight.Data)); chunk.Add(new NbtByteArray("BlockLight", BlockLight.Data)); var tiles = new NbtList("TileEntities", NbtTagType.Compound); foreach (var kvp in TileEntities) { var c = new NbtCompound(); c.Add(new NbtList("coordinates", new[] { new NbtInt(kvp.Key.X), new NbtInt(kvp.Key.Y), new NbtInt(kvp.Key.Z) })); c.Add(new NbtList("value", new[] { kvp.Value })); tiles.Add(c); } chunk.Add(tiles); // TODO: Entities return chunk; } public void Deserialize(NbtTag value) { var chunk = new Chunk(); var tag = (NbtCompound)value; Biomes = chunk.Biomes; HeightMap = chunk.HeightMap; LastUpdate = chunk.LastUpdate; TerrainPopulated = chunk.TerrainPopulated; X = tag["X"].IntValue; Z = tag["Z"].IntValue; Blocks = tag["Blocks"].ByteArrayValue; Metadata = new NibbleArray(); Metadata.Data = tag["Data"].ByteArrayValue; BlockLight = new NibbleArray(); BlockLight.Data = tag["BlockLight"].ByteArrayValue; SkyLight = new NibbleArray(); SkyLight.Data = tag["SkyLight"].ByteArrayValue; if (tag.Contains("TileEntities")) { foreach (var entity in tag["TileEntities"] as NbtList) { TileEntities[new Coordinates3D(entity["coordinates"][0].IntValue, entity["coordinates"][1].IntValue, entity["coordinates"][2].IntValue)] = entity["value"][0] as NbtCompound; } } // TODO: Tile entities, entities } } }
// 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.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml; using mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.BlogClient; namespace OpenLiveWriter.BlogClient.Detection { public class RsdServiceDetector { public static RsdServiceDescription DetectFromWeblog(string homepage, IHTMLDocument2 weblogDOM ) { try { // get the edit uri string rsdFileUrl = ExtractEditUri(homepage, weblogDOM ) ; // do the detection if ( rsdFileUrl != null ) return DetectFromRsdUrl( rsdFileUrl ) ; else return null ; } catch( Exception ex ) { Trace.Fail( "Unexpected error attempting to detect Blog service: " + ex.ToString() ); return null ; } } public static RsdServiceDescription DetectFromRsdUrl( string rsdFileUrl ) { try { // see if we can download a local copy of the RSD file using ( Stream rsdStream = HttpRequestHelper.SafeDownloadFile( rsdFileUrl ) ) { // if we got an RSD file then read the service info from there if ( rsdStream != null ) { return ReadFromRsdStream( rsdStream, rsdFileUrl ) ; } else { // if we couldn't do a successful RSD detection then return null return null ; } } } catch(Exception ex) { Trace.Fail( "Unexpected error attempting to detect Blog service: " + ex.ToString() ); return null ; } } /// <summary> /// Try to extract the EditUri (RSD file URI) from the passed DOM /// </summary> /// <param name="weblogDOM"></param> /// <returns></returns> private static string ExtractEditUri(string homepageUrl, IHTMLDocument2 weblogDOM) { // look in the first HEAD tag IHTMLElementCollection headElements = ((IHTMLDocument3)weblogDOM).getElementsByTagName( "HEAD" ) ; if ( headElements.length > 0 ) { // get the first head element IHTMLElement2 firstHeadElement = (IHTMLElement2)headElements.item(0,0); // look for link tags within the head foreach ( IHTMLElement element in firstHeadElement.getElementsByTagName( "LINK" ) ) { IHTMLLinkElement linkElement = element as IHTMLLinkElement ; if ( linkElement != null ) { string linkRel = linkElement.rel ; if ( linkRel != null && (linkRel.ToUpperInvariant().Equals("EDITURI") ) ) { return UrlHelper.UrlCombineIfRelative(homepageUrl, linkElement.href); } } } } // couldn't find one return null ; } /// <summary> /// Skips leading whitespace in a reader. /// </summary> /// <param name="reader"></param> /// <returns></returns> private static TextReader SkipLeadingWhitespace(TextReader reader) { while (true) { int c = reader.Peek(); if (c != -1 && char.IsWhiteSpace((char) c)) reader.Read(); else return reader; } } /// <summary> /// Read the definition of a blog service from the passed RSD XML /// </summary> /// <param name="rsdStream"></param> /// <returns></returns> private static RsdServiceDescription ReadFromRsdStream( Stream rsdStream, string url ) { // initialize a blog service to return RsdServiceDescription rsdServiceDescription = new RsdServiceDescription(); rsdServiceDescription.SourceUrl = url ; ArrayList blogApis = new ArrayList() ; try { // liberally parse the RSD xml XmlReader reader = new XmlTextReader( SkipLeadingWhitespace(new StreamReader(rsdStream, new UTF8Encoding(false, false))) ) ; while ( reader.Read() ) { if ( reader.NodeType == XmlNodeType.Element ) { // windows-live writer extensions to rsd if ( UrlHelper.UrlsAreEqual( reader.NamespaceURI, WINDOWS_LIVE_WRITER_NAMESPACE ) ) { /* switch ( reader.LocalName.ToLower() ) { case "manifestlink": rsdServiceDescription.WriterManifestUrl = reader.ReadString().Trim() ; break; } */ } // standard rsd elements else { switch( reader.LocalName.ToUpperInvariant() ) { case "ENGINENAME": rsdServiceDescription.EngineName = reader.ReadString().Trim() ; break; case "ENGINELINK": rsdServiceDescription.EngineLink = ToAbsoluteUrl(url, reader.ReadString().Trim()) ; break; case "HOMEPAGELINK": rsdServiceDescription.HomepageLink = ToAbsoluteUrl(url, reader.ReadString().Trim()) ; break; case "API": RsdApi api = new RsdApi() ; for ( int i=0; i<reader.AttributeCount; i++ ) { reader.MoveToAttribute(i) ; switch ( reader.LocalName.ToUpperInvariant()) { case "NAME": api.Name = NormalizeApiName(reader.Value); break; case "PREFERRED": api.Preferred = "true" == reader.Value.Trim() ; break; case "APILINK": case "RPCLINK": // radio-userland uses rpcLink api.ApiLink = ToAbsoluteUrl(url, reader.Value.Trim()) ; break; case "BLOGID": api.BlogId = reader.Value.Trim() ; break; } } blogApis.Add( api ) ; break; case "SETTING": if ( blogApis.Count > 0 ) { RsdApi lastRsdApi = (RsdApi)blogApis[blogApis.Count-1] ; string name = reader.GetAttribute("name") ; if ( name != null ) { string value = reader.ReadString().Trim(); lastRsdApi.Settings.Add(name, value); } } break; } } } } } catch( Exception ex ) { Trace.Fail("Exception attempting to read RSD file: " + ex.ToString()) ; // don't re-propagate exceptions here becaus we found that TypePad's // RSD file was returning bogus HTTP crap at the end of the response // and the XML parser cholking on this caused us to fail autodetection } // if we got at least one API then return the service description if ( blogApis.Count > 0 ) { rsdServiceDescription.Apis = (RsdApi[]) blogApis.ToArray(typeof(RsdApi)) ; return rsdServiceDescription ; } else { return null ; } } private static string ToAbsoluteUrl(string baseUrl, string url) { if(!UrlHelper.IsUrl(url)) { url = UrlHelper.EscapeRelativeURL(baseUrl, url); } return url; } private static string NormalizeApiName(string name) { string nName = name.Trim().ToLower(CultureInfo.InvariantCulture); if ( nName == "movable type") // typepad uses no space, wordpress uses a space, and so on... nName = "movabletype" ; return nName; } private const string WINDOWS_LIVE_WRITER_NAMESPACE = "http://www.microsoft.com/schemas/livewriter" ; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { private class MoveTypeEditor : Editor { public MoveTypeEditor( TService service, State state, string fileName, CancellationToken cancellationToken) : base(service, state, fileName, cancellationToken) { } /// <summary> /// Given a document and a type contained in it, moves the type /// out to its own document. The new document's name typically /// is the type name, or is at least based on the type name. /// </summary> /// <remarks> /// The algorithm for this, is as follows: /// 1. Fork the original document that contains the type to be moved. /// 2. Keep the type, required namespace containers and using statements. /// remove everything else from the forked document. /// 3. Add this forked document to the solution. /// 4. Finally, update the original document and remove the type from it. /// </remarks> internal override async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = SemanticDocument.Document.Project.Solution; // Fork, update and add as new document. var projectToBeUpdated = SemanticDocument.Document.Project; var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, FileName); var documentWithMovedType = await AddNewDocumentWithSingleTypeDeclarationAndImportsAsync(newDocumentId).ConfigureAwait(false); var solutionWithNewDocument = documentWithMovedType.Project.Solution; // Get the original source document again, from the latest forked solution. var sourceDocument = solutionWithNewDocument.GetDocument(SemanticDocument.Document.Id); // update source document to add partial modifiers to type chain // and/or remove type declaration from original source document. var solutionWithBothDocumentsUpdated = await RemoveTypeFromSourceDocumentAsync( sourceDocument, documentWithMovedType).ConfigureAwait(false); return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solutionWithBothDocumentsUpdated)); } /// <summary> /// Forks the source document, keeps required type, namespace containers /// and adds it the solution. /// </summary> /// <param name="newDocumentId">id for the new document to be added</param> /// <returns>the new solution which contains a new document with the type being moved</returns> private async Task<Document> AddNewDocumentWithSingleTypeDeclarationAndImportsAsync( DocumentId newDocumentId) { var document = SemanticDocument.Document; Debug.Assert(document.Name != FileName, $"New document name is same as old document name:{FileName}"); var root = SemanticDocument.Root; var projectToBeUpdated = document.Project; var documentEditor = await DocumentEditor.CreateAsync(document, CancellationToken).ConfigureAwait(false); // Make the type chain above this new type partial. Also, remove any // attributes from the containing partial types. We don't want to create // duplicate attributes on things. AddPartialModifiersToTypeChain( documentEditor, removeAttributesAndComments: true, removeTypeInheritance: true); // remove things that are not being moved, from the forked document. var membersToRemove = GetMembersToRemove(root); foreach (var member in membersToRemove) { documentEditor.RemoveNode(member, SyntaxRemoveOptions.KeepNoTrivia); } var modifiedRoot = documentEditor.GetChangedRoot(); modifiedRoot = await AddFinalNewLineIfDesired(document, modifiedRoot).ConfigureAwait(false); // add an empty document to solution, so that we'll have options from the right context. var solutionWithNewDocument = projectToBeUpdated.Solution.AddDocument( newDocumentId, FileName, text: string.Empty, folders: document.Folders); // update the text for the new document solutionWithNewDocument = solutionWithNewDocument.WithDocumentSyntaxRoot(newDocumentId, modifiedRoot, PreservationMode.PreserveIdentity); // get the updated document, give it the minimal set of imports that the type // inside it needs. var service = document.GetLanguageService<IRemoveUnnecessaryImportsService>(); var newDocument = solutionWithNewDocument.GetDocument(newDocumentId); newDocument = await service.RemoveUnnecessaryImportsAsync(newDocument, CancellationToken).ConfigureAwait(false); return newDocument; } /// <summary> /// Add a trailing newline if we don't already have one if that's what the user's /// preference is. /// </summary> private async Task<SyntaxNode> AddFinalNewLineIfDesired(Document document, SyntaxNode modifiedRoot) { var options = await document.GetOptionsAsync(CancellationToken).ConfigureAwait(false); var insertFinalNewLine = options.GetOption(FormattingOptions.InsertFinalNewLine); if (insertFinalNewLine) { var endOfFileToken = ((ICompilationUnitSyntax)modifiedRoot).EndOfFileToken; var previousToken = endOfFileToken.GetPreviousToken(includeZeroWidth: true, includeSkipped: true); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (endOfFileToken.LeadingTrivia.IsEmpty() && !previousToken.TrailingTrivia.Any(syntaxFacts.IsEndOfLineTrivia)) { var generator = SyntaxGenerator.GetGenerator(document); var endOfLine = generator.EndOfLine(options.GetOption(FormattingOptions.NewLine)); return modifiedRoot.ReplaceToken( previousToken, previousToken.WithAppendedTrailingTrivia(endOfLine)); } } return modifiedRoot; } /// <summary> /// update the original document and remove the type that was moved. /// perform other fix ups as necessary. /// </summary> /// <returns>an updated solution with the original document fixed up as appropriate.</returns> private async Task<Solution> RemoveTypeFromSourceDocumentAsync( Document sourceDocument, Document documentWithMovedType) { var documentEditor = await DocumentEditor.CreateAsync(sourceDocument, CancellationToken).ConfigureAwait(false); // Make the type chain above the type we're moving 'partial'. // However, keep all the attributes on these types as theses are the // original attributes and we don't want to mess with them. AddPartialModifiersToTypeChain(documentEditor, removeAttributesAndComments: false, removeTypeInheritance: false); documentEditor.RemoveNode(State.TypeNode, SyntaxRemoveOptions.KeepNoTrivia); var updatedDocument = documentEditor.GetChangedDocument(); // Now, remove any imports that we no longer need *if* they were used in the new // file with the moved type. Essentially, those imports were here just to serve // that new type and we should remove them. If we have *other* imports that // other file does not use *and* we do not use, we'll still keep those around. // Those may be important to the user for code they're about to write, and we // don't want to interfere with them by removing them. var service = sourceDocument.GetLanguageService<IRemoveUnnecessaryImportsService>(); var syntaxFacts = sourceDocument.GetLanguageService<ISyntaxFactsService>(); var rootWithMovedType = await documentWithMovedType.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false); var movedImports = rootWithMovedType.DescendantNodes() .Where(syntaxFacts.IsUsingOrExternOrImport) .ToImmutableArray(); Func<SyntaxNode, bool> predicate = n => movedImports.Contains(i => i.IsEquivalentTo(n)); updatedDocument = await service.RemoveUnnecessaryImportsAsync( updatedDocument, predicate, CancellationToken).ConfigureAwait(false); return updatedDocument.Project.Solution; } /// <summary> /// Traverses the syntax tree of the forked document and /// collects a list of nodes that are not being moved. /// This list of nodes are then removed from the forked copy. /// </summary> /// <param name="root">root, of the syntax tree of forked document</param> /// <returns>list of syntax nodes, to be removed from the forked copy.</returns> private ISet<SyntaxNode> GetMembersToRemove(SyntaxNode root) { var spine = new HashSet<SyntaxNode>(); // collect the parent chain of declarations to keep. spine.AddRange(State.TypeNode.GetAncestors()); // get potential namespace, types and members to remove. var removableCandidates = root .DescendantNodes(n => spine.Contains(n)) .Where(n => FilterToTopLevelMembers(n, State.TypeNode)).ToSet(); // diff candidates with items we want to keep. removableCandidates.ExceptWith(spine); #if DEBUG // None of the nodes we're removing should also have any of their parent // nodes removed. If that happened we could get a crash by first trying to remove // the parent, then trying to remove the child. foreach (var node in removableCandidates) { foreach (var ancestor in node.GetAncestors()) { Debug.Assert(!removableCandidates.Contains(ancestor)); } } #endif return removableCandidates; } private static bool FilterToTopLevelMembers(SyntaxNode node, SyntaxNode typeNode) { // We never filter out the actual node we're trying to keep around. if (node == typeNode) { return false; } return node is TTypeDeclarationSyntax || node is TMemberDeclarationSyntax || node is TNamespaceDeclarationSyntax; } /// <summary> /// if a nested type is being moved, this ensures its containing type is partial. /// </summary> private void AddPartialModifiersToTypeChain( DocumentEditor documentEditor, bool removeAttributesAndComments, bool removeTypeInheritance) { var semanticFacts = State.SemanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var typeChain = State.TypeNode.Ancestors().OfType<TTypeDeclarationSyntax>(); foreach (var node in typeChain) { var symbol = (ITypeSymbol)State.SemanticDocument.SemanticModel.GetDeclaredSymbol(node, CancellationToken); if (!semanticFacts.IsPartial(symbol, CancellationToken)) { documentEditor.SetModifiers(node, documentEditor.Generator.GetModifiers(node) | DeclarationModifiers.Partial); } if (removeAttributesAndComments) { documentEditor.RemoveAllAttributes(node); documentEditor.RemoveAllComments(node); } if (removeTypeInheritance) { documentEditor.RemoveAllTypeInheritance(node); } } documentEditor.ReplaceNode(State.TypeNode, (currentNode, generator) => { var currentTypeNode = (TTypeDeclarationSyntax)currentNode; // Trim leading whitespace from the type so we don't have excessive // leading blank lines. return RemoveLeadingWhitespace(currentTypeNode); }); } private TTypeDeclarationSyntax RemoveLeadingWhitespace( TTypeDeclarationSyntax currentTypeNode) { var syntaxFacts = State.SemanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); var leadingTrivia = currentTypeNode.GetLeadingTrivia(); var afterWhitespace = leadingTrivia.SkipWhile( t => syntaxFacts.IsWhitespaceTrivia(t) || syntaxFacts.IsEndOfLineTrivia(t)); var withoutLeadingWhitespace = currentTypeNode.WithLeadingTrivia(afterWhitespace); return withoutLeadingWhitespace.ReplaceToken( withoutLeadingWhitespace.GetFirstToken(), withoutLeadingWhitespace.GetFirstToken().WithAdditionalAnnotations(Formatter.Annotation)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Globalization; using System.Text; namespace System.Net.Http.Headers { public class ContentRangeHeaderValue : ICloneable { private string _unit; private long? _from; private long? _to; private long? _length; public string Unit { get { return _unit; } set { HeaderUtilities.CheckValidToken(value, "value"); _unit = value; } } public long? From { get { return _from; } } public long? To { get { return _to; } } public long? Length { get { return _length; } } public bool HasLength // e.g. "Content-Range: bytes 12-34/*" { get { return _length != null; } } public bool HasRange // e.g. "Content-Range: bytes */1234" { get { return _from != null; } } public ContentRangeHeaderValue(long from, long to, long length) { // Scenario: "Content-Range: bytes 12-34/5678" if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if ((to < 0) || (to > length)) { throw new ArgumentOutOfRangeException(nameof(to)); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(from)); } _from = from; _to = to; _length = length; _unit = HeaderUtilities.BytesUnit; } public ContentRangeHeaderValue(long length) { // Scenario: "Content-Range: bytes */1234" if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } _length = length; _unit = HeaderUtilities.BytesUnit; } public ContentRangeHeaderValue(long from, long to) { // Scenario: "Content-Range: bytes 12-34/*" if (to < 0) { throw new ArgumentOutOfRangeException(nameof(to)); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(from)); } _from = from; _to = to; _unit = HeaderUtilities.BytesUnit; } private ContentRangeHeaderValue() { } private ContentRangeHeaderValue(ContentRangeHeaderValue source) { Contract.Requires(source != null); _from = source._from; _to = source._to; _length = source._length; _unit = source._unit; } public override bool Equals(object obj) { ContentRangeHeaderValue other = obj as ContentRangeHeaderValue; if (other == null) { return false; } return ((_from == other._from) && (_to == other._to) && (_length == other._length) && string.Equals(_unit, other._unit, StringComparison.OrdinalIgnoreCase)); } public override int GetHashCode() { int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_unit); if (HasRange) { result = result ^ _from.GetHashCode() ^ _to.GetHashCode(); } if (HasLength) { result = result ^ _length.GetHashCode(); } return result; } public override string ToString() { StringBuilder sb = new StringBuilder(_unit); sb.Append(' '); if (HasRange) { sb.Append(_from.Value.ToString(NumberFormatInfo.InvariantInfo)); sb.Append('-'); sb.Append(_to.Value.ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } sb.Append('/'); if (HasLength) { sb.Append(_length.Value.ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } return sb.ToString(); } public static ContentRangeHeaderValue Parse(string input) { int index = 0; return (ContentRangeHeaderValue)GenericHeaderParser.ContentRangeParser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out ContentRangeHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.ContentRangeParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (ContentRangeHeaderValue)output; return true; } return false; } internal static int GetContentRangeLength(string input, int startIndex, out object parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the unit string: <unit> in '<unit> <from>-<to>/<length>' int unitLength = HttpRuleParser.GetTokenLength(input, startIndex); if (unitLength == 0) { return 0; } string unit = input.Substring(startIndex, unitLength); int current = startIndex + unitLength; int separatorLength = HttpRuleParser.GetWhitespaceLength(input, current); if (separatorLength == 0) { return 0; } current = current + separatorLength; if (current == input.Length) { return 0; } // Read range values <from> and <to> in '<unit> <from>-<to>/<length>' int fromStartIndex = current; int fromLength = 0; int toStartIndex = 0; int toLength = 0; if (!TryGetRangeLength(input, ref current, out fromLength, out toStartIndex, out toLength)) { return 0; } // After the range is read we expect the length separator '/' if ((current == input.Length) || (input[current] != '/')) { return 0; } current++; // Skip '/' separator current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return 0; } // We may not have a length (e.g. 'bytes 1-2/*'). But if we do, parse the length now. int lengthStartIndex = current; int lengthLength = 0; if (!TryGetLengthLength(input, ref current, out lengthLength)) { return 0; } if (!TryCreateContentRange(input, unit, fromStartIndex, fromLength, toStartIndex, toLength, lengthStartIndex, lengthLength, out parsedValue)) { return 0; } return current - startIndex; } private static bool TryGetLengthLength(string input, ref int current, out int lengthLength) { lengthLength = 0; if (input[current] == '*') { current++; } else { // Parse length value: <length> in '<unit> <from>-<to>/<length>' lengthLength = HttpRuleParser.GetNumberLength(input, current, false); if ((lengthLength == 0) || (lengthLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + lengthLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryGetRangeLength(string input, ref int current, out int fromLength, out int toStartIndex, out int toLength) { fromLength = 0; toStartIndex = 0; toLength = 0; // Check if we have a value like 'bytes */133'. If yes, skip the range part and continue parsing the // length separator '/'. if (input[current] == '*') { current++; } else { // Parse first range value: <from> in '<unit> <from>-<to>/<length>' fromLength = HttpRuleParser.GetNumberLength(input, current, false); if ((fromLength == 0) || (fromLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + fromLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Afer the first value, the '-' character must follow. if ((current == input.Length) || (input[current] != '-')) { // We need a '-' character otherwise this can't be a valid range. return false; } current++; // skip the '-' character current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return false; } // Parse second range value: <to> in '<unit> <from>-<to>/<length>' toStartIndex = current; toLength = HttpRuleParser.GetNumberLength(input, current, false); if ((toLength == 0) || (toLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + toLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryCreateContentRange(string input, string unit, int fromStartIndex, int fromLength, int toStartIndex, int toLength, int lengthStartIndex, int lengthLength, out object parsedValue) { parsedValue = null; long from = 0; if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from)) { return false; } long to = 0; if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to)) { return false; } // 'from' must not be greater than 'to' if ((fromLength > 0) && (toLength > 0) && (from > to)) { return false; } long length = 0; if ((lengthLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(lengthStartIndex, lengthLength), out length)) { return false; } // 'from' and 'to' must be less than 'length' if ((toLength > 0) && (lengthLength > 0) && (to >= length)) { return false; } ContentRangeHeaderValue result = new ContentRangeHeaderValue(); result._unit = unit; if (fromLength > 0) { result._from = from; result._to = to; } if (lengthLength > 0) { result._length = length; } parsedValue = result; return true; } object ICloneable.Clone() { return new ContentRangeHeaderValue(this); } } }
// 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: Managed ACL wrapper for Win32 mutexes. ** ** ===========================================================*/ using System; using System.Collections; using System.Security.Principal; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Threading; namespace System.Security.AccessControl { // Derive this list of values from winnt.h and MSDN docs: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization_object_security_and_access_rights.asp // In order to call ReleaseMutex, you must have an ACL granting you // MUTEX_MODIFY_STATE rights (0x0001). The other interesting value // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001). // You need SYNCHRONIZE to be able to open a handle to a mutex. [Flags] public enum MutexRights { Modify = 0x000001, Delete = 0x010000, ReadPermissions = 0x020000, ChangePermissions = 0x040000, TakeOwnership = 0x080000, Synchronize = 0x100000, // SYNCHRONIZE FullControl = 0x1F0001 } public sealed class MutexAccessRule : AccessRule { // Constructor for creating access rules for registry objects public MutexAccessRule(IdentityReference identity, MutexRights eventRights, AccessControlType type) : this(identity, (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public MutexAccessRule(String identity, MutexRights eventRights, AccessControlType type) : this(new NTAccount(identity), (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of {File|Folder}Security // internal MutexAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } public MutexRights MutexRights { get { return (MutexRights)base.AccessMask; } } } public sealed class MutexAuditRule : AuditRule { public MutexAuditRule(IdentityReference identity, MutexRights eventRights, AuditFlags flags) : this(identity, (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags) { } /* // Not in the spec public MutexAuditRule(string identity, MutexRights eventRights, AuditFlags flags) : this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags) { } */ internal MutexAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } public MutexRights MutexRights { get { return (MutexRights)base.AccessMask; } } } public sealed class MutexSecurity : NativeObjectSecurity { public MutexSecurity() : base(true, ResourceType.KernelObject) { } [System.Security.SecuritySafeCritical] // auto-generated public MutexSecurity(String name, AccessControlSections includeSections) : base(true, ResourceType.KernelObject, name, includeSections, _HandleErrorCode, null) { // Let the underlying ACL API's demand unmanaged code permission. } [System.Security.SecurityCritical] // auto-generated internal MutexSecurity(SafeWaitHandle handle, AccessControlSections includeSections) : base(true, ResourceType.KernelObject, handle, includeSections, _HandleErrorCode, null) { // Let the underlying ACL API's demand unmanaged code permission. } [System.Security.SecurityCritical] // auto-generated private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) { System.Exception exception = null; switch (errorCode) { case Interop.mincore.Errors.ERROR_INVALID_NAME: case Interop.mincore.Errors.ERROR_INVALID_HANDLE: case Interop.mincore.Errors.ERROR_FILE_NOT_FOUND: if ((name != null) && (name.Length != 0)) exception = new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); else exception = new WaitHandleCannotBeOpenedException(); break; default: break; } return exception; } public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new MutexAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new MutexAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } internal AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) persistRules = AccessControlSections.Access; if (AuditRulesModified) persistRules |= AccessControlSections.Audit; if (OwnerModified) persistRules |= AccessControlSections.Owner; if (GroupModified) persistRules |= AccessControlSections.Group; return persistRules; } [System.Security.SecurityCritical] // auto-generated internal void Persist(SafeWaitHandle handle) { // Let the underlying ACL API's demand unmanaged code. WriteLock(); try { AccessControlSections persistSections = GetAccessControlSectionsFromChanges(); if (persistSections == AccessControlSections.None) return; // Don't need to persist anything. base.Persist(handle, persistSections); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } public void AddAccessRule(MutexAccessRule rule) { base.AddAccessRule(rule); } public void SetAccessRule(MutexAccessRule rule) { base.SetAccessRule(rule); } public void ResetAccessRule(MutexAccessRule rule) { base.ResetAccessRule(rule); } public bool RemoveAccessRule(MutexAccessRule rule) { return base.RemoveAccessRule(rule); } public void RemoveAccessRuleAll(MutexAccessRule rule) { base.RemoveAccessRuleAll(rule); } public void RemoveAccessRuleSpecific(MutexAccessRule rule) { base.RemoveAccessRuleSpecific(rule); } public void AddAuditRule(MutexAuditRule rule) { base.AddAuditRule(rule); } public void SetAuditRule(MutexAuditRule rule) { base.SetAuditRule(rule); } public bool RemoveAuditRule(MutexAuditRule rule) { return base.RemoveAuditRule(rule); } public void RemoveAuditRuleAll(MutexAuditRule rule) { base.RemoveAuditRuleAll(rule); } public void RemoveAuditRuleSpecific(MutexAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } public override Type AccessRightType { get { return typeof(MutexRights); } } public override Type AccessRuleType { get { return typeof(MutexAccessRule); } } public override Type AuditRuleType { get { return typeof(MutexAuditRule); } } } }
using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Resources; using System.Text; using System.Threading; using log4net; namespace Memcached.ClientLibrary { /// <summary> /// Memcached C# client, utility class for Socket IO. /// /// This class is a wrapper around a Socket and its streams. /// </summary> public class SockIO { // logger private static ILog Log = LogManager.GetLogger(typeof(SockIO)); // id generator. Gives ids to all the SockIO instances private static int IdGenerator; // id private int _id; // time created private DateTime _created; // pool private SockIOPool _pool; // data private String _host; private Socket _socket; private Stream _networkStream; private SockIO() { _id = Interlocked.Increment(ref IdGenerator); _created = DateTime.Now; } /// <summary> /// creates a new SockIO object wrapping a socket /// connection to host:port, and its input and output streams /// </summary> /// <param name="pool">Pool this object is tied to</param> /// <param name="host">host to connect to</param> /// <param name="port">port to connect to</param> /// <param name="timeout">int ms to block on data for read</param> /// <param name="connectTimeout">timeout (in ms) for initial connection</param> /// <param name="noDelay">TCP NODELAY option?</param> public SockIO(SockIOPool pool, String host, int port, int timeout, int connectTimeout, bool noDelay) : this() { if (host == null || host.Length == 0) throw new ArgumentNullException(GetLocalizedString("host"), GetLocalizedString("null host")); _pool = pool; if (connectTimeout > 0) { _socket = GetSocket(host, port, connectTimeout); } else { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(new IPEndPoint(IPAddress.Parse(host), port)); } _networkStream = new BufferedStream(new NetworkStreamIgnoreSeek(_socket)); _host = host + ":" + port; } /// <summary> /// creates a new SockIO object wrapping a socket /// connection to host:port, and its input and output streams /// </summary> /// <param name="pool">Pool this object is tied to</param> /// <param name="host">hostname:port</param> /// <param name="timeout">read timeout value for connected socket</param> /// <param name="connectTimeout">timeout for initial connections</param> /// <param name="noDelay">TCP NODELAY option?</param> public SockIO(SockIOPool pool, String host, int timeout, int connectTimeout, bool noDelay) : this() { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException(GetLocalizedString("host"), GetLocalizedString("null host")); _pool = pool; String[] ip = host.Split(':'); // get socket: default is to use non-blocking connect if (connectTimeout > 0) { _socket = GetSocket(ip[0], int.Parse(ip[1], new System.Globalization.NumberFormatInfo()), connectTimeout); } else { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(new IPEndPoint(IPAddress.Parse(ip[0]), int.Parse(ip[1], new System.Globalization.NumberFormatInfo()))); } _networkStream = new BufferedStream(new NetworkStreamIgnoreSeek(_socket)); _host = host; } /// <summary> /// Method which spawns thread to get a connection and then enforces a timeout on the initial /// connection. /// /// This should be backed by a thread pool. Any volunteers? /// </summary> /// <param name="host">host to establish connection to</param> /// <param name="port">port on that host</param> /// <param name="timeout">connection timeout in ms</param> /// <returns>connected socket</returns> protected static Socket GetSocket(String host, int port, int timeout) { // Create a new thread which will attempt to connect to host:port, and start it running ConnectThread thread = new ConnectThread(host, port); thread.Start(); int timer = 0; int sleep = 25; while (timer < timeout) { // if the thread has a connected socket // then return it if (thread.IsConnected) return thread.Socket; // if the thread had an error // then throw a new IOException if (thread.IsError) throw new IOException(); try { // sleep for short time before polling again Thread.Sleep(sleep); } catch (ThreadInterruptedException) { } // Increment timer timer += sleep; } // made it through loop without getting connection // the connection thread will timeout on its own at OS timeout throw new IOException(GetLocalizedString("connect timeout").Replace("$$timeout$$", timeout.ToString(new System.Globalization.NumberFormatInfo()))); } /// <summary> /// returns the host this socket is connected to /// /// String representation of host (hostname:port) /// </summary> public string Host { get { return _host; } } /// <summary> /// closes socket and all streams connected to it /// </summary> public void TrueClose() { if(Log.IsDebugEnabled) { Log.Debug(GetLocalizedString("true close socket").Replace("$$Socket$$", ToString()).Replace("$$Lifespan$$", DateTime.Now.Subtract(_created).ToString())); } bool err = false; StringBuilder errMsg = new StringBuilder(); if (_socket == null || _networkStream == null) { err = true; errMsg.Append(GetLocalizedString("socket already closed")); } if (_socket != null) { try { _socket.Close(); } catch (IOException ioe) { if(Log.IsErrorEnabled) { Log.Error(GetLocalizedString("error closing socket").Replace("$$ToString$$", ToString()).Replace("$$Host$$", Host), ioe); } errMsg.Append(GetLocalizedString("error closing socket").Replace("$$ToString$$", ToString()).Replace("$$Host$$", Host) + System.Environment.NewLine); errMsg.Append(ioe.ToString()); err = true; } catch (SocketException soe) { if(Log.IsErrorEnabled) { Log.Error(GetLocalizedString("error closing socket").Replace("$$ToString$$", ToString()).Replace("$$Host$$", Host), soe); } errMsg.Append(GetLocalizedString("error closing socket").Replace("$$ToString$$", ToString()).Replace("$$Host$$", Host) + System.Environment.NewLine); errMsg.Append(soe.ToString()); err = true; } } // check in to pool if (_socket != null) _pool.CheckIn(this, false); _networkStream = null; _socket = null; if (err) throw new IOException(errMsg.ToString()); } /// <summary> /// sets closed flag and checks in to connection pool /// but does not close connections /// </summary> public void Close() { // check in to pool if(Log.IsDebugEnabled) { Log.Debug(GetLocalizedString("close socket").Replace("$$ToString$$", ToString())); } _pool.CheckIn(this); } /// <summary> /// Gets whether or not the socket is connected. Returns <c>true</c> if it is. /// </summary> public bool IsConnected { get { return _socket != null && _socket.Connected; } } /// <summary> /// reads a line /// intentionally not using the deprecated readLine method from DataInputStream /// </summary> /// <returns>String that was read in</returns> public string ReadLine() { if (_socket == null || !_socket.Connected) { if(Log.IsErrorEnabled) { Log.Error(GetLocalizedString("read closed socket")); } throw new IOException(GetLocalizedString("read closed socket")); } byte[] b = new byte[1]; MemoryStream memoryStream = new MemoryStream(); bool eol = false; while (_networkStream.Read(b, 0, 1) != -1) { if (b[0] == 13) { eol = true; } else { if (eol) { if (b[0] == 10) break; eol = false; } } // cast byte into char array memoryStream.Write(b, 0, 1); } if (memoryStream == null || memoryStream.Length <= 0) { throw new IOException(GetLocalizedString("closing dead stream")); } // else return the string string temp = Encoding.UTF8.GetString(memoryStream.GetBuffer()).TrimEnd('\0', '\r', '\n'); return temp; } /// <summary> /// reads up to end of line and returns nothing /// </summary> public void ClearEndOfLine() { if (_socket == null || !_socket.Connected) { Log.Error(GetLocalizedString("read closed socket")); throw new IOException(GetLocalizedString("read closed socket")); } byte[] b = new byte[1]; bool eol = false; while (_networkStream.Read(b, 0, 1) != -1) { // only stop when we see // \r (13) followed by \n (10) if (b[0] == 13) { eol = true; continue; } if (eol) { if (b[0] == 10) break; eol = false; } } } /// <summary> /// reads length bytes into the passed in byte array from stream /// </summary> /// <param name="b">byte array</param> public void Read(byte[] bytes) { if (_socket == null || !_socket.Connected) { if(Log.IsErrorEnabled) { Log.Error(GetLocalizedString("read closed socket")); } throw new IOException(GetLocalizedString("read closed socket")); } if (bytes == null) return; int count = 0; while (count < bytes.Length) { int cnt = _networkStream.Read(bytes, count, (bytes.Length - count)); count += cnt; } } /// <summary> /// flushes output stream /// </summary> public void Flush() { if (_socket == null || !_socket.Connected) { if(Log.IsErrorEnabled) { Log.Error(GetLocalizedString("write closed socket")); } throw new IOException(GetLocalizedString("write closed socket")); } _networkStream.Flush(); } /// <summary> /// writes a byte array to the output stream /// </summary> /// <param name="bytes">byte array to write</param> public void Write(byte[] bytes) { Write(bytes, 0, bytes.Length); } /// <summary> /// writes a byte array to the output stream /// </summary> /// <param name="bytes">byte array to write</param> /// <param name="offset">offset to begin writing from</param> /// <param name="count">count of bytes to write</param> public void Write(byte[] bytes, int offset, int count) { if (_socket == null || !_socket.Connected) { if(Log.IsErrorEnabled) { Log.Error(GetLocalizedString("write closed socket")); } throw new IOException(GetLocalizedString("write closed socket")); } if (bytes != null) _networkStream.Write(bytes, offset, count); } /// <summary> /// returns the string representation of this socket /// </summary> /// <returns></returns> public override string ToString() { if (_socket == null) return ""; return _id.ToString(new System.Globalization.NumberFormatInfo()); } //public void Dispose() //{ // Dispose(true); // GC.SuppressFinalize(this); //} //protected virtual void Dispose(bool disposing) //{ // if (!_disposed) // { // if (disposing) // Close(); // TrueClose(); // } // _disposed = true; //} /// <summary> /// Thread to attempt connection. /// This will be polled by the main thread. We run the risk of filling up w/ /// threads attempting connections if network is down. However, the falling off /// mech in the main code should limit this. /// </summary> private class ConnectThread { //thread Thread _thread; // logger private static ILog Log = LogManager.GetLogger(typeof(ConnectThread)); private Socket _socket; private String _host; private int _port; bool _error; /// <summary> /// Constructor /// </summary> /// <param name="host"></param> /// <param name="port"></param> public ConnectThread(string host, int port) { _host = host; _port = port; _thread = new Thread(new ThreadStart(Connect)); _thread.IsBackground = true; } /// <summary> /// The logic of the thread. /// </summary> private void Connect() { try { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(new IPEndPoint(IPAddress.Parse(_host), _port)); } catch (IOException) { _error = true; } catch (SocketException ex) { _error = true; if(Log.IsDebugEnabled) { Log.Debug(GetLocalizedString("socket connection exception"), ex); } } if(Log.IsDebugEnabled) { Log.Debug(GetLocalizedString("connect thread connect").Replace("$$Host$$", _host)); } } /// <summary> /// start thread running. /// This attempts to establish a connection. /// </summary> public void Start() { _thread.Start(); } /// <summary> /// Is the new socket connected yet /// </summary> public bool IsConnected { get { return _socket != null && _socket.Connected; } } /// <summary> /// Did we have an exception while connecting? /// </summary> /// <returns></returns> public bool IsError { get { return _error; } } /// <summary> /// Return the socket. /// </summary> public Socket Socket { get { return _socket; } } } private static readonly ResourceManager ResourceManager = new ResourceManager("Memcached.ClientLibrary.StringMessages", typeof(SockIO).Assembly); private static string GetLocalizedString(string key) { return ResourceManager.GetString(key); } } }
/* VRWandInteraction * MiddleVR * (c) i'm in VR */ using UnityEngine; using System.Collections; using MiddleVR_Unity3D; public class VRWandInteraction : MonoBehaviour { public float RayLength = 2; public bool Highlight = true; public Color HighlightColor = new Color(); public Color GrabColor = new Color(); public bool RepeatAction = false; public GameObject ObjectInHand = null; public GameObject CurrentObject = null; bool m_ObjectWasKinematic = true; private vrButtons m_Buttons = null; private bool m_SearchedButtons = false; private Transform m_ObjectLastParentTransform = null; private GameObject m_Ray = null; // Use this for initialization void Start () { m_Ray = GameObject.Find("WandRay"); if (m_Ray != null) { m_Ray.transform.localScale = new Vector3( 0.01f, RayLength / 2.0f, 0.01f ); m_Ray.transform.localPosition = new Vector3( 0,0, RayLength / 2.0f ); } } private Collider GetClosestHit() { // Detect objects RaycastHit[] hits; Vector3 dir = transform.localToWorldMatrix * Vector3.forward; hits = Physics.RaycastAll(transform.position, dir, RayLength); int i = 0; Collider closest = null; float distance = Mathf.Infinity; while (i < hits.Length) { RaycastHit hit = hits[i]; //print("HIT : " + i + " : " + hit.collider.name); if( hit.distance < distance && hit.collider.name != "VRWand" && hit.collider.GetComponent<VRActor>() != null ) { distance = hit.distance; closest = hit.collider; } i++; } return closest; } private void HighlightObject( GameObject obj, bool state ) { HighlightObject(obj, state, HighlightColor); } private void HighlightObject( GameObject obj, bool state, Color hCol ) { GameObject hobj = m_Ray; if (hobj != null && hobj.GetComponent<Renderer>() != null && Highlight) { if( state ) { hobj.GetComponent<Renderer>().material.color = hCol; } else { //CurrentObject.renderer.material.color = Color.white; hobj.GetComponent<Renderer>().material.color = Color.white; } } } private void Grab( GameObject iObject ) { //MiddleVRTools.Log("Take :" + CurrentObject.name); ObjectInHand = iObject; m_ObjectLastParentTransform = ObjectInHand.transform.parent; ObjectInHand.transform.parent = transform.parent; if (ObjectInHand.GetComponent<Rigidbody>() != null) { m_ObjectWasKinematic = ObjectInHand.GetComponent<Rigidbody>().isKinematic; ObjectInHand.GetComponent<Rigidbody>().isKinematic = true; } HighlightObject(ObjectInHand, true, GrabColor); } private void Ungrab() { //MiddleVRTools.Log("Release : " + ObjectInHand); ObjectInHand.transform.parent = m_ObjectLastParentTransform; if (ObjectInHand.GetComponent<Rigidbody>() != null) { if (!m_ObjectWasKinematic) ObjectInHand.GetComponent<Rigidbody>().isKinematic = false; } ObjectInHand = null; m_ObjectLastParentTransform = null; HighlightObject(CurrentObject, false, HighlightColor); CurrentObject = null; } // Update is called once per frame void Update () { if (m_Buttons == null) { m_Buttons = MiddleVR.VRDeviceMgr.GetWandButtons(); } if( m_Buttons == null ) { if (m_SearchedButtons == false) { //MiddleVRTools.Log("[~] VRWandInteraction: Wand buttons undefined. Please specify Wand Buttons in the configuration tool."); m_SearchedButtons = true; } } Collider hit = GetClosestHit(); if( hit != null ) { //print("Closest : " + hit.name); if( CurrentObject != hit.gameObject && ObjectInHand == null ) { //MiddleVRTools.Log("Enter other : " + hit.name); HighlightObject( CurrentObject, false ); CurrentObject = hit.gameObject; HighlightObject(CurrentObject, true ); //MiddleVRTools.Log("Current : " + CurrentObject.name); } } // Else else { //MiddleVRTools.Log("No touch ! "); if (CurrentObject != null && CurrentObject != ObjectInHand) { HighlightObject(CurrentObject, false, HighlightColor ); CurrentObject = null; } } //MiddleVRTools.Log("Current : " + CurrentObject); if (m_Buttons != null && CurrentObject != null ) { uint MainButton = MiddleVR.VRDeviceMgr.GetWandButton0(); VRActor script = CurrentObject.GetComponent<VRActor>(); //MiddleVRTools.Log("Trying to take :" + CurrentObject.name); if (script != null) { // Grab if (m_Buttons.IsToggled(MainButton)) { if (script.Grabable) { Grab(CurrentObject); } } // Release if (m_Buttons.IsToggled(MainButton, false) && ObjectInHand != null) { Ungrab(); } // Action if (((!RepeatAction && m_Buttons.IsToggled(MainButton)) || (RepeatAction&& m_Buttons.IsPressed(MainButton)))) { CurrentObject.SendMessage("VRAction", SendMessageOptions.DontRequireReceiver); } } } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Media.Effect.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Android.Media.Effect { /// <java-name> /// android/media/effect/EffectUpdateListener /// </java-name> [Dot42.DexImport("android/media/effect/EffectUpdateListener", AccessFlags = 1537)] public partial interface IEffectUpdateListener /* scope: __dot42__ */ { /// <java-name> /// onEffectUpdated /// </java-name> [Dot42.DexImport("onEffectUpdated", "(Landroid/media/effect/Effect;Ljava/lang/Object;)V", AccessFlags = 1025)] void OnEffectUpdated(global::Android.Media.Effect.Effect effect, object @object) /* MethodBuilder.Create */ ; } /// <java-name> /// android/media/effect/Effect /// </java-name> [Dot42.DexImport("android/media/effect/Effect", AccessFlags = 1057)] public abstract partial class Effect /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Effect() /* MethodBuilder.Create */ { } /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)] public abstract string GetName() /* MethodBuilder.Create */ ; /// <java-name> /// apply /// </java-name> [Dot42.DexImport("apply", "(IIII)V", AccessFlags = 1025)] public abstract void Apply(int int32, int int321, int int322, int int323) /* MethodBuilder.Create */ ; /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 1025)] public abstract void SetParameter(string @string, object @object) /* MethodBuilder.Create */ ; /// <java-name> /// setUpdateListener /// </java-name> [Dot42.DexImport("setUpdateListener", "(Landroid/media/effect/EffectUpdateListener;)V", AccessFlags = 1)] public virtual void SetUpdateListener(global::Android.Media.Effect.IEffectUpdateListener effectUpdateListener) /* MethodBuilder.Create */ { } /// <java-name> /// release /// </java-name> [Dot42.DexImport("release", "()V", AccessFlags = 1025)] public abstract void Release() /* MethodBuilder.Create */ ; /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)] get{ return GetName(); } } } /// <java-name> /// android/media/effect/EffectFactory /// </java-name> [Dot42.DexImport("android/media/effect/EffectFactory", AccessFlags = 33)] public partial class EffectFactory /* scope: __dot42__ */ { /// <java-name> /// EFFECT_BRIGHTNESS /// </java-name> [Dot42.DexImport("EFFECT_BRIGHTNESS", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_BRIGHTNESS = "android.media.effect.effects.BrightnessEffect"; /// <java-name> /// EFFECT_CONTRAST /// </java-name> [Dot42.DexImport("EFFECT_CONTRAST", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_CONTRAST = "android.media.effect.effects.ContrastEffect"; /// <java-name> /// EFFECT_FISHEYE /// </java-name> [Dot42.DexImport("EFFECT_FISHEYE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_FISHEYE = "android.media.effect.effects.FisheyeEffect"; /// <java-name> /// EFFECT_BACKDROPPER /// </java-name> [Dot42.DexImport("EFFECT_BACKDROPPER", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_BACKDROPPER = "android.media.effect.effects.BackDropperEffect"; /// <java-name> /// EFFECT_AUTOFIX /// </java-name> [Dot42.DexImport("EFFECT_AUTOFIX", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_AUTOFIX = "android.media.effect.effects.AutoFixEffect"; /// <java-name> /// EFFECT_BLACKWHITE /// </java-name> [Dot42.DexImport("EFFECT_BLACKWHITE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_BLACKWHITE = "android.media.effect.effects.BlackWhiteEffect"; /// <java-name> /// EFFECT_CROP /// </java-name> [Dot42.DexImport("EFFECT_CROP", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_CROP = "android.media.effect.effects.CropEffect"; /// <java-name> /// EFFECT_CROSSPROCESS /// </java-name> [Dot42.DexImport("EFFECT_CROSSPROCESS", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_CROSSPROCESS = "android.media.effect.effects.CrossProcessEffect"; /// <java-name> /// EFFECT_DOCUMENTARY /// </java-name> [Dot42.DexImport("EFFECT_DOCUMENTARY", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_DOCUMENTARY = "android.media.effect.effects.DocumentaryEffect"; /// <java-name> /// EFFECT_BITMAPOVERLAY /// </java-name> [Dot42.DexImport("EFFECT_BITMAPOVERLAY", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_BITMAPOVERLAY = "android.media.effect.effects.BitmapOverlayEffect"; /// <java-name> /// EFFECT_DUOTONE /// </java-name> [Dot42.DexImport("EFFECT_DUOTONE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_DUOTONE = "android.media.effect.effects.DuotoneEffect"; /// <java-name> /// EFFECT_FILLLIGHT /// </java-name> [Dot42.DexImport("EFFECT_FILLLIGHT", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_FILLLIGHT = "android.media.effect.effects.FillLightEffect"; /// <java-name> /// EFFECT_FLIP /// </java-name> [Dot42.DexImport("EFFECT_FLIP", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_FLIP = "android.media.effect.effects.FlipEffect"; /// <java-name> /// EFFECT_GRAIN /// </java-name> [Dot42.DexImport("EFFECT_GRAIN", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_GRAIN = "android.media.effect.effects.GrainEffect"; /// <java-name> /// EFFECT_GRAYSCALE /// </java-name> [Dot42.DexImport("EFFECT_GRAYSCALE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_GRAYSCALE = "android.media.effect.effects.GrayscaleEffect"; /// <java-name> /// EFFECT_LOMOISH /// </java-name> [Dot42.DexImport("EFFECT_LOMOISH", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_LOMOISH = "android.media.effect.effects.LomoishEffect"; /// <java-name> /// EFFECT_NEGATIVE /// </java-name> [Dot42.DexImport("EFFECT_NEGATIVE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_NEGATIVE = "android.media.effect.effects.NegativeEffect"; /// <java-name> /// EFFECT_POSTERIZE /// </java-name> [Dot42.DexImport("EFFECT_POSTERIZE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_POSTERIZE = "android.media.effect.effects.PosterizeEffect"; /// <java-name> /// EFFECT_REDEYE /// </java-name> [Dot42.DexImport("EFFECT_REDEYE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_REDEYE = "android.media.effect.effects.RedEyeEffect"; /// <java-name> /// EFFECT_ROTATE /// </java-name> [Dot42.DexImport("EFFECT_ROTATE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_ROTATE = "android.media.effect.effects.RotateEffect"; /// <java-name> /// EFFECT_SATURATE /// </java-name> [Dot42.DexImport("EFFECT_SATURATE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_SATURATE = "android.media.effect.effects.SaturateEffect"; /// <java-name> /// EFFECT_SEPIA /// </java-name> [Dot42.DexImport("EFFECT_SEPIA", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_SEPIA = "android.media.effect.effects.SepiaEffect"; /// <java-name> /// EFFECT_SHARPEN /// </java-name> [Dot42.DexImport("EFFECT_SHARPEN", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_SHARPEN = "android.media.effect.effects.SharpenEffect"; /// <java-name> /// EFFECT_STRAIGHTEN /// </java-name> [Dot42.DexImport("EFFECT_STRAIGHTEN", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_STRAIGHTEN = "android.media.effect.effects.StraightenEffect"; /// <java-name> /// EFFECT_TEMPERATURE /// </java-name> [Dot42.DexImport("EFFECT_TEMPERATURE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_TEMPERATURE = "android.media.effect.effects.ColorTemperatureEffect"; /// <java-name> /// EFFECT_TINT /// </java-name> [Dot42.DexImport("EFFECT_TINT", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_TINT = "android.media.effect.effects.TintEffect"; /// <java-name> /// EFFECT_VIGNETTE /// </java-name> [Dot42.DexImport("EFFECT_VIGNETTE", "Ljava/lang/String;", AccessFlags = 25)] public const string EFFECT_VIGNETTE = "android.media.effect.effects.VignetteEffect"; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal EffectFactory() /* MethodBuilder.Create */ { } /// <java-name> /// createEffect /// </java-name> [Dot42.DexImport("createEffect", "(Ljava/lang/String;)Landroid/media/effect/Effect;", AccessFlags = 1)] public virtual global::Android.Media.Effect.Effect CreateEffect(string @string) /* MethodBuilder.Create */ { return default(global::Android.Media.Effect.Effect); } /// <java-name> /// isEffectSupported /// </java-name> [Dot42.DexImport("isEffectSupported", "(Ljava/lang/String;)Z", AccessFlags = 9)] public static bool IsEffectSupported(string @string) /* MethodBuilder.Create */ { return default(bool); } } /// <java-name> /// android/media/effect/EffectContext /// </java-name> [Dot42.DexImport("android/media/effect/EffectContext", AccessFlags = 33)] public partial class EffectContext /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal EffectContext() /* MethodBuilder.Create */ { } /// <java-name> /// createWithCurrentGlContext /// </java-name> [Dot42.DexImport("createWithCurrentGlContext", "()Landroid/media/effect/EffectContext;", AccessFlags = 9)] public static global::Android.Media.Effect.EffectContext CreateWithCurrentGlContext() /* MethodBuilder.Create */ { return default(global::Android.Media.Effect.EffectContext); } /// <java-name> /// getFactory /// </java-name> [Dot42.DexImport("getFactory", "()Landroid/media/effect/EffectFactory;", AccessFlags = 1)] public virtual global::Android.Media.Effect.EffectFactory GetFactory() /* MethodBuilder.Create */ { return default(global::Android.Media.Effect.EffectFactory); } /// <java-name> /// release /// </java-name> [Dot42.DexImport("release", "()V", AccessFlags = 1)] public virtual void Release() /* MethodBuilder.Create */ { } /// <java-name> /// getFactory /// </java-name> public global::Android.Media.Effect.EffectFactory Factory { [Dot42.DexImport("getFactory", "()Landroid/media/effect/EffectFactory;", AccessFlags = 1)] get{ return GetFactory(); } } } }
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class FormHandlingTests : DriverTestFixture { [Test] public void ShouldClickOnSubmitInputElements() { driver.Url = formsPage; driver.FindElement(By.Id("submitButton")).Click(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ClickingOnUnclickableElementsDoesNothing() { driver.Url = formsPage; driver.FindElement(By.XPath("//body")).Click(); } [Test] public void ShouldBeAbleToClickImageButtons() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Click(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToSubmitForms() { driver.Url = formsPage; driver.FindElement(By.Name("login")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.Id("checky")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.XPath("//form/p")).Submit(); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.Android)] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.PhantomJS)] //[IgnoreBrowser(Browser.Safari)] public void ShouldNotBeAbleToSubmitAFormThatDoesNotExist() { driver.Url = formsPage; Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Name("SearchableText")).Submit()); } [Test] public void ShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue() { driver.Url = javascriptPage; IWebElement textarea = driver.FindElement(By.Id("keyUpArea")); string cheesey = "Brie and cheddar"; textarea.SendKeys(cheesey); Assert.AreEqual(textarea.GetAttribute("value"), cheesey); } [Test] public void SendKeysKeepsCapitalization() { driver.Url = javascriptPage; IWebElement textarea = driver.FindElement(By.Id("keyUpArea")); string cheesey = "BrIe And CheDdar"; textarea.SendKeys(cheesey); Assert.AreEqual(textarea.GetAttribute("value"), cheesey); } [Test] public void ShouldSubmitAFormUsingTheNewlineLiteral() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys("\n"); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldSubmitAFormUsingTheEnterKey() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys(Keys.Enter); WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldEnterDataIntoFormFields() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String originalValue = element.GetAttribute("value"); Assert.AreEqual(originalValue, "change"); element.Clear(); element.SendKeys("some text"); element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String newFormValue = element.GetAttribute("value"); Assert.AreEqual(newFormValue, "some text"); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] //[IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] //[IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument() { // IE before 9 doesn't handle pages served with an XHTML content type, and just prompts for to // download it if (TestUtilities.IsOldIE(driver)) { return; } driver.Url = xhtmlFormPage; IWebElement uploadElement = driver.FindElement(By.Id("file")); Assert.AreEqual(string.Empty, uploadElement.GetAttribute("value")); string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] //[IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void ShouldBeAbleToUploadTheSameFileTwice() { string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); for (int i = 0; i < 2; ++i) { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); uploadElement.SendKeys(inputFile.FullName); uploadElement.Submit(); } // If we get this far, then we're all good. } [Test] public void SendingKeyboardEventsShouldAppendTextInInputs() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some"); String value = element.GetAttribute("value"); Assert.AreEqual(value, "Some"); element.SendKeys(" text"); value = element.GetAttribute("value"); Assert.AreEqual(value, "Some text"); } [Test] public void SendingKeyboardEventsShouldAppendTextInInputsWithExistingValue() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("inputWithText")); element.SendKeys(". Some text"); string value = element.GetAttribute("value"); Assert.AreEqual("Example text. Some text", value); } [Test] [IgnoreBrowser(Browser.HtmlUnit, "Not implemented going to the end of the line first")] public void SendingKeyboardEventsShouldAppendTextInTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys(". Some text"); String value = element.GetAttribute("value"); Assert.AreEqual(value, "Example text. Some text"); } [Test] public void ShouldBeAbleToClearTextFromInputElements() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some text"); String value = element.GetAttribute("value"); Assert.IsTrue(value.Length > 0); element.Clear(); value = element.GetAttribute("value"); Assert.AreEqual(value.Length, 0); } [Test] public void EmptyTextBoxesShouldReturnAnEmptyStringNotNull() { driver.Url = formsPage; IWebElement emptyTextBox = driver.FindElement(By.Id("working")); Assert.AreEqual(emptyTextBox.GetAttribute("value"), ""); IWebElement emptyTextArea = driver.FindElement(By.Id("emptyTextArea")); Assert.AreEqual(emptyTextBox.GetAttribute("value"), ""); } [Test] public void ShouldBeAbleToClearTextFromTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys("Some text"); String value = element.GetAttribute("value"); Assert.IsTrue(value.Length > 0); element.Clear(); value = element.GetAttribute("value"); Assert.AreEqual(value.Length, 0); } [Test] [IgnoreBrowser(Browser.IE, "Hangs")] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] [IgnoreBrowser(Browser.Opera, "Untested")] [IgnoreBrowser(Browser.PhantomJS, "Untested")] [IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support alert handling")] [IgnoreBrowser(Browser.Firefox, "Dismissing alert causes entire window to close.")] public void HandleFormWithJavascriptAction() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("form_handling_js_submit.html"); driver.Url = url; IWebElement element = driver.FindElement(By.Id("theForm")); element.Submit(); IAlert alert = driver.SwitchTo().Alert(); string text = alert.Text; alert.Dismiss(); Assert.AreEqual("Tasty cheese", text); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] //[IgnoreBrowser(Browser.Safari, "Untested")] public void CanClickOnASubmitButton() { CheckSubmitButton("internal_explicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] // [IgnoreBrowser(Browser.Safari, "Untested")] public void CanClickOnAnImplicitSubmitButton() { CheckSubmitButton("internal_implicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] //[IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Fails on HtmlUnit")] [IgnoreBrowser(Browser.IE, "Fails on IE")] public void CanClickOnAnExternalSubmitButton() { CheckSubmitButton("external_explicit_submit"); } [Test] [IgnoreBrowser(Browser.Android, "Untested")] [IgnoreBrowser(Browser.IPhone, "Untested")] // [IgnoreBrowser(Browser.Safari, "Untested")] [IgnoreBrowser(Browser.HtmlUnit, "Fails on HtmlUnit")] [IgnoreBrowser(Browser.IE, "Fails on IE")] public void CanClickOnAnExternalImplicitSubmitButton() { CheckSubmitButton("external_implicit_submit"); } private void CheckSubmitButton(string buttonId) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/html5_submit_buttons.html"); string name = "Gromit"; driver.FindElement(By.Id("name")).SendKeys(name); driver.FindElement(By.Id(buttonId)).Click(); WaitFor(TitleToBe("Submitted Successfully!"), "Browser title is not 'Submitted Successfully!'"); Assert.That(driver.Url.Contains("name=" + name), "URL does not contain 'name=" + name + "'. Actual URL:" + driver.Url); } private Func<bool> TitleToBe(string desiredTitle) { return () => { return driver.Title == desiredTitle; }; } } }
/* * 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.Collections.Specialized; using System.Reflection; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Connectors.SimianGrid { /// <summary> /// Connects user account data (creating new users, looking up existing /// users) to the SimianGrid backend /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class SimianUserAccountServiceConnector : IUserAccountService, ISharedRegionModule { private const double CACHE_EXPIRATION_SECONDS = 120.0; private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_serverUrl = String.Empty; private ExpiringCache<UUID, UserAccount> m_accountCache = new ExpiringCache<UUID,UserAccount>(); private bool m_Enabled; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public SimianUserAccountServiceConnector() { } public string Name { get { return "SimianUserAccountServiceConnector"; } } public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IUserAccountService>(this); } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IUserAccountService>(this); } } #endregion ISharedRegionModule public SimianUserAccountServiceConnector(IConfigSource source) { CommonInit(source); } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("UserAccountServices", ""); if (name == Name) CommonInit(source); } } private void CommonInit(IConfigSource source) { IConfig gridConfig = source.Configs["UserAccountService"]; if (gridConfig != null) { string serviceUrl = gridConfig.GetString("UserAccountServerURI"); if (!String.IsNullOrEmpty(serviceUrl)) { if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("=")) serviceUrl = serviceUrl + '/'; m_serverUrl = serviceUrl; m_Enabled = true; } } if (String.IsNullOrEmpty(m_serverUrl)) m_log.Info("[SIMIAN ACCOUNT CONNECTOR]: No UserAccountServerURI specified, disabling connector"); } public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "Name", firstName + ' ' + lastName } }; return GetUser(requestArgs); } public UserAccount GetUserAccount(UUID scopeID, string email) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "Email", email } }; return GetUser(requestArgs); } public UserAccount GetUserAccount(UUID scopeID, UUID userID) { // Cache check UserAccount account; if (m_accountCache.TryGetValue(userID, out account)) return account; NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; account = GetUser(requestArgs); if (account == null) { // Store null responses too, to avoid repeated lookups for missing accounts m_accountCache.AddOrUpdate(userID, null, CACHE_EXPIRATION_SECONDS); } return account; } public List<UserAccount> GetUserAccounts(UUID scopeID, string query) { List<UserAccount> accounts = new List<UserAccount>(); // m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Searching for user accounts with name query " + query); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUsers" }, { "NameQuery", query } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDArray array = response["Users"] as OSDArray; if (array != null && array.Count > 0) { for (int i = 0; i < array.Count; i++) { UserAccount account = ResponseToUserAccount(array[i] as OSDMap); if (account != null) accounts.Add(account); } } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format"); } } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to search for account data by name " + query); } return accounts; } public bool StoreUserAccount(UserAccount data) { // m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account for " + data.Name); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUser" }, { "UserID", data.PrincipalID.ToString() }, { "Name", data.Name }, { "Email", data.Email }, { "AccessLevel", data.UserLevel.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Storing user account data for " + data.Name); requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", data.PrincipalID.ToString() }, { "CreationDate", data.Created.ToString() }, { "UserFlags", data.UserFlags.ToString() }, { "UserTitle", data.UserTitle } }; response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (success) { // Cache the user account info m_accountCache.AddOrUpdate(data.PrincipalID, data, CACHE_EXPIRATION_SECONDS); } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account data for " + data.Name + ": " + response["Message"].AsString()); } return success; } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to store user account for " + data.Name + ": " + response["Message"].AsString()); } return false; } /// <summary> /// Helper method for the various ways of retrieving a user account /// </summary> /// <param name="requestArgs">Service query parameters</param> /// <returns>A UserAccount object on success, null on failure</returns> private UserAccount GetUser(NameValueCollection requestArgs) { string lookupValue = (requestArgs.Count > 1) ? requestArgs[1] : "(Unknown)"; // m_log.DebugFormat("[SIMIAN ACCOUNT CONNECTOR]: Looking up user account with query: " + lookupValue); OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDMap user = response["User"] as OSDMap; if (user != null) return ResponseToUserAccount(user); else m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Account search failed, response data was in an invalid format"); } else { m_log.Warn("[SIMIAN ACCOUNT CONNECTOR]: Failed to lookup user account with query: " + lookupValue); } return null; } /// <summary> /// Convert a User object in LLSD format to a UserAccount /// </summary> /// <param name="response">LLSD containing user account data</param> /// <returns>A UserAccount object on success, null on failure</returns> private UserAccount ResponseToUserAccount(OSDMap response) { if (response == null) return null; UserAccount account = new UserAccount(); account.PrincipalID = response["UserID"].AsUUID(); account.Created = response["CreationDate"].AsInteger(); account.Email = response["Email"].AsString(); account.ServiceURLs = new Dictionary<string, object>(0); account.UserFlags = response["UserFlags"].AsInteger(); account.UserLevel = response["AccessLevel"].AsInteger(); account.UserTitle = response["UserTitle"].AsString(); GetFirstLastName(response["Name"].AsString(), out account.FirstName, out account.LastName); // Cache the user account info m_accountCache.AddOrUpdate(account.PrincipalID, account, CACHE_EXPIRATION_SECONDS); return account; } /// <summary> /// Convert a name with a single space in it to a first and last name /// </summary> /// <param name="name">A full name such as "John Doe"</param> /// <param name="firstName">First name</param> /// <param name="lastName">Last name (surname)</param> private static void GetFirstLastName(string name, out string firstName, out string lastName) { if (String.IsNullOrEmpty(name)) { firstName = String.Empty; lastName = String.Empty; } else { string[] names = name.Split(' '); if (names.Length == 2) { firstName = names[0]; lastName = names[1]; } else { firstName = String.Empty; lastName = name; } } } } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Extensions; using Type = System.Type; namespace Umbraco.Cms.Infrastructure.Migrations { /// <summary> /// Represents a migration plan. /// </summary> public class MigrationPlan { private readonly Dictionary<string, Transition> _transitions = new Dictionary<string, Transition>(StringComparer.InvariantCultureIgnoreCase); private readonly List<Type> _postMigrationTypes = new List<Type>(); private string _prevState; private string _finalState; /// <summary> /// Initializes a new instance of the <see cref="MigrationPlan"/> class. /// </summary> /// <param name="name">The name of the plan.</param> public MigrationPlan(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(name)); } Name = name; } /// <summary> /// If set to true the plan executor will ignore any current state persisted and /// run the plan from its initial state to its end state. /// </summary> public virtual bool IgnoreCurrentState { get; } = false; /// <summary> /// Gets the transitions. /// </summary> public IReadOnlyDictionary<string, Transition> Transitions => _transitions; public IReadOnlyList<Type> PostMigrationTypes => _postMigrationTypes; /// <summary> /// Gets the name of the plan. /// </summary> public string Name { get; } // adds a transition private MigrationPlan Add(string sourceState, string targetState, Type migration) { if (sourceState == null) throw new ArgumentNullException(nameof(sourceState), $"{nameof(sourceState)} is null, {nameof(MigrationPlan)}.{nameof(MigrationPlan.From)} must not have been called."); if (targetState == null) throw new ArgumentNullException(nameof(targetState)); if (string.IsNullOrWhiteSpace(targetState)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(targetState)); if (sourceState == targetState) throw new ArgumentException("Source and target state cannot be identical."); if (migration == null) throw new ArgumentNullException(nameof(migration)); if (!migration.Implements<MigrationBase>()) throw new ArgumentException($"Type {migration.Name} does not implement IMigration.", nameof(migration)); sourceState = sourceState.Trim(); targetState = targetState.Trim(); // throw if we already have a transition for that state which is not null, // null is used to keep track of the last step of the chain if (_transitions.ContainsKey(sourceState) && _transitions[sourceState] != null) throw new InvalidOperationException($"A transition from state \"{sourceState}\" has already been defined."); // register the transition _transitions[sourceState] = new Transition(sourceState, targetState, migration); // register the target state if we don't know it already // this is how we keep track of the final state - because // transitions could be defined in any order, that might // be overridden afterwards. if (!_transitions.ContainsKey(targetState)) _transitions.Add(targetState, null); _prevState = targetState; _finalState = null; // force re-validation return this; } /// <summary> /// Adds a transition to a target state through an empty migration. /// </summary> public MigrationPlan To(string targetState) => To<NoopMigration>(targetState); public MigrationPlan To(Guid targetState) => To<NoopMigration>(targetState.ToString()); /// <summary> /// Adds a transition to a target state through a migration. /// </summary> public MigrationPlan To<TMigration>(string targetState) where TMigration : MigrationBase => To(targetState, typeof(TMigration)); public MigrationPlan To<TMigration>(Guid targetState) where TMigration : MigrationBase => To(targetState, typeof(TMigration)); /// <summary> /// Adds a transition to a target state through a migration. /// </summary> public MigrationPlan To(string targetState, Type migration) => Add(_prevState, targetState, migration); public MigrationPlan To(Guid targetState, Type migration) => Add(_prevState, targetState.ToString(), migration); /// <summary> /// Sets the starting state. /// </summary> public MigrationPlan From(string sourceState) { _prevState = sourceState ?? throw new ArgumentNullException(nameof(sourceState)); return this; } /// <summary> /// Adds a transition to a target state through a migration, replacing a previous migration. /// </summary> /// <typeparam name="TMigrationNew">The new migration.</typeparam> /// <typeparam name="TMigrationRecover">The migration to use to recover from the previous target state.</typeparam> /// <param name="recoverState">The previous target state, which we need to recover from through <typeparamref name="TMigrationRecover"/>.</param> /// <param name="targetState">The new target state.</param> public MigrationPlan ToWithReplace<TMigrationNew, TMigrationRecover>(string recoverState, string targetState) where TMigrationNew : MigrationBase where TMigrationRecover : MigrationBase { To<TMigrationNew>(targetState); From(recoverState).To<TMigrationRecover>(targetState); return this; } /// <summary> /// Adds a transition to a target state through a migration, replacing a previous migration. /// </summary> /// <typeparam name="TMigrationNew">The new migration.</typeparam> /// <param name="recoverState">The previous target state, which we can recover from directly.</param> /// <param name="targetState">The new target state.</param> public MigrationPlan ToWithReplace<TMigrationNew>(string recoverState, string targetState) where TMigrationNew : MigrationBase { To<TMigrationNew>(targetState); From(recoverState).To(targetState); return this; } /// <summary> /// Adds transitions to a target state by cloning transitions from a start state to an end state. /// </summary> public MigrationPlan ToWithClone(string startState, string endState, string targetState) { if (startState == null) throw new ArgumentNullException(nameof(startState)); if (string.IsNullOrWhiteSpace(startState)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(startState)); if (endState == null) throw new ArgumentNullException(nameof(endState)); if (string.IsNullOrWhiteSpace(endState)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(endState)); if (targetState == null) throw new ArgumentNullException(nameof(targetState)); if (string.IsNullOrWhiteSpace(targetState)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(targetState)); if (startState == endState) throw new ArgumentException("Start and end states cannot be identical."); startState = startState.Trim(); endState = endState.Trim(); targetState = targetState.Trim(); var state = startState; var visited = new HashSet<string>(); while (state != endState) { if (visited.Contains(state)) throw new InvalidOperationException("A loop was detected in the copied chain."); visited.Add(state); if (!_transitions.TryGetValue(state, out var transition)) throw new InvalidOperationException($"There is no transition from state \"{state}\"."); var newTargetState = transition.TargetState == endState ? targetState : CreateRandomState(); To(newTargetState, transition.MigrationType); state = transition.TargetState; } return this; } /// <summary> /// Adds a post-migration to the plan. /// </summary> public virtual MigrationPlan AddPostMigration<TMigration>() where TMigration : MigrationBase { // TODO: Post migrations are obsolete/irrelevant. Notifications should be used instead. // The only place we use this is to clear cookies in the installer which could be done // via notification. Then we can clean up all the code related to post migrations which is // not insignificant. _postMigrationTypes.Add(typeof(TMigration)); return this; } /// <summary> /// Creates a random, unique state. /// </summary> public virtual string CreateRandomState() => Guid.NewGuid().ToString("B").ToUpper(); /// <summary> /// Begins a merge. /// </summary> public MergeBuilder Merge() => new MergeBuilder(this); /// <summary> /// Gets the initial state. /// </summary> /// <remarks>The initial state is the state when the plan has never /// run. By default, it is the empty string, but plans may override /// it if they have other ways of determining where to start from.</remarks> public virtual string InitialState => string.Empty; /// <summary> /// Gets the final state. /// </summary> public string FinalState { get { // modifying the plan clears _finalState // Validate() either sets _finalState, or throws if (_finalState == null) Validate(); return _finalState; } } /// <summary> /// Validates the plan. /// </summary> /// <returns>The plan's final state.</returns> public void Validate() { if (_finalState != null) return; // quick check for dead ends - a dead end is a transition that has a target state // that is not null and does not match any source state. such a target state has // been registered as a source state with a null transition. so there should be only // one. string finalState = null; foreach (var kvp in _transitions.Where(x => x.Value == null)) { if (finalState == null) finalState = kvp.Key; else throw new InvalidOperationException($"Multiple final states have been detected in the plan (\"{finalState}\", \"{kvp.Key}\")." + " Make sure the plan contains only one final state."); } // now check for loops var verified = new List<string>(); foreach (var transition in _transitions.Values) { if (transition == null || verified.Contains(transition.SourceState)) continue; var visited = new List<string> { transition.SourceState }; var nextTransition = _transitions[transition.TargetState]; while (nextTransition != null && !verified.Contains(nextTransition.SourceState)) { if (visited.Contains(nextTransition.SourceState)) throw new InvalidOperationException($"A loop has been detected in the plan around state \"{nextTransition.SourceState}\"." + " Make sure the plan does not contain circular transition paths."); visited.Add(nextTransition.SourceState); nextTransition = _transitions[nextTransition.TargetState]; } verified.AddRange(visited); } _finalState = finalState; } /// <summary> /// Throws an exception when the initial state is unknown. /// </summary> public virtual void ThrowOnUnknownInitialState(string state) { throw new InvalidOperationException($"The migration plan does not support migrating from state \"{state}\"."); } /// <summary> /// Follows a path (for tests and debugging). /// </summary> /// <remarks>Does the same thing Execute does, but does not actually execute migrations.</remarks> internal IReadOnlyList<string> FollowPath(string fromState = null, string toState = null) { toState = toState.NullOrWhiteSpaceAsNull(); Validate(); var origState = fromState ?? string.Empty; var states = new List<string> { origState }; if (!_transitions.TryGetValue(origState, out var transition)) throw new InvalidOperationException($"Unknown state \"{origState}\"."); while (transition != null) { var nextState = transition.TargetState; origState = nextState; states.Add(origState); if (nextState == toState) { transition = null; continue; } if (!_transitions.TryGetValue(origState, out transition)) throw new InvalidOperationException($"Unknown state \"{origState}\"."); } // safety check if (origState != (toState ?? _finalState)) throw new InvalidOperationException($"Internal error, reached state {origState} which is not state {toState ?? _finalState}"); return states; } /// <summary> /// Represents a plan transition. /// </summary> public class Transition { /// <summary> /// Initializes a new instance of the <see cref="Transition"/> class. /// </summary> public Transition(string sourceState, string targetState, Type migrationTtype) { SourceState = sourceState; TargetState = targetState; MigrationType = migrationTtype; } /// <summary> /// Gets the source state. /// </summary> public string SourceState { get; } /// <summary> /// Gets the target state. /// </summary> public string TargetState { get; } /// <summary> /// Gets the migration type. /// </summary> public Type MigrationType { get; } /// <inheritdoc /> public override string ToString() { return MigrationType == typeof(NoopMigration) ? $"{(SourceState == string.Empty ? "<empty>" : SourceState)} --> {TargetState}" : $"{SourceState} -- ({MigrationType.FullName}) --> {TargetState}"; } } } }
using System; using SubSonic.Schema; using SubSonic.DataProviders; using System.Data; namespace Solution.DataAccess.DataModel { /// <summary> /// Table: UploadFile /// Primary Key: Id /// </summary> public class UploadFileStructs: DatabaseTable { public UploadFileStructs(IDataProvider provider):base("UploadFile",provider){ ClassName = "UploadFile"; SchemaName = "dbo"; Columns.Add(new DatabaseColumn("Id", this) { IsPrimaryKey = true, DataType = DbType.Int32, IsNullable = false, AutoIncrement = true, IsForeignKey = false, MaxLength = 0, PropertyName = "Id" }); Columns.Add(new DatabaseColumn("Name", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "Name" }); Columns.Add(new DatabaseColumn("Path", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 200, PropertyName = "Path" }); Columns.Add(new DatabaseColumn("Ext", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 10, PropertyName = "Ext" }); Columns.Add(new DatabaseColumn("Src", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "Src" }); Columns.Add(new DatabaseColumn("Size", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "Size" }); Columns.Add(new DatabaseColumn("PicWidth", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "PicWidth" }); Columns.Add(new DatabaseColumn("PicHeight", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "PicHeight" }); Columns.Add(new DatabaseColumn("UploadConfig_Id", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "UploadConfig_Id" }); Columns.Add(new DatabaseColumn("JoinName", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "JoinName" }); Columns.Add(new DatabaseColumn("JoinId", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "JoinId" }); Columns.Add(new DatabaseColumn("UserType", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "UserType" }); Columns.Add(new DatabaseColumn("UserId", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "UserId" }); Columns.Add(new DatabaseColumn("UserName", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "UserName" }); Columns.Add(new DatabaseColumn("UserIp", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "UserIp" }); Columns.Add(new DatabaseColumn("AddDate", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "AddDate" }); Columns.Add(new DatabaseColumn("InfoText", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "InfoText" }); Columns.Add(new DatabaseColumn("RndKey", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 20, PropertyName = "RndKey" }); } public IColumn Id{ get{ return this.GetColumn("Id"); } } public IColumn Name{ get{ return this.GetColumn("Name"); } } public IColumn Path{ get{ return this.GetColumn("Path"); } } public IColumn Ext{ get{ return this.GetColumn("Ext"); } } public IColumn Src{ get{ return this.GetColumn("Src"); } } public IColumn Size{ get{ return this.GetColumn("Size"); } } public IColumn PicWidth{ get{ return this.GetColumn("PicWidth"); } } public IColumn PicHeight{ get{ return this.GetColumn("PicHeight"); } } public IColumn UploadConfig_Id{ get{ return this.GetColumn("UploadConfig_Id"); } } public IColumn JoinName{ get{ return this.GetColumn("JoinName"); } } public IColumn JoinId{ get{ return this.GetColumn("JoinId"); } } public IColumn UserType{ get{ return this.GetColumn("UserType"); } } public IColumn UserId{ get{ return this.GetColumn("UserId"); } } public IColumn UserName{ get{ return this.GetColumn("UserName"); } } public IColumn UserIp{ get{ return this.GetColumn("UserIp"); } } public IColumn AddDate{ get{ return this.GetColumn("AddDate"); } } public IColumn InfoText{ get{ return this.GetColumn("InfoText"); } } public IColumn RndKey{ get{ return this.GetColumn("RndKey"); } } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Cassandra.Mapping; using Cassandra.Tasks; using Cassandra.Tests.Mapping.Pocos; using Cassandra.Tests.Mapping.TestData; using Moq; using NUnit.Framework; namespace Cassandra.Tests.Mapping { [TestFixture] public class MapperExecutionProfileTests : MappingTestBase { [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteFetchWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { var usersExpected = TestDataHelper.GetUserList(); var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mapperAndSession = GetMappingClientAndSession(rowset); var cql = Cql.New("SELECT * FROM users") .WithOptions(opt => opt.SetConsistencyLevel(ConsistencyLevel.Quorum)) .WithExecutionProfile("testProfile"); var users = async ? mapperAndSession.Mapper.FetchAsync<PlainUser>(cql).Result : mapperAndSession.Mapper.Fetch<PlainUser>(cql); CollectionAssert.AreEqual(users, usersExpected, new TestHelper.PropertyComparer()); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteFetchPagedWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { var usersExpected = TestDataHelper.GetUserList(); var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mapperAndSession = GetMappingClientAndSession(rowset); var cql = Cql.New("SELECT * FROM users") .WithOptions(opt => opt.SetConsistencyLevel(ConsistencyLevel.Quorum)) .WithExecutionProfile("testProfile"); var users = async ? mapperAndSession.Mapper.FetchPageAsync<PlainUser>(cql).Result : mapperAndSession.Mapper.FetchPage<PlainUser>(cql); CollectionAssert.AreEqual(users.ToList(), usersExpected, new TestHelper.PropertyComparer()); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteFirstOrDefaultWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { var usersExpected = TestDataHelper.GetUserList(); var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mapperAndSession = GetMappingClientAndSession(rowset); var cql = Cql.New("SELECT * FROM users") .WithOptions(opt => opt.SetConsistencyLevel(ConsistencyLevel.Quorum)) .WithExecutionProfile("testProfile"); var user = async ? mapperAndSession.Mapper.FirstOrDefaultAsync<PlainUser>(cql).Result : mapperAndSession.Mapper.FirstOrDefault<PlainUser>(cql); CollectionAssert.AreEqual(new List<PlainUser> { usersExpected.First() }, new List<PlainUser> { user }, new TestHelper.PropertyComparer()); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteSingleOrDefaultWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { var usersExpected = new List<PlainUser> { TestDataHelper.GetUserList().First() }; var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mapperAndSession = GetMappingClientAndSession(rowset); var cql = Cql.New("SELECT * FROM users") .WithOptions(opt => opt.SetConsistencyLevel(ConsistencyLevel.Quorum)) .WithExecutionProfile("testProfile"); var user = async ? mapperAndSession.Mapper.SingleOrDefaultAsync<PlainUser>(cql).Result : mapperAndSession.Mapper.SingleOrDefault<PlainUser>(cql); CollectionAssert.AreEqual(usersExpected, new List<PlainUser> { user }, new TestHelper.PropertyComparer()); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteFirstWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { var usersExpected = TestDataHelper.GetUserList(); var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mapperAndSession = GetMappingClientAndSession(rowset); var cql = Cql.New("SELECT * FROM users") .WithOptions(opt => opt.SetConsistencyLevel(ConsistencyLevel.Quorum)) .WithExecutionProfile("testProfile"); var user = async ? mapperAndSession.Mapper.FirstAsync<PlainUser>(cql).Result : mapperAndSession.Mapper.First<PlainUser>(cql); CollectionAssert.AreEqual(new List<PlainUser> { usersExpected.First() }, new List<PlainUser> { user }, new TestHelper.PropertyComparer()); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteSingleWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { var usersExpected = new List<PlainUser> { TestDataHelper.GetUserList().First() }; var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mapperAndSession = GetMappingClientAndSession(rowset); var cql = Cql.New("SELECT * FROM users") .WithOptions(opt => opt.SetConsistencyLevel(ConsistencyLevel.Quorum)) .WithExecutionProfile("testProfile"); var user = async ? mapperAndSession.Mapper.SingleAsync<PlainUser>(cql).Result : mapperAndSession.Mapper.Single<PlainUser>(cql); CollectionAssert.AreEqual(usersExpected, new List<PlainUser> { user }, new TestHelper.PropertyComparer()); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteDeleteWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { string query = null; object[] parameters = null; var session = GetSession((q, args) => { query = q; parameters = args; }, new RowSet()); var mapper = new Mapper(session, new MappingConfiguration().Define(new Map<Song>().PartitionKey(s => s.Id))); var song = new Song {Id = Guid.NewGuid()}; if (async) { mapper.DeleteAsync(song, "testProfile").Wait(); } else { mapper.Delete(song, "testProfile"); } Assert.AreEqual("DELETE FROM Song WHERE Id = ?", query); CollectionAssert.AreEqual(new object[] { song.Id }, parameters); Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteDeleteIfWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { string query = null; var session = GetSession((q, args) => query = q, new RowSet()); var mapper = new Mapper(session, new MappingConfiguration()); if (async) { mapper.DeleteIfAsync<Song>(Cql.New("WHERE id = ? IF title = ?", Guid.NewGuid(), "All of My love").WithExecutionProfile("testProfile")).Wait(); } else { mapper.DeleteIf<Song>(Cql.New("WHERE id = ? IF title = ?", Guid.NewGuid(), "All of My love").WithExecutionProfile("testProfile")); } Assert.AreEqual("DELETE FROM Song WHERE id = ? IF title = ?", query); Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteInsertWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { string query = null; object[] parameters = null; var mapperAndSession = GetMappingClientAndSession(() => TaskHelper.ToTask(RowSet.Empty()), (q, p) => { query = q; parameters = p; }); var song = new Song { Id = Guid.NewGuid() }; const int ttl = 600; if (async) { mapperAndSession.Mapper.InsertAsync(song, "testProfile", false, ttl).Wait(); } else { mapperAndSession.Mapper.Insert(song, "testProfile", false, ttl); } Assert.AreEqual("INSERT INTO Song (Id, ReleaseDate) VALUES (?, ?) USING TTL ?", query); Assert.AreEqual(song.Id, parameters[0]); Assert.AreEqual(ttl, parameters.Last()); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } [Test] [TestCase(true)] [TestCase(false)] public void Should_ExecuteInsertIfNotExistsWithExecutionProfile_When_ExecutionProfileIsProvided(bool async) { string query = null; object[] parameters = null; var mapperAndSession = GetMappingClientAndSession(() => TaskHelper.ToTask(RowSet.Empty()), (q, p) => { query = q; parameters = p; }); var song = new Song { Id = Guid.NewGuid(), Title = "t2", ReleaseDate = DateTimeOffset.Now }; const int ttl = 600; if (async) { mapperAndSession.Mapper.InsertIfNotExistsAsync(song, "testProfile", false, ttl).Wait(); } else { mapperAndSession.Mapper.InsertIfNotExists(song, "testProfile", false, ttl); } Assert.AreEqual("INSERT INTO Song (Id, ReleaseDate, Title) VALUES (?, ?, ?) IF NOT EXISTS USING TTL ?", query); Assert.AreEqual(song.Id, parameters[0]); Assert.AreEqual(song.ReleaseDate, parameters[1]); Assert.AreEqual(song.Title, parameters[2]); Assert.AreEqual(ttl, parameters[3]); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>(), "testProfile"), Times.Once); Mock.Get(mapperAndSession.Session).Verify(s => s.ExecuteAsync(It.IsAny<IStatement>()), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>(), "testProfile"), Times.Never); Mock.Get(mapperAndSession.Session).Verify(s => s.Execute(It.IsAny<IStatement>()), Times.Never); } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPriceSet { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPriceSet() : base() { Load += frmPriceSet_Load; FormClosed += frmPriceSet_FormClosed; KeyDown += frmPriceSet_KeyDown; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.TextBox txtholdvalue; private System.Windows.Forms.Button withEventsField_cmdEdit; public System.Windows.Forms.Button cmdEdit { get { return withEventsField_cmdEdit; } set { if (withEventsField_cmdEdit != null) { withEventsField_cmdEdit.Click -= cmdEdit_Click; } withEventsField_cmdEdit = value; if (withEventsField_cmdEdit != null) { withEventsField_cmdEdit.Click += cmdEdit_Click; } } } private System.Windows.Forms.Button withEventsField_cmdEmulate; public System.Windows.Forms.Button cmdEmulate { get { return withEventsField_cmdEmulate; } set { if (withEventsField_cmdEmulate != null) { withEventsField_cmdEmulate.Click -= cmdEmulate_Click; } withEventsField_cmdEmulate = value; if (withEventsField_cmdEmulate != null) { withEventsField_cmdEmulate.Click += cmdEmulate_Click; } } } public System.Windows.Forms.CheckBox _chkFields_0; private System.Windows.Forms.TextBox withEventsField__txtFields_0; public System.Windows.Forms.TextBox _txtFields_0 { get { return withEventsField__txtFields_0; } set { if (withEventsField__txtFields_0 != null) { withEventsField__txtFields_0.TextChanged -= txtFields_TextChanged; withEventsField__txtFields_0.Enter -= txtFields_Enter; } withEventsField__txtFields_0 = value; if (withEventsField__txtFields_0 != null) { withEventsField__txtFields_0.TextChanged += txtFields_TextChanged; withEventsField__txtFields_0.Enter += txtFields_Enter; } } } private System.Windows.Forms.Button withEventsField_cmdPrintAll; public System.Windows.Forms.Button cmdPrintAll { get { return withEventsField_cmdPrintAll; } set { if (withEventsField_cmdPrintAll != null) { withEventsField_cmdPrintAll.Click -= cmdPrintAll_Click; } withEventsField_cmdPrintAll = value; if (withEventsField_cmdPrintAll != null) { withEventsField_cmdPrintAll.Click += cmdPrintAll_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPrint; public System.Windows.Forms.Button cmdPrint { get { return withEventsField_cmdPrint; } set { if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click -= cmdPrint_Click; } withEventsField_cmdPrint = value; if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click += cmdPrint_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label _lblLabels_1; public System.Windows.Forms.Label lblStockItem; public System.Windows.Forms.Label _lblLabels_0; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public System.Windows.Forms.Label _lbl_5; //Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this.txtholdvalue = new System.Windows.Forms.TextBox(); this.cmdEdit = new System.Windows.Forms.Button(); this.cmdEmulate = new System.Windows.Forms.Button(); this._chkFields_0 = new System.Windows.Forms.CheckBox(); this._txtFields_0 = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdPrintAll = new System.Windows.Forms.Button(); this.cmdPrint = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this._lblLabels_1 = new System.Windows.Forms.Label(); this.lblStockItem = new System.Windows.Forms.Label(); this._lblLabels_0 = new System.Windows.Forms.Label(); this._lbl_5 = new System.Windows.Forms.Label(); this.picButtons.SuspendLayout(); this.SuspendLayout(); // //ShapeContainer1 // this.ShapeContainer1.Location = new System.Drawing.Point(0, 0); this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0); this.ShapeContainer1.Name = "ShapeContainer1"; this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this._Shape1_2 }); this.ShapeContainer1.Size = new System.Drawing.Size(408, 204); this.ShapeContainer1.TabIndex = 13; this.ShapeContainer1.TabStop = false; // //_Shape1_2 // this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.Location = new System.Drawing.Point(9, 60); this._Shape1_2.Name = "_Shape1_2"; this._Shape1_2.Size = new System.Drawing.Size(322, 112); // //txtholdvalue // this.txtholdvalue.AcceptsReturn = true; this.txtholdvalue.BackColor = System.Drawing.SystemColors.Window; this.txtholdvalue.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtholdvalue.ForeColor = System.Drawing.SystemColors.WindowText; this.txtholdvalue.Location = new System.Drawing.Point(90, 236); this.txtholdvalue.MaxLength = 0; this.txtholdvalue.Name = "txtholdvalue"; this.txtholdvalue.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtholdvalue.Size = new System.Drawing.Size(71, 19); this.txtholdvalue.TabIndex = 12; // //cmdEdit // this.cmdEdit.BackColor = System.Drawing.SystemColors.Control; this.cmdEdit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdEdit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdEdit.Location = new System.Drawing.Point(282, 147); this.cmdEdit.Name = "cmdEdit"; this.cmdEdit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdEdit.Size = new System.Drawing.Size(37, 17); this.cmdEdit.TabIndex = 11; this.cmdEdit.Text = "&Edit"; this.cmdEdit.UseVisualStyleBackColor = false; // //cmdEmulate // this.cmdEmulate.BackColor = System.Drawing.SystemColors.Control; this.cmdEmulate.Cursor = System.Windows.Forms.Cursors.Default; this.cmdEmulate.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdEmulate.Location = new System.Drawing.Point(282, 128); this.cmdEmulate.Name = "cmdEmulate"; this.cmdEmulate.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdEmulate.Size = new System.Drawing.Size(37, 17); this.cmdEmulate.TabIndex = 10; this.cmdEmulate.Text = "..."; this.cmdEmulate.UseVisualStyleBackColor = false; // //_chkFields_0 // this._chkFields_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkFields_0.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkFields_0.Cursor = System.Windows.Forms.Cursors.Default; this._chkFields_0.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkFields_0.ForeColor = System.Drawing.SystemColors.WindowText; this._chkFields_0.Location = new System.Drawing.Point(222, 90); this._chkFields_0.Name = "_chkFields_0"; this._chkFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkFields_0.Size = new System.Drawing.Size(97, 19); this._chkFields_0.TabIndex = 6; this._chkFields_0.Text = "Disable this Set:"; this._chkFields_0.UseVisualStyleBackColor = false; // //_txtFields_0 // this._txtFields_0.AcceptsReturn = true; this._txtFields_0.BackColor = System.Drawing.SystemColors.Window; this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_0.Location = new System.Drawing.Point(96, 66); this._txtFields_0.MaxLength = 0; this._txtFields_0.Name = "_txtFields_0"; this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_0.Size = new System.Drawing.Size(226, 19); this._txtFields_0.TabIndex = 5; // //picButtons // this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Controls.Add(this.cmdPrintAll); this.picButtons.Controls.Add(this.cmdPrint); this.picButtons.Controls.Add(this.cmdCancel); this.picButtons.Controls.Add(this.cmdClose); this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.Name = "picButtons"; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Size = new System.Drawing.Size(408, 39); this.picButtons.TabIndex = 2; // //cmdPrintAll // this.cmdPrintAll.BackColor = System.Drawing.SystemColors.Control; this.cmdPrintAll.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrintAll.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrintAll.Location = new System.Drawing.Point(96, 3); this.cmdPrintAll.Name = "cmdPrintAll"; this.cmdPrintAll.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrintAll.Size = new System.Drawing.Size(73, 29); this.cmdPrintAll.TabIndex = 13; this.cmdPrintAll.Text = "&Print All"; this.cmdPrintAll.UseVisualStyleBackColor = false; // //cmdPrint // this.cmdPrint.BackColor = System.Drawing.SystemColors.Control; this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrint.Location = new System.Drawing.Point(183, 3); this.cmdPrint.Name = "cmdPrint"; this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrint.Size = new System.Drawing.Size(73, 29); this.cmdPrint.TabIndex = 7; this.cmdPrint.TabStop = false; this.cmdPrint.Text = "&Print"; this.cmdPrint.UseVisualStyleBackColor = false; // //cmdCancel // this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Location = new System.Drawing.Point(5, 3); this.cmdCancel.Name = "cmdCancel"; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.TabIndex = 1; this.cmdCancel.TabStop = false; this.cmdCancel.Text = "&Undo"; this.cmdCancel.UseVisualStyleBackColor = false; // //cmdClose // this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Location = new System.Drawing.Point(261, 3); this.cmdClose.Name = "cmdClose"; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.TabIndex = 0; this.cmdClose.TabStop = false; this.cmdClose.Text = "E&xit"; this.cmdClose.UseVisualStyleBackColor = false; // //_lblLabels_1 // this._lblLabels_1.AutoSize = true; this._lblLabels_1.BackColor = System.Drawing.Color.Transparent; this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_1.Location = new System.Drawing.Point(16, 114); this._lblLabels_1.Name = "_lblLabels_1"; this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_1.Size = new System.Drawing.Size(98, 13); this._lblLabels_1.TabIndex = 9; this._lblLabels_1.Text = "Primary Stock Item:"; this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight; // //lblStockItem // this.lblStockItem.BackColor = System.Drawing.SystemColors.Control; this.lblStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.lblStockItem.ForeColor = System.Drawing.SystemColors.ControlText; this.lblStockItem.Location = new System.Drawing.Point(15, 129); this.lblStockItem.Name = "lblStockItem"; this.lblStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblStockItem.Size = new System.Drawing.Size(262, 16); this.lblStockItem.TabIndex = 8; this.lblStockItem.Text = "No Stock Item Selected"; // //_lblLabels_0 // this._lblLabels_0.AutoSize = true; this._lblLabels_0.BackColor = System.Drawing.Color.Transparent; this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_0.Location = new System.Drawing.Point(14, 69); this._lblLabels_0.Name = "_lblLabels_0"; this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_0.Size = new System.Drawing.Size(84, 13); this._lblLabels_0.TabIndex = 4; this._lblLabels_0.Text = "Price Set Name:"; this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lbl_5 // this._lbl_5.AutoSize = true; this._lbl_5.BackColor = System.Drawing.Color.Transparent; this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_5.Location = new System.Drawing.Point(9, 45); this._lbl_5.Name = "_lbl_5"; this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_5.Size = new System.Drawing.Size(56, 13); this._lbl_5.TabIndex = 3; this._lbl_5.Text = "&1. General"; // //frmPriceSet // this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224))); this.ClientSize = new System.Drawing.Size(408, 204); this.ControlBox = false; this.Controls.Add(this.txtholdvalue); this.Controls.Add(this.cmdEdit); this.Controls.Add(this.cmdEmulate); this.Controls.Add(this._chkFields_0); this.Controls.Add(this._txtFields_0); this.Controls.Add(this.picButtons); this.Controls.Add(this._lblLabels_1); this.Controls.Add(this.lblStockItem); this.Controls.Add(this._lblLabels_0); this.Controls.Add(this._lbl_5); this.Controls.Add(this.ShapeContainer1); this.Cursor = System.Windows.Forms.Cursors.Default; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.KeyPreview = true; this.Location = new System.Drawing.Point(73, 22); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmPriceSet"; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Edit Pricing Set Details"; this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using NUnit.Framework; using System; using System.Xml.Linq; using System.Linq; using JohnMoore.AmpacheNet.DataAccess; using JohnMoore.AmpacheNet.Entities; namespace JohnMoore.AmpacheNet.DataAccess.Tests { [TestFixture()] public class SongFactoryFixture { [Test()] [ExpectedException(typeof(System.Xml.XmlException))] public void SongFactoryConstructBadXmlTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <albums> <name>Back in Black</name> <artist id=""129348"">AC/DC</artist> <year>1984</year> <tracks>12</tracks> <disk>1</disk> <tag id=""2482"" count=""1"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </albums>"); var actual = target.Construct(raw); Assert.Fail(); } [Test] [ExpectedException(typeof(System.Xml.XmlException))] public void PlaylistFactoryConstructMissingTitleTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <artist id=""129348"">AC/DC</artist> <album id=""2910"">Back in Black</album> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <track>4</track> <time>234</time> <url>http://localhost/play/index.php?oid=123908...</url> <size>Song Filesize in Bytes</size> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.Fail(); } [Test] [ExpectedException(typeof(System.Xml.XmlException))] public void PlaylistFactoryConstructMissingUrlTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <artist id=""129348"">AC/DC</artist> <album id=""2910"">Back in Black</album> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <track>4</track> <time>234</time> <size>Song Filesize in Bytes</size> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.Fail(); } [Test] public void PlaylistFactoryConstructNormalTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <artist id=""129348"">AC/DC</artist> <album id=""2910"">Back in Black</album> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <track>4</track> <time>234</time> <url>http://localhost/play/index.php?oid=123908...</url> <size>Song Filesize in Bytes</size> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.That(actual.Name, Is.EqualTo("Hells Bells")); Assert.That(actual.AlbumId, Is.EqualTo(2910)); Assert.That(actual.AlbumName, Is.EqualTo("Back in Black")); Assert.That(actual.ArtistId, Is.EqualTo(129348)); Assert.That(actual.ArtistName, Is.EqualTo("AC/DC")); Assert.That(actual.ArtId, Is.EqualTo(2910)); Assert.That(actual.ArtUrl, Is.EqualTo("http://localhost/image.php?id=129348")); Assert.That(actual.PerciseRating, Is.EqualTo(3)); Assert.That(actual.Rating, Is.EqualTo(3)); Assert.That(actual.Tags.Count, Is.EqualTo(3)); Assert.That(actual.TrackLength, Is.EqualTo(TimeSpan.FromSeconds(234))); Assert.That(actual.TrackNumber, Is.EqualTo(4)); Assert.That(actual.Url, Is.EqualTo("http://localhost/play/index.php?oid=123908...")); } [Test] public void PlaylistFactoryConstructMissingArtistTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <album id=""2910"">Back in Black</album> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <track>4</track> <time>234</time> <url>http://localhost/play/index.php?oid=123908...</url> <size>Song Filesize in Bytes</size> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.That(actual.Name, Is.EqualTo("Hells Bells")); Assert.That(actual.AlbumId, Is.EqualTo(2910)); Assert.That(actual.AlbumName, Is.EqualTo("Back in Black")); Assert.That(actual.ArtistId, Is.EqualTo(0)); Assert.That(actual.ArtistName, Is.Null); Assert.That(actual.ArtId, Is.EqualTo(2910)); Assert.That(actual.ArtUrl, Is.EqualTo("http://localhost/image.php?id=129348")); Assert.That(actual.PerciseRating, Is.EqualTo(3)); Assert.That(actual.Rating, Is.EqualTo(3)); Assert.That(actual.Tags.Count, Is.EqualTo(3)); Assert.That(actual.TrackLength, Is.EqualTo(TimeSpan.FromSeconds(234))); Assert.That(actual.TrackNumber, Is.EqualTo(4)); Assert.That(actual.Url, Is.EqualTo("http://localhost/play/index.php?oid=123908...")); } [Test] public void PlaylistFactoryConstructMissingAlbumTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <artist id=""129348"">AC/DC</artist> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <track>4</track> <time>234</time> <url>http://localhost/play/index.php?oid=123908...</url> <size>Song Filesize in Bytes</size> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.That(actual.Name, Is.EqualTo("Hells Bells")); Assert.That(actual.AlbumId, Is.EqualTo(0)); Assert.That(actual.AlbumName, Is.Null); Assert.That(actual.ArtistId, Is.EqualTo(129348)); Assert.That(actual.ArtistName, Is.EqualTo("AC/DC")); Assert.That(actual.ArtId, Is.EqualTo(0)); Assert.That(actual.ArtUrl, Is.EqualTo("http://localhost/image.php?id=129348")); Assert.That(actual.PerciseRating, Is.EqualTo(3)); Assert.That(actual.Rating, Is.EqualTo(3)); Assert.That(actual.Tags.Count, Is.EqualTo(3)); Assert.That(actual.TrackLength, Is.EqualTo(TimeSpan.FromSeconds(234))); Assert.That(actual.TrackNumber, Is.EqualTo(4)); Assert.That(actual.Url, Is.EqualTo("http://localhost/play/index.php?oid=123908...")); } [Test] public void PlaylistFactoryConstructMissingTagsTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <artist id=""129348"">AC/DC</artist> <album id=""2910"">Back in Black</album> <track>4</track> <time>234</time> <url>http://localhost/play/index.php?oid=123908...</url> <size>Song Filesize in Bytes</size> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.That(actual.Name, Is.EqualTo("Hells Bells")); Assert.That(actual.AlbumId, Is.EqualTo(2910)); Assert.That(actual.AlbumName, Is.EqualTo("Back in Black")); Assert.That(actual.ArtistId, Is.EqualTo(129348)); Assert.That(actual.ArtistName, Is.EqualTo("AC/DC")); Assert.That(actual.ArtId, Is.EqualTo(2910)); Assert.That(actual.ArtUrl, Is.EqualTo("http://localhost/image.php?id=129348")); Assert.That(actual.PerciseRating, Is.EqualTo(3)); Assert.That(actual.Rating, Is.EqualTo(3)); Assert.That(actual.Tags.Count, Is.EqualTo(0)); Assert.That(actual.TrackLength, Is.EqualTo(TimeSpan.FromSeconds(234))); Assert.That(actual.TrackNumber, Is.EqualTo(4)); Assert.That(actual.Url, Is.EqualTo("http://localhost/play/index.php?oid=123908...")); } [Test] public void PlaylistFactoryConstructMissingTrackTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <artist id=""129348"">AC/DC</artist> <album id=""2910"">Back in Black</album> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <time>234</time> <url>http://localhost/play/index.php?oid=123908...</url> <size>Song Filesize in Bytes</size> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.That(actual.Name, Is.EqualTo("Hells Bells")); Assert.That(actual.AlbumId, Is.EqualTo(2910)); Assert.That(actual.AlbumName, Is.EqualTo("Back in Black")); Assert.That(actual.ArtistId, Is.EqualTo(129348)); Assert.That(actual.ArtistName, Is.EqualTo("AC/DC")); Assert.That(actual.ArtId, Is.EqualTo(2910)); Assert.That(actual.ArtUrl, Is.EqualTo("http://localhost/image.php?id=129348")); Assert.That(actual.PerciseRating, Is.EqualTo(3)); Assert.That(actual.Rating, Is.EqualTo(3)); Assert.That(actual.Tags.Count, Is.EqualTo(3)); Assert.That(actual.TrackLength, Is.EqualTo(TimeSpan.FromSeconds(234))); Assert.That(actual.TrackNumber, Is.EqualTo(0)); Assert.That(actual.Url, Is.EqualTo("http://localhost/play/index.php?oid=123908...")); } [Test] public void PlaylistFactoryConstructMissingLengthTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <artist id=""129348"">AC/DC</artist> <album id=""2910"">Back in Black</album> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <track>4</track> <url>http://localhost/play/index.php?oid=123908...</url> <size>Song Filesize in Bytes</size> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.That(actual.Name, Is.EqualTo("Hells Bells")); Assert.That(actual.AlbumId, Is.EqualTo(2910)); Assert.That(actual.AlbumName, Is.EqualTo("Back in Black")); Assert.That(actual.ArtistId, Is.EqualTo(129348)); Assert.That(actual.ArtistName, Is.EqualTo("AC/DC")); Assert.That(actual.ArtId, Is.EqualTo(2910)); Assert.That(actual.ArtUrl, Is.EqualTo("http://localhost/image.php?id=129348")); Assert.That(actual.PerciseRating, Is.EqualTo(3)); Assert.That(actual.Rating, Is.EqualTo(3)); Assert.That(actual.Tags.Count, Is.EqualTo(3)); Assert.That(actual.TrackLength, Is.EqualTo(TimeSpan.Zero)); Assert.That(actual.TrackNumber, Is.EqualTo(4)); Assert.That(actual.Url, Is.EqualTo("http://localhost/play/index.php?oid=123908...")); } [Test] public void PlaylistFactoryConstructMissingSizeTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <artist id=""129348"">AC/DC</artist> <album id=""2910"">Back in Black</album> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <track>4</track> <time>234</time> <url>http://localhost/play/index.php?oid=123908...</url> <art>http://localhost/image.php?id=129348</art> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.That(actual.Name, Is.EqualTo("Hells Bells")); Assert.That(actual.AlbumId, Is.EqualTo(2910)); Assert.That(actual.AlbumName, Is.EqualTo("Back in Black")); Assert.That(actual.ArtistId, Is.EqualTo(129348)); Assert.That(actual.ArtistName, Is.EqualTo("AC/DC")); Assert.That(actual.ArtId, Is.EqualTo(2910)); Assert.That(actual.ArtUrl, Is.EqualTo("http://localhost/image.php?id=129348")); Assert.That(actual.PerciseRating, Is.EqualTo(3)); Assert.That(actual.Rating, Is.EqualTo(3)); Assert.That(actual.Tags.Count, Is.EqualTo(3)); Assert.That(actual.TrackLength, Is.EqualTo(TimeSpan.FromSeconds(234))); Assert.That(actual.TrackNumber, Is.EqualTo(4)); Assert.That(actual.Url, Is.EqualTo("http://localhost/play/index.php?oid=123908...")); } [Test] public void PlaylistFactoryConstructMissingArtTest () { var target = new SongFactory(); var raw = XElement.Parse(@" <song id=""3180""> <title>Hells Bells</title> <artist id=""129348"">AC/DC</artist> <album id=""2910"">Back in Black</album> <tag id=""2481"" count=""3"">Rock &amp; Roll</tag> <tag id=""2482"" count=""1"">Rock</tag> <tag id=""2483"" count=""1"">Roll</tag> <track>4</track> <time>234</time> <url>http://localhost/play/index.php?oid=123908...</url> <size>Song Filesize in Bytes</size> <preciserating>3</preciserating> <rating>2.9</rating> </song>"); var actual = target.Construct(raw); Assert.That(actual.Name, Is.EqualTo("Hells Bells")); Assert.That(actual.AlbumId, Is.EqualTo(2910)); Assert.That(actual.AlbumName, Is.EqualTo("Back in Black")); Assert.That(actual.ArtistId, Is.EqualTo(129348)); Assert.That(actual.ArtistName, Is.EqualTo("AC/DC")); Assert.That(actual.ArtId, Is.EqualTo(2910)); Assert.That(actual.ArtUrl, Is.Null); Assert.That(actual.PerciseRating, Is.EqualTo(3)); Assert.That(actual.Rating, Is.EqualTo(3)); Assert.That(actual.Tags.Count, Is.EqualTo(3)); Assert.That(actual.TrackLength, Is.EqualTo(TimeSpan.FromSeconds(234))); Assert.That(actual.TrackNumber, Is.EqualTo(4)); Assert.That(actual.Url, Is.EqualTo("http://localhost/play/index.php?oid=123908...")); } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using log4net; namespace MindTouch.Tasking { using Yield = IEnumerator<IYield>; /// <summary> /// Provides Extension methods on <see cref="AResult"/>, <see cref="Result"/> and <see cref="Result{T}"/> for working with them in /// the context of <see cref="Coroutine"/> execution. /// </summary> public static class CoroutineUtil { //--- Types --- private sealed class SetAndContinue<T> : IYield, IContinuation { //--- Fields --- private readonly Result<T> _result; private readonly Action<T> _callback; private IContinuation _continuation; private Exception _exception; //--- Constructors --- public SetAndContinue(Result<T> result, Action<T> callback) { _result = result; _callback = callback; } //--- Properties --- public Exception Exception { get { return _exception ?? _result.Exception; } } //--- Methods --- public bool CanContinueImmediately(IContinuation continuation) { _continuation = continuation; // check if we can resume immediately; if not, use this object as the continuation bool result = ((IYield)_result).CanContinueImmediately(this); // check if we have a value for our callback if(result && _result.HasValue) { try { _callback(_result.Value); } catch(Exception e) { _exception = e; } } return result; } public void Continue() { // check if we have a value for our callback if(_result.HasValue) { try { _callback(_result.Value); } catch(Exception e) { _exception = e; } } // continue coroutine _continuation.Continue(); } } private sealed class LogExceptionAndContinue : IYield, IContinuation { //--- Fields --- private readonly AResult _result; private readonly ILog _log; private readonly string _message; private IContinuation _continuation; //--- Constructors --- public LogExceptionAndContinue(AResult result, ILog log, string message) { _result = result; _log = log; _message = message ?? "unhandled exception occurred in coroutine"; } //--- Properties --- public Exception Exception { get { return _result.Exception; } } //--- Methods --- public bool CanContinueImmediately(IContinuation continuation) { _continuation = continuation; // check if we can resume immediately; if not, use this object as the continuation bool result = ((IYield)_result).CanContinueImmediately(this); // check if we have an exception to log if(result && _result.HasException) { _log.Warn(_message, _result.Exception); } return result; } public void Continue() { // check if we have an exception to log if(_result.HasException) { _log.Warn(_message, _result.Exception); } // continue coroutine _continuation.Continue(); } } private sealed class EnumerateAll : IYield, IContinuation { //--- Fields --- private readonly IEnumerator<IYield> _results; private IContinuation _continuation; //--- Constructors --- public EnumerateAll(IEnumerator<IYield> results) { _results = results; } //--- Properties --- public Exception Exception { get { return null; } } //--- Methods --- public bool CanContinueImmediately(IContinuation continuation) { _continuation = continuation; // loop over each IYield instance and check if we need to continue later while(_results.MoveNext()) { if(!_results.Current.CanContinueImmediately(this)) { return false; } } // all IYield instances completed; time to dispose of the enumerator _results.Dispose(); return true; } public void Continue() { // loop over remaining IYield instance and check if we need to continue later while(_results.MoveNext()) { if(!_results.Current.CanContinueImmediately(this)) { return; } } // all IYield instances completed; time to dispose of the enumerator _results.Dispose(); // continue coroutine _continuation.Continue(); } } //--- Constants --- private const string COROUTINE_KEY = "coroutine"; //--- AResult/Result/Result<T> Extension Methods --- /// <summary> /// Sets the current coroutine's behavior to catch its exception so that the invoking context can examine the exception, rather than it /// bubbling up the Coroutine stack. /// </summary> /// <remarks> /// The <see cref="Coroutine.Invoke"/> analog to calling a method with a try/catch around it. /// </remarks> /// <typeparam name="T">Type of AResult derivative value.</typeparam> /// <param name="result">Coroutine synchronization handle.</param> /// <returns>Coroutine synchronization handle.</returns> public static T Catch<T>(this T result) where T : AResult { // Note (arnec): this overload exists, because without it yield on async methods (not Coroutine.Invoke'd) // require the result type T to be specified because it can't infer it. // I.e. method Result<Foo> Method(Result<Foo> result) requires a .Catch<Foo>() instead of .Catch() without // this overloaded extension. Coroutine.Current.Mode = CoroutineExceptionHandlingMode.CatchOnce; return result; } /// <summary> /// Sets the current's coroutine behavior to catch its exception so that the invoking context can examine the exception, rather than it /// bubbling up the Coroutine stack. /// </summary> /// <remarks> /// The <see cref="Coroutine.Invoke"/> analog to calling a method with a try/catch around it. /// </remarks> /// <param name="result">Coroutine synchronization handle.</param> /// <returns>Coroutine synchronization handle.</returns> public static Result Catch(this Result result) { Coroutine.Current.Mode = CoroutineExceptionHandlingMode.CatchOnce; return result; } /// <summary> /// Sets the current coroutine's behavior to catch its exception so that the invoking context can examine the exception, rather than it /// bubbling up the Coroutine stack. /// </summary> /// <remarks> /// The <see cref="Coroutine.Invoke"/> analog to calling a method with a try/catch around it. /// </remarks> /// <typeparam name="T">Type of result's value.</typeparam> /// <param name="result">Coroutine synchronization handle.</param> /// <returns>Coroutine synchronization handle.</returns> public static Result<T> Catch<T>(this Result<T> result) { Coroutine.Current.Mode = CoroutineExceptionHandlingMode.CatchOnce; return result; } /// <summary> /// Sets the current coroutine's behavior to catch any exception thrown by a coroutine and log the exception, /// but continue with the caller's context. /// </summary> /// <param name="result">Coroutine synchronization handle.</param> /// <param name="log">Logger instance to use for the exception logging.</param> /// <returns>Iterator used by <see cref="Coroutine"/>.</returns> public static IYield CatchAndLog(this AResult result, ILog log) { return CatchAndLog(result, log, null); } /// <summary> /// Sets the current coroutine's behavior to catch any exception thrown by a coroutine and log the exception, /// but continue with the caller's context. /// </summary> /// <param name="result">Coroutine synchronization handle.</param> /// <param name="log">Logger instance to use for the exception logging.</param> /// <param name="message">Additional message to log along with exception</param> /// <returns>Iterator used by <see cref="Coroutine"/>.</returns> public static IYield CatchAndLog(this AResult result, ILog log, string message) { if(result == null) { throw new ArgumentNullException("result"); } if(log == null) { throw new ArgumentNullException("log"); } Coroutine.Current.Mode = CoroutineExceptionHandlingMode.CatchOnce; return new LogExceptionAndContinue(result, log, message); } /// <summary> /// Sets a callback for capturing the result's value. /// </summary> /// <remarks> /// Using the callback allows the value to be captured into a local variable rather than having to define /// a result instance before invoking the coroutine that would only be used to extract the value from after invocation.</remarks> /// <typeparam name="T">Type of result's value.</typeparam> /// <param name="result">Coroutine synchronization handle.</param> /// <param name="callback">Callback action to invoke on successful completion of the synchronization handle.</param> /// <returns>Iterator used by <see cref="Coroutine"/>.</returns> public static IYield Set<T>(this Result<T> result, Action<T> callback) { if(result == null) { throw new ArgumentNullException("result"); } if(callback == null) { throw new ArgumentNullException("callback"); } return new SetAndContinue<T>(result, callback); } /// <summary> /// Yield execution of the current coroutine untill all the results have completed. /// </summary> /// <typeparam name="TResult">Type of the result value.</typeparam> /// <param name="list">List of result instances to yield execution to.</param> /// <returns>Iterator used by <see cref="Coroutine"/>.</returns> public static IYield Join<TResult>(this IEnumerable<TResult> list) where TResult : AResult { return new EnumerateAll(list.Cast<IYield>().GetEnumerator()); } //--- Exception Extension Methods --- /// <summary> /// Extract the coroutine context from an exception that was thrown as part of an invoke. /// </summary> /// <param name="exception">Exception to examine.</param> /// <returns>The coroutine instance if the exception was thrown in the context of a coroutine, <see langword="null"/> otherwise.</returns> public static Coroutine GetCoroutineInfo(this Exception exception) { if(exception == null) { return null; } return exception.Data[COROUTINE_KEY] as Coroutine; } /// <summary> /// Get the coroutine invocation stack trace, including exception stack traces, and values of inner exceptions' coroutine stack traces. /// </summary> /// <param name="exception">Exception to examine.</param> /// <returns> /// A string representation of stack trace if the exception was thrown in the context of a coroutine, <see langword="null"/> otherwise. /// </returns> public static string GetCoroutineStackTrace(this Exception exception) { if(exception == null) { throw new ArgumentNullException("exception"); } // render exception message var result = new StringBuilder(); result.Append(exception.GetType().FullName); var message = exception.Message; if(!string.IsNullOrEmpty(message)) { result.Append(": "); result.Append(message); } // check if there is an inner exception to render if(exception.InnerException != null) { result.Append(" ---> "); result.AppendLine(exception.InnerException.GetCoroutineStackTrace()); result.Append(" --- End of inner exception stack trace ---"); } // render exception stack trace result.AppendLine(); result.Append(exception.StackTrace); // check if exception has a coroutine stack trace associated with it var coroutine = exception.GetCoroutineInfo(); if(coroutine != null) { result.AppendLine(); result.AppendLine(" --- End of exception stack trace ---"); // render coroutine stack trace foreach(var entry in coroutine.GetStackTrace()) { result.AppendLine(string.Format(" at {0}", entry.FullName)); } result.Append(" --- End of coroutine stack trace ---"); } return result.ToString(); } internal static void SetCoroutineInfo(this Exception exception) { exception.SetCoroutineInfo(Coroutine.Current); } internal static void SetCoroutineInfo(this Exception exception, Coroutine coroutine) { if((coroutine != null) && (exception.Data[COROUTINE_KEY] == null)) { exception.Data[COROUTINE_KEY] = coroutine; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ExpressionTreeVisitors; using Remotion.Linq.Clauses.ResultOperators; using Remotion.Linq.Parsing; using Revenj.DatabasePersistence.Oracle.QueryGeneration.QueryComposition; namespace Revenj.DatabasePersistence.Oracle.QueryGeneration.Visitors { public class SelectGeneratorExpressionTreeVisitor : ThrowingExpressionTreeVisitor { public static void ProcessExpression(Expression linqExpression, MainQueryParts query, QueryModel queryModel) { var visitor = new SelectGeneratorExpressionTreeVisitor( query, queryModel.ResultOperators.Any(it => it is AllResultOperator)); visitor.VisitExpression(linqExpression); } private readonly MainQueryParts Query; private readonly bool IsSimple; private readonly List<Expression> DataSources = new List<Expression>(); private SelectGeneratorExpressionTreeVisitor(MainQueryParts query, bool simple) { this.Query = query; this.IsSimple = simple; } protected override Expression VisitQuerySourceReferenceExpression(QuerySourceReferenceExpression expression) { if (IsSimple) { var qs = expression.ReferencedQuerySource; Query.AddSelectPart(qs, qs.ItemName, qs.ItemName, typeof(bool), (_, dr) => dr.GetBoolean(0)); } else { CreateSelector(expression.ReferencedQuerySource); } return expression; } class PropertySource : IQuerySource { public IQuerySource Parent; public PropertyInfo Property; public PropertySource(IQuerySource parent, PropertyInfo pi) { this.Parent = parent; this.Property = pi; this.ItemName = parent.ItemName + "." + pi.Name; this.ItemType = pi.PropertyType; } public string ItemName { get; set; } public Type ItemType { get; set; } } private void CreateSelector(IQuerySource qs) { var index = Query.CurrentSelectIndex; if (qs.ItemType.IsGrouping()) { var factoryKey = QuerySourceConverterFactory.CreateResult( "Key", qs.ItemType.GetGenericArguments()[0], qs, Query, false); var factoryValue = QuerySourceConverterFactory.Create(qs, Query); var genericType = qs.ItemType.CreateGrouping(); if (Query.AddSelectPart( qs, "\"{0}\".\"Key\" AS \"{0}.Key\", \"{0}\".\"Values\" AS \"{0}\"".With(factoryValue.Name), factoryValue.Name, qs.ItemType, (_, dr) => { var keyInstance = factoryKey.Instancer(dr.GetValue(index)); //TODO fix later return null; /*var array = dr.IsDBNull(index + 1) ? new string[0] : OracleRecordConverter.ParseArray(dr.GetString(index + 1)); var valueInstances = array.Select(it => factoryValue.Instancer(it)); return Activator.CreateInstance(genericType, keyInstance, valueInstances);*/ })) Query.CurrentSelectIndex++; } else if (typeof(IOracleReader).IsAssignableFrom(qs.ItemType)) { var props = qs.ItemType.GetProperties(); var selectors = new PropertySource[props.Length]; for (int i = 0; i < selectors.Length; i++) { var s = selectors[i] = new PropertySource(qs, props[i]); Query.AddSelectPart( s, "\"{0}\".\"{1}\" AS \"{0}.{1}\"".With(s.Parent.ItemName, s.Property.Name), s.ItemName, s.ItemType, null); } Query.AddSelectPart( qs, null, qs.ItemName, qs.ItemType, (_, dr) => { var inst = (IOracleReader)Activator.CreateInstance(qs.ItemType); inst.Read(qs.ItemName, dr, Query.Locator); return inst; }); } else { var factory = QuerySourceConverterFactory.Create(qs, Query); var ii = factory.CanBeNull && factory.AsValue; Query.AddSelectPart( factory.QuerySource, ii ? "CASE WHEN \"{0}\".URI IS NULL THEN NULL ELSE VALUE(\"{0}\") END".With(factory.Name) : factory.AsValue ? "VALUE(\"{0}\")".With(factory.Name) : "\"{0}\"".With(factory.Name), factory.Name, factory.Type, (_, dr) => dr.IsDBNull(index) ? null : factory.Instancer(dr.GetValue(index))); } } protected override Expression VisitNewExpression(NewExpression expression) { if (expression.CanReduce) return expression.Reduce(); foreach (var arg in expression.Arguments) VisitExpression(arg); return Expression.New(expression.Constructor, expression.Arguments); } protected override Expression VisitMemberInitExpression(MemberInitExpression expression) { var newExpression = expression.NewExpression; var newBindings = VisitMemberBindingList(expression.Bindings); if (newExpression != expression.NewExpression || newBindings != expression.Bindings) return Expression.MemberInit(newExpression, newBindings); return Expression.New(newExpression.Constructor, newExpression.Arguments); } protected override ReadOnlyCollection<MemberBinding> VisitMemberBindingList(ReadOnlyCollection<MemberBinding> expressions) { return base.VisitMemberBindingList(expressions); } protected override MemberBinding VisitMemberAssignment(MemberAssignment memberAssigment) { if (memberAssigment.Expression.NodeType == ExpressionType.Constant) return Expression.Bind(memberAssigment.Member, memberAssigment.Expression); var expression = VisitExpression(memberAssigment.Expression); return Expression.Bind(memberAssigment.Member, expression); } protected override Expression VisitBinaryExpression(BinaryExpression expression) { VisitExpression(expression.Left); VisitExpression(expression.Right); return expression; } protected override Expression VisitConstantExpression(ConstantExpression expression) { return expression; } protected override Expression VisitUnaryExpression(UnaryExpression expression) { VisitExpression(expression.Operand); return expression; } protected override Expression VisitMemberExpression(MemberExpression expression) { VisitExpression(expression.Expression); return expression; } protected override Expression VisitMethodCallExpression(MethodCallExpression expression) { VisitExpression(expression.Object); foreach (var arg in expression.Arguments) VisitExpression(arg); return expression; } protected override Expression VisitConditionalExpression(ConditionalExpression expression) { VisitExpression(expression.Test); VisitExpression(expression.IfTrue); VisitExpression(expression.IfFalse); return expression; } private readonly List<Expression> ProcessedExpressions = new List<Expression>(); protected override Expression VisitSubQueryExpression(SubQueryExpression expression) { if (ProcessedExpressions.Contains(expression)) return expression; if (DataSources.Count == 0) { DataSources.Add(Query.MainFrom.FromExpression); DataSources.AddRange(Query.Joins.Select(it => it.InnerSequence)); DataSources.AddRange(Query.AdditionalJoins.Select(it => it.FromExpression)); } var model = expression.QueryModel; if (model.BodyClauses.Count == 0 && DataSources.Contains(model.MainFromClause.FromExpression)) return expression; ProcessedExpressions.Add(expression); foreach (var candidate in Query.ProjectionMatchers) if (candidate.TryMatch(expression, Query, exp => VisitExpression(exp))) return expression; var subquery = SubqueryGeneratorQueryModelVisitor.ParseSubquery(expression.QueryModel, Query, true, Query.ContextName, Query.Context.Select()); var cnt = Query.CurrentSelectIndex; //TODO true or false var sql = subquery.BuildSqlString(true); var selector = model.SelectClause.Selector; var projector = (IExecuteFunc)Activator.CreateInstance(typeof(GenericProjection<>).MakeGenericType(selector.Type), model); var ssd = SelectSubqueryData.Create(Query, subquery); if (subquery.ResultOperators.Any(it => it is FirstResultOperator)) { //TODO fix later Query.AddSelectPart( expression.QueryModel.MainFromClause, @"(SELECT ""{1}"" FROM ({2}) ""{1}"" WHERE RowNum = 1) AS ""{0}""".With( "_first_or_default_" + cnt, expression.QueryModel.MainFromClause.ItemName, sql), "_first_or_default_" + cnt, expression.QueryModel.ResultTypeOverride, (rom, dr) => { if (dr.IsDBNull(cnt)) return null; var tuple = new[] { dr.GetValue(cnt).ToString() }; var result = ssd.ProcessRow(rom, tuple); return projector.Eval(result); }); } else { //TODO fix later Query.AddSelectPart( expression.QueryModel.MainFromClause, @"(SELECT ARRAY_AGG(""{1}"") FROM ({2}) ""{1}"") AS ""{0}""".With( "_subquery_" + cnt, expression.QueryModel.MainFromClause.ItemName, sql), "_subquery_" + cnt, expression.QueryModel.ResultTypeOverride, (rom, dr) => { //TODO fix later return null; /* string[] array; if (dr.IsDBNull(cnt)) array = new string[0]; else { var value = dr.GetValue(cnt); array = value is string[] ? value as string[] : OracleRecordConverter.ParseArray(dr.GetString(cnt)); } var resultItems = new List<ResultObjectMapping>(); array.Foreach(it => resultItems.Add(ssd.ProcessRow(rom, it))); return projector.Process(resultItems);*/ }); } return expression; } class GenericProjection<TOut> : IExecuteFunc { private readonly Func<ResultObjectMapping, TOut> Func; public GenericProjection(QueryModel model) { Func = ProjectorBuildingExpressionTreeVisitor<TOut>.BuildProjector(model); } public IQueryable Process(IEnumerable<ResultObjectMapping> items) { return items.Select(it => Func(it)).ToList().AsQueryable(); } public object Eval(ResultObjectMapping item) { return Func(item); } } interface IExecuteFunc { IQueryable Process(IEnumerable<ResultObjectMapping> items); object Eval(ResultObjectMapping item); } // Called when a LINQ expression type is not handled above. protected override Exception CreateUnhandledItemException<T>(T unhandledItem, string visitMethod) { string itemText = FormatUnhandledItem(unhandledItem); var message = "The expression '{0}' (type: {1}) is not supported by this LINQ provider.".With(itemText, typeof(T)); return new NotSupportedException(message); } private string FormatUnhandledItem<T>(T unhandledItem) { var itemAsExpression = unhandledItem as Expression; return itemAsExpression != null ? FormattingExpressionTreeVisitor.Format(itemAsExpression) : unhandledItem.ToString(); } } }
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 medical clinic. /// </summary> public class MedicalClinic_Core : TypeCore, IMedicalOrganization { public MedicalClinic_Core() { this._TypeId = 162; this._Id = "MedicalClinic"; this._Schema_Org_Url = "http://schema.org/MedicalClinic"; string label = ""; GetLabel(out label, "MedicalClinic", typeof(MedicalClinic_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,163}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{163}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <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> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <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> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <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> /// 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> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <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 opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Build.Construction; using Microsoft.DotNet.Tools.Test.Utilities; using Msbuild.Tests.Utilities; using System; using System.IO; using System.Linq; using Xunit; namespace Microsoft.DotNet.Cli.Add.Reference.Tests { public class GivenDotnetAddReference : TestBase { private const string HelpText = @".NET Add Project to Project reference Command Usage: dotnet add <PROJECT> reference [options] <args> Arguments: <PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one. <args> Project to project references to add Options: -h, --help Show help information -f, --framework <FRAMEWORK> Add reference only when targeting a specific framework "; const string FrameworkNet451Arg = "-f net451"; const string ConditionFrameworkNet451 = "== 'net451'"; const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0"; const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'"; const string ProjectNotCompatibleErrorMessageRegEx = "Project `[^`]*` cannot be added due to incompatible targeted frameworks between the two projects\\. Please review the project you are trying to add and verify that is compatible with the following targets\\:"; const string ProjectDoesNotTargetFrameworkErrorMessageRegEx = "Project `[^`]*` does not target framework `[^`]*`."; static readonly string[] DefaultFrameworks = new string[] { "netcoreapp1.0", "net451" }; private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "") { return new TestSetup( TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName) .CreateInstance(callingMethod: callingMethod, identifier: identifier) .WithSourceFiles() .Root .FullName); } private ProjDir NewDir([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { return new ProjDir(TestAssets.CreateTestDirectory(callingMethod: callingMethod, identifier: identifier).FullName); } private ProjDir NewLib(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { var projDir = dir == null ? NewDir(callingMethod: callingMethod, identifier: identifier) : new ProjDir(dir); try { string args = $"classlib -o \"{projDir.Path}\" --debug:ephemeral-hive --no-restore"; new NewCommandShim() .WithWorkingDirectory(projDir.Path) .ExecuteWithCapturedOutput(args) .Should().Pass(); } catch (System.ComponentModel.Win32Exception e) { throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{projDir.Path}`\nException:\n{e}"); } return projDir; } private static void SetTargetFrameworks(ProjDir proj, string[] frameworks) { var csproj = proj.CsProj(); csproj.AddProperty("TargetFrameworks", string.Join(";", frameworks)); csproj.Save(); } private ProjDir NewLibWithFrameworks(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "") { var ret = NewLib(dir, callingMethod: callingMethod, identifier: identifier); SetTargetFrameworks(ret, DefaultFrameworks); return ret; } [Theory] [InlineData("--help")] [InlineData("-h")] public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg) { var cmd = new AddReferenceCommand().Execute(helpArg); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Theory] [InlineData("")] [InlineData("unknownCommandName")] public void WhenNoCommandIsPassedItPrintsError(string commandName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"add {commandName}"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Required command was not provided."); } [Fact] public void WhenTooManyArgumentsArePassedItPrintsError() { var cmd = new AddReferenceCommand() .WithProject("one two three") .Execute("proj.csproj"); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().BeVisuallyEquivalentTo( "Unrecognized command or argument 'two'\r\nUnrecognized command or argument 'three'"); } [Theory] [InlineData("idontexist.csproj")] [InlineData("ihave?inv@lid/char\\acters")] public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName) { var setup = Setup(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(projName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Could not find project or directory `{projName}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage() { string projName = "Broken/Broken.csproj"; var setup = Setup(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(projName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be("Project `Broken/Broken.csproj` is invalid."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage() { var setup = Setup(); var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne"); var cmd = new AddReferenceCommand() .WithWorkingDirectory(workingDir) .Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Found more than one project in `{workingDir + Path.DirectorySeparatorChar}`. Please specify which one to use."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage() { var setup = Setup(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.ExitCode.Should().NotBe(0); cmd.StdErr.Should().Be($"Could not find any project in `{setup.TestRoot + Path.DirectorySeparatorChar}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void ItAddsRefWithoutCondAndPrintsStatus() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project."); cmd.StdErr.Should().BeEmpty(); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1); } [Fact] public void ItAddsRefWithCondAndPrintsStatus() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project."); cmd.StdErr.Should().BeEmpty(); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1); } [Fact] public void WhenRefWithoutCondIsPresentItAddsDifferentRefWithoutCond() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{setup.LibCsprojPath}\"") .Should().Pass(); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(lib.Path) .WithProject(lib.CsProjName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1); } [Fact] public void WhenRefWithCondIsPresentItAddsDifferentRefWithCond() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\"") .Should().Pass(); int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1); } [Fact] public void WhenRefWithCondIsPresentItAddsRefWithDifferentCond() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNetCoreApp10Arg} \"{setup.ValidRefCsprojPath}\"") .Should().Pass(); int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1); } [Fact] public void WhenRefWithConditionIsPresentItAddsDifferentRefWithoutCond() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\"") .Should().Pass(); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1); } [Fact] public void WhenRefWithNoCondAlreadyExistsItDoesntDuplicate() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{setup.ValidRefCsprojPath}\"") .Should().Pass(); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(lib.Path) .WithProject(lib.CsProjName) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Project already has a reference to `ValidRef\\ValidRef.csproj`."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1); } [Fact] public void WhenRefWithCondOnItemAlreadyExistsItDoesntDuplicate() { var setup = Setup(); var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithExistingRefCondOnItem")); string contentBefore = proj.CsProjContent(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(proj.Path) .WithProject(proj.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Project already has a reference to `..\\Lib\\Lib.csproj`."); proj.CsProjContent().Should().BeEquivalentTo(contentBefore); } [Fact] public void WhenRefWithCondOnItemGroupAlreadyExistsItDoesntDuplicate() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"") .Should().Pass(); var csprojContentBefore = lib.CsProjContent(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Project already has a reference to `ValidRef\\ValidRef.csproj`."); lib.CsProjContent().Should().BeEquivalentTo(csprojContentBefore); } [Fact] public void WhenRefWithCondWithWhitespaceOnItemGroupExistsItDoesntDuplicate() { var setup = Setup(); var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithExistingRefCondWhitespaces")); string contentBefore = proj.CsProjContent(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(proj.Path) .WithProject(proj.CsProjName) .Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Project already has a reference to `..\\Lib\\Lib.csproj`."); proj.CsProjContent().Should().BeEquivalentTo(contentBefore); } [Fact] public void WhenRefWithoutCondAlreadyExistsInNonUniformItemGroupItDoesntDuplicate() { var setup = Setup(); var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefNoCondNonUniform")); string contentBefore = proj.CsProjContent(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(proj.Path) .WithProject(proj.CsProjName) .Execute($"\"{setup.LibCsprojRelPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Project already has a reference to `..\\Lib\\Lib.csproj`."); proj.CsProjContent().Should().BeEquivalentTo(contentBefore); } [Fact] public void WhenRefWithoutCondAlreadyExistsInNonUniformItemGroupItAddsDifferentRefInDifferentGroup() { var setup = Setup(); var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefNoCondNonUniform")); int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(proj.CsProjPath) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `..\\ValidRef\\ValidRef.csproj` added to the project."); var csproj = proj.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1); } [Fact] public void WhenRefWithCondAlreadyExistsInNonUniformItemGroupItDoesntDuplicate() { var setup = Setup(); var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefCondNonUniform")); string contentBefore = proj.CsProjContent(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(proj.Path) .WithProject(proj.CsProjName) .Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Project already has a reference to `..\\Lib\\Lib.csproj`."); proj.CsProjContent().Should().BeEquivalentTo(contentBefore); } [Fact] public void WhenRefWithCondAlreadyExistsInNonUniformItemGroupItAddsDifferentRefInDifferentGroup() { var setup = Setup(); var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefCondNonUniform")); int condBefore = proj.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(proj.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `..\\ValidRef\\ValidRef.csproj` added to the project."); var csproj = proj.CsProj(); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1); } [Fact] public void WhenEmptyItemGroupPresentItAddsRefInIt() { var setup = Setup(); var proj = new ProjDir(Path.Combine(setup.TestRoot, "EmptyItemGroup")); int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(proj.CsProjPath) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `..\\ValidRef\\ValidRef.csproj` added to the project."); var csproj = proj.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1); } [Fact] public void ItAddsMultipleRefsNoCondToTheSameItemGroup() { const string OutputText = @"Reference `Lib\Lib.csproj` added to the project. Reference `ValidRef\ValidRef.csproj` added to the project."; var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{setup.LibCsprojPath}\" \"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.LibCsprojName).Should().Be(1); } [Fact] public void ItAddsMultipleRefsWithCondToTheSameItemGroup() { const string OutputText = @"Reference `Lib\Lib.csproj` added to the project. Reference `ValidRef\ValidRef.csproj` added to the project."; var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\" \"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.LibCsprojName, ConditionFrameworkNet451).Should().Be(1); } [Fact] public void WhenProjectNameIsNotPassedItFindsItAndAddsReference() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(lib.Path) .Execute($"\"{setup.ValidRefCsprojPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project."); cmd.StdErr.Should().BeEmpty(); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1); } [Fact] public void WhenPassedReferenceDoesNotExistItShowsAnError() { var lib = NewLibWithFrameworks(); var contentBefore = lib.CsProjContent(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(lib.Path) .WithProject(lib.CsProjName) .Execute("\"IDoNotExist.csproj\""); cmd.Should().Fail(); cmd.StdErr.Should().Be("Reference IDoNotExist.csproj does not exist."); lib.CsProjContent().Should().BeEquivalentTo(contentBefore); } [Fact] public void WhenPassedMultipleRefsAndOneOfthemDoesNotExistItCancelsWholeOperation() { var lib = NewLibWithFrameworks(); var setup = Setup(); var contentBefore = lib.CsProjContent(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(lib.CsProjPath) .Execute($"\"{setup.ValidRefCsprojPath}\" \"IDoNotExist.csproj\""); cmd.Should().Fail(); cmd.StdErr.Should().Be("Reference IDoNotExist.csproj does not exist."); lib.CsProjContent().Should().BeEquivalentTo(contentBefore); } [Fact] public void WhenPassedReferenceIsUsingSlashesItNormalizesItToBackslashes() { var setup = Setup(); var lib = NewLibWithFrameworks(dir: setup.TestRoot); int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(lib.Path) .WithProject(lib.CsProjName) .Execute($"\"{setup.ValidRefCsprojPath.Replace('\\', '/')}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project."); cmd.StdErr.Should().BeEmpty(); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojRelPath.Replace('/', '\\')).Should().Be(1); } [Fact] public void WhenReferenceIsRelativeAndProjectIsNotInCurrentDirectoryReferencePathIsFixed() { var setup = Setup(); var proj = new ProjDir(setup.LibDir); int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithWorkingDirectory(setup.TestRoot) .WithProject(setup.LibCsprojPath) .Execute($"\"{setup.ValidRefCsprojRelPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `..\\ValidRef\\ValidRef.csproj` added to the project."); cmd.StdErr.Should().BeEmpty(); var csproj = proj.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojRelToOtherProjPath.Replace('/', '\\')).Should().Be(1); } [Fact] public void ItCanAddReferenceWithConditionOnCompatibleFramework() { var setup = Setup(); var lib = new ProjDir(setup.LibDir); var net45lib = new ProjDir(Path.Combine(setup.TestRoot, "Net45Lib")); int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451); var cmd = new AddReferenceCommand() .WithProject(lib.CsProjPath) .Execute($"{FrameworkNet451Arg} \"{net45lib.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `..\\Net45Lib\\Net45Lib.csproj` added to the project."); var csproj = lib.CsProj(); csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1); csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(net45lib.CsProjName, ConditionFrameworkNet451).Should().Be(1); } [Fact] public void ItCanAddRefWithoutCondAndTargetingSupersetOfFrameworksAndOneOfReferencesCompatible() { var setup = Setup(); var lib = new ProjDir(setup.LibDir); var net452netcoreapp10lib = new ProjDir(Path.Combine(setup.TestRoot, "Net452AndNetCoreApp10Lib")); int noCondBefore = net452netcoreapp10lib.CsProj().NumberOfItemGroupsWithoutCondition(); var cmd = new AddReferenceCommand() .WithProject(net452netcoreapp10lib.CsProjPath) .Execute($"\"{lib.CsProjPath}\""); cmd.Should().Pass(); cmd.StdOut.Should().Be("Reference `..\\Lib\\Lib.csproj` added to the project."); var csproj = net452netcoreapp10lib.CsProj(); csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1); csproj.NumberOfProjectReferencesWithIncludeContaining(lib.CsProjName).Should().Be(1); } [Theory] [InlineData("net45")] [InlineData("net40")] [InlineData("netcoreapp1.1")] [InlineData("nonexistingframeworkname")] public void WhenFrameworkSwitchIsNotMatchingAnyOfTargetedFrameworksItPrintsError(string framework) { var setup = Setup(); var lib = new ProjDir(setup.LibDir); var net45lib = new ProjDir(Path.Combine(setup.TestRoot, "Net45Lib")); var csProjContent = lib.CsProjContent(); var cmd = new AddReferenceCommand() .WithProject(lib.CsProjPath) .Execute($"-f {framework} \"{net45lib.CsProjPath}\""); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Project `{setup.LibCsprojPath}` does not target framework `{framework}`."); lib.CsProjContent().Should().BeEquivalentTo(csProjContent); } [Theory] [InlineData("")] [InlineData("-f net45")] public void WhenIncompatibleFrameworkDetectedItPrintsError(string frameworkArg) { var setup = Setup(); var lib = new ProjDir(setup.LibDir); var net45lib = new ProjDir(Path.Combine(setup.TestRoot, "Net45Lib")); var csProjContent = net45lib.CsProjContent(); var cmd = new AddReferenceCommand() .WithProject(net45lib.CsProjPath) .Execute($"{frameworkArg} \"{lib.CsProjPath}\""); cmd.Should().Fail(); cmd.StdErr.Should().MatchRegex(ProjectNotCompatibleErrorMessageRegEx); cmd.StdErr.Should().MatchRegex(" - net45"); net45lib.CsProjContent().Should().BeEquivalentTo(csProjContent); } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using Orleans.Providers; namespace Orleans.Runtime.Configuration { /// <summary> /// Orleans client configuration parameters. /// </summary> public class ClientConfiguration : MessagingConfiguration, ITraceConfiguration, IStatisticsConfiguration { /// <summary> /// Specifies the type of the gateway provider. /// </summary> public enum GatewayProviderType { /// <summary>No provider specified</summary> None, /// <summary>use Azure, requires SystemStore element</summary> AzureTable, /// <summary>use SQL, requires SystemStore element</summary> SqlServer, /// <summary>use ZooKeeper, requires SystemStore element</summary> ZooKeeper, /// <summary>use Config based static list, requires Config element(s)</summary> Config, /// <summary>use provider from third-party assembly</summary> Custom } /// <summary> /// The name of this client. /// </summary> public static string ClientName = "Client"; private string traceFilePattern; private readonly DateTime creationTimestamp; /// <summary>Gets the configuration source file path</summary> public string SourceFile { get; private set; } /// <summary> /// The list fo the gateways to use. /// Each GatewayNode element specifies an outside grain client gateway node. /// If outside (non-Orleans) clients are to connect to the Orleans system, then at least one gateway node must be specified. /// Additional gateway nodes may be specified if desired, and will add some failure resilience and scalability. /// If multiple gateways are specified, then each client will select one from the list at random. /// </summary> public IList<IPEndPoint> Gateways { get; set; } /// <summary> /// </summary> public int PreferedGatewayIndex { get; set; } /// <summary> /// </summary> public GatewayProviderType GatewayProvider { get; set; } /// <summary> /// Specifies a unique identifier of this deployment. /// If the silos are deployed on Azure (run as workers roles), deployment id is set automatically by Azure runtime, /// accessible to the role via RoleEnvironment.DeploymentId static variable and is passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set by a deployment script in the OrleansConfiguration.xml file. /// </summary> public string DeploymentId { get; set; } /// <summary> /// Specifies the connection string for the gateway provider. /// If the silos are deployed on Azure (run as workers roles), DataConnectionString may be specified via RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"); /// In such a case it is taken from there and passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles and this config is specified via RoleEnvironment, /// this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set in the OrleansConfiguration.xml file. /// If not set at all, DevelopmentStorageAccount will be used. /// </summary> public string DataConnectionString { get; set; } /// <summary> /// When using ADO, identifies the underlying data provider for the gateway provider. This three-part naming syntax is also used when creating a new factory /// and for identifying the provider in an application configuration file so that the provider name, along with its associated /// connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx /// </summary> public string AdoInvariant { get; set; } public string CustomGatewayProviderAssemblyName { get; set; } /// <inheritdoc /> public Severity DefaultTraceLevel { get; set; } /// <inheritdoc /> public IList<Tuple<string, Severity>> TraceLevelOverrides { get; private set; } /// <inheritdoc /> public bool TraceToConsole { get; set; } /// <inheritdoc /> public int LargeMessageWarningThreshold { get; set; } /// <inheritdoc /> public bool PropagateActivityId { get; set; } /// <inheritdoc /> public int BulkMessageLimit { get; set; } /// <summary> /// </summary> public AddressFamily PreferredFamily { get; set; } /// <summary> /// The Interface attribute specifies the name of the network interface to use to work out an IP address for this machine. /// </summary> public string NetInterface { get; private set; } /// <summary> /// The Port attribute specifies the specific listen port for this client machine. /// If value is zero, then a random machine-assigned port number will be used. /// </summary> public int Port { get; private set; } /// <summary>Gets the true host name, no IP address. It equals Dns.GetHostName()</summary> public string DNSHostName { get; private set; } /// <summary> /// </summary> public TimeSpan GatewayListRefreshPeriod { get; set; } public string StatisticsProviderName { get; set; } public TimeSpan StatisticsMetricsTableWriteInterval { get; set; } public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } public TimeSpan StatisticsLogWriteInterval { get; set; } public bool StatisticsWriteLogStatisticsToTable { get; set; } public StatisticsLevel StatisticsCollectionLevel { get; set; } public LimitManager LimitManager { get; private set; } private static readonly TimeSpan DEFAULT_GATEWAY_LIST_REFRESH_PERIOD = TimeSpan.FromMinutes(1); private static readonly TimeSpan DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = Constants.INFINITE_TIMESPAN; private static readonly TimeSpan DEFAULT_STATS_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5); /// <summary> /// </summary> public bool UseAzureSystemStore { get { return GatewayProvider == GatewayProviderType.AzureTable && !String.IsNullOrWhiteSpace(DeploymentId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } /// <summary> /// </summary> public bool UseSqlSystemStore { get { return GatewayProvider == GatewayProviderType.SqlServer && !String.IsNullOrWhiteSpace(DeploymentId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } private bool HasStaticGateways { get { return Gateways != null && Gateways.Count > 0; } } /// <summary> /// </summary> public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; } /// <inheritdoc /> public string TraceFilePattern { get { return traceFilePattern; } set { traceFilePattern = value; ConfigUtilities.SetTraceFileName(this, ClientName, this.creationTimestamp); } } /// <inheritdoc /> public string TraceFileName { get; set; } /// <summary>Initializes a new instance of <see cref="ClientConfiguration"/>.</summary> public ClientConfiguration() : base(false) { creationTimestamp = DateTime.UtcNow; SourceFile = null; PreferedGatewayIndex = -1; Gateways = new List<IPEndPoint>(); GatewayProvider = GatewayProviderType.None; PreferredFamily = AddressFamily.InterNetwork; NetInterface = null; Port = 0; DNSHostName = Dns.GetHostName(); DeploymentId = ""; DataConnectionString = ""; // Assume the ado invariant is for sql server storage if not explicitly specified AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER; DefaultTraceLevel = Severity.Info; TraceLevelOverrides = new List<Tuple<string, Severity>>(); TraceToConsole = true; TraceFilePattern = "{0}-{1}.log"; LargeMessageWarningThreshold = Constants.LARGE_OBJECT_HEAP_THRESHOLD; PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; BulkMessageLimit = Constants.DEFAULT_LOGGER_BULK_MESSAGE_LIMIT; GatewayListRefreshPeriod = DEFAULT_GATEWAY_LIST_REFRESH_PERIOD; StatisticsProviderName = null; StatisticsMetricsTableWriteInterval = DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD; StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD; StatisticsLogWriteInterval = DEFAULT_STATS_LOG_WRITE_PERIOD; StatisticsWriteLogStatisticsToTable = true; StatisticsCollectionLevel = NodeConfiguration.DEFAULT_STATS_COLLECTION_LEVEL; LimitManager = new LimitManager(); ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>(); } public void Load(TextReader input) { var xml = new XmlDocument(); var xmlReader = XmlReader.Create(input); xml.Load(xmlReader); XmlElement root = xml.DocumentElement; LoadFromXml(root); } internal void LoadFromXml(XmlElement root) { foreach (XmlNode node in root.ChildNodes) { var child = node as XmlElement; if (child != null) { switch (child.LocalName) { case "Gateway": Gateways.Add(ConfigUtilities.ParseIPEndPoint(child).GetResult()); if (GatewayProvider == GatewayProviderType.None) { GatewayProvider = GatewayProviderType.Config; } break; case "Azure": // Throw exception with explicit deprecation error message throw new OrleansException( "The Azure element has been deprecated -- use SystemStore element instead."); case "SystemStore": if (child.HasAttribute("SystemStoreType")) { var sst = child.GetAttribute("SystemStoreType"); GatewayProvider = (GatewayProviderType)Enum.Parse(typeof(GatewayProviderType), sst); } if (child.HasAttribute("CustomGatewayProviderAssemblyName")) { CustomGatewayProviderAssemblyName = child.GetAttribute("CustomGatewayProviderAssemblyName"); if (CustomGatewayProviderAssemblyName.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"CustomGatewayProviderAssemblyName\""); if (GatewayProvider != GatewayProviderType.Custom) throw new FormatException("SystemStoreType should be \"Custom\" when CustomGatewayProviderAssemblyName is specified"); } if (child.HasAttribute("DeploymentId")) { DeploymentId = child.GetAttribute("DeploymentId"); } if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME)) { DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionString)) { throw new FormatException("SystemStore.DataConnectionString cannot be blank"); } if (GatewayProvider == GatewayProviderType.None) { // Assume the connection string is for Azure storage if not explicitly specified GatewayProvider = GatewayProviderType.AzureTable; } } if (child.HasAttribute(Constants.ADO_INVARIANT_NAME)) { AdoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME); if (String.IsNullOrWhiteSpace(AdoInvariant)) { throw new FormatException("SystemStore.AdoInvariant cannot be blank"); } } break; case "Tracing": ConfigUtilities.ParseTracing(this, child, ClientName); break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, ClientName); break; case "Limits": ConfigUtilities.ParseLimitValues(LimitManager, child, ClientName); break; case "Debug": break; case "Messaging": base.Load(child); break; case "LocalAddress": if (child.HasAttribute("PreferredFamily")) { PreferredFamily = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid address family for the PreferredFamily attribute on the LocalAddress element"); } else { throw new FormatException("Missing PreferredFamily attribute on the LocalAddress element"); } if (child.HasAttribute("Interface")) { NetInterface = child.GetAttribute("Interface"); } if (child.HasAttribute("Port")) { Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Invalid integer value for the Port attribute on the LocalAddress element"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child); break; default: if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal)) { var providerCategory = ProviderCategoryConfiguration.Load(child); if (ProviderConfigurations.ContainsKey(providerCategory.Name)) { var existingCategory = ProviderConfigurations[providerCategory.Name]; existingCategory.Merge(providerCategory); } else { ProviderConfigurations.Add(providerCategory.Name, providerCategory); } } break; } } } } /// <summary> /// </summary> public static ClientConfiguration LoadFromFile(string fileName) { if (fileName == null) { return null; } using (TextReader input = File.OpenText(fileName)) { var config = new ClientConfiguration(); config.Load(input); config.SourceFile = fileName; return config; } } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="Orleans.Streams.IStreamProvider"/> stream</typeparam> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to stream provider upon initialization</param> public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider { TypeInfo providerTypeInfo = typeof(T).GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(typeof(T))) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given stream provider. /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to the stream provider upon initialization </param> public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Retrieves an existing provider configuration /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="config">The provider configuration, if exists</param> /// <returns>True if a configuration for this provider already exists, false otherwise.</returns> public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config) { return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config); } /// <summary> /// Retrieves an enumeration of all currently configured provider configurations. /// </summary> /// <returns>An enumeration of all currently configured provider configurations.</returns> public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations() { return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations); } /// <summary> /// Loads the configuration from the standard paths, looking up the directory hierarchy /// </summary> /// <returns>Client configuration data if a configuration file was found.</returns> /// <exception cref="FileNotFoundException">Thrown if no configuration file could be found in any of the standard locations</exception> public static ClientConfiguration StandardLoad() { var fileName = ConfigUtilities.FindConfigFile(false); // Throws FileNotFoundException return LoadFromFile(fileName); } /// <summary>Returns a detailed human readable string that represents the current configuration. It does not contain every single configuration knob.</summary> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo()); sb.Append(" Host: ").AppendLine(Dns.GetHostName()); sb.Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.AppendLine("Client Configuration:"); sb.Append(" Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile)); sb.Append(" Start time: ").AppendLine(LogFormatter.PrintDate(DateTime.UtcNow)); sb.Append(" Gateway Provider: ").Append(GatewayProvider); if (GatewayProvider == GatewayProviderType.None) { sb.Append(". Gateway Provider that will be used instead: ").Append(GatewayProviderToUse); } sb.AppendLine(); if (Gateways != null && Gateways.Count > 0 ) { sb.AppendFormat(" Gateways[{0}]:", Gateways.Count).AppendLine(); foreach (var endpoint in Gateways) { sb.Append(" ").AppendLine(endpoint.ToString()); } } else { sb.Append(" Gateways: ").AppendLine("Unspecified"); } sb.Append(" Preferred Gateway Index: ").AppendLine(PreferedGatewayIndex.ToString()); if (Gateways != null && PreferedGatewayIndex >= 0 && PreferedGatewayIndex < Gateways.Count) { sb.Append(" Preferred Gateway Address: ").AppendLine(Gateways[PreferedGatewayIndex].ToString()); } sb.Append(" GatewayListRefreshPeriod: ").Append(GatewayListRefreshPeriod).AppendLine(); if (!String.IsNullOrEmpty(DeploymentId) || !String.IsNullOrEmpty(DataConnectionString)) { sb.Append(" Azure:").AppendLine(); sb.Append(" DeploymentId: ").Append(DeploymentId).AppendLine(); string dataConnectionInfo = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); // Don't print Azure account keys in log files sb.Append(" DataConnectionString: ").Append(dataConnectionInfo).AppendLine(); } if (!string.IsNullOrWhiteSpace(NetInterface)) { sb.Append(" Network Interface: ").AppendLine(NetInterface); } if (Port != 0) { sb.Append(" Network Port: ").Append(Port).AppendLine(); } sb.Append(" Preferred Address Family: ").AppendLine(PreferredFamily.ToString()); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Client Name: ").AppendLine(ClientName); sb.Append(ConfigUtilities.TraceConfigurationToString(this)); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); sb.AppendFormat(base.ToString()); #if !NETSTANDARD sb.Append(" .NET: ").AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); #endif sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return sb.ToString(); } internal GatewayProviderType GatewayProviderToUse { get { // order is important here for establishing defaults. if (GatewayProvider != GatewayProviderType.None) return GatewayProvider; if (UseAzureSystemStore) return GatewayProviderType.AzureTable; return HasStaticGateways ? GatewayProviderType.Config : GatewayProviderType.None; } } internal void CheckGatewayProviderSettings() { switch (GatewayProvider) { case GatewayProviderType.AzureTable: if (!UseAzureSystemStore) throw new ArgumentException("Config specifies Azure based GatewayProviderType, but Azure element is not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.Config: if (!HasStaticGateways) throw new ArgumentException("Config specifies Config based GatewayProviderType, but Gateway element(s) is/are not specified.", "GatewayProvider"); break; case GatewayProviderType.Custom: if (String.IsNullOrEmpty(CustomGatewayProviderAssemblyName)) throw new ArgumentException("Config specifies Custom GatewayProviderType, but CustomGatewayProviderAssemblyName attribute is not specified", "GatewayProvider"); break; case GatewayProviderType.None: if (!UseAzureSystemStore && !HasStaticGateways) throw new ArgumentException("Config does not specify GatewayProviderType, and also does not have the adequate defaults: no Azure and or Gateway element(s) are specified.","GatewayProvider"); break; case GatewayProviderType.SqlServer: if (!UseSqlSystemStore) throw new ArgumentException("Config specifies SqlServer based GatewayProviderType, but DeploymentId or DataConnectionString are not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.ZooKeeper: break; } } /// <summary> /// Retuurns a ClientConfiguration object for connecting to a local silo (for testing). /// </summary> /// <param name="gatewayPort">Client gateway TCP port</param> /// <returns>ClientConfiguration object that can be passed to GrainClient class for initialization</returns> public static ClientConfiguration LocalhostSilo(int gatewayPort = 40000) { var config = new ClientConfiguration {GatewayProvider = GatewayProviderType.Config}; config.Gateways.Add(new IPEndPoint(IPAddress.Loopback, gatewayPort)); return config; } } }
using System; using System.Collections; using System.Diagnostics; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; using System.Windows.Input; using System.Windows.Automation; using System.Windows.Automation.Peers; using MS.Internal.PresentationCore; namespace MS.Internal { internal static class SynchronizedInputHelper { internal static DependencyObject GetUIParentCore(DependencyObject o) { UIElement e = o as UIElement; if (e != null) { return e.GetUIParentCore(); } else { ContentElement ce = o as ContentElement; if (ce != null) { return ce.GetUIParentCore(); } else { UIElement3D e3D = o as UIElement3D; if (e3D != null) { return e3D.GetUIParentCore(); } } return null; } } internal static bool IsMappedEvent(RoutedEventArgs args) { RoutedEvent re = args.RoutedEvent; return (re == Keyboard.KeyUpEvent || re == Keyboard.KeyDownEvent || re == TextCompositionManager.TextInputEvent || re == Mouse.MouseDownEvent || re == Mouse.MouseUpEvent); } internal static SynchronizedInputType GetPairedInputType(SynchronizedInputType inputType) { SynchronizedInputType pairedInputType = SynchronizedInputType.KeyDown; switch (inputType) { case SynchronizedInputType.KeyDown: pairedInputType = SynchronizedInputType.KeyUp; break; case SynchronizedInputType.KeyUp: pairedInputType = SynchronizedInputType.KeyDown; break; case SynchronizedInputType.MouseLeftButtonDown: pairedInputType = SynchronizedInputType.MouseLeftButtonUp; break; case SynchronizedInputType.MouseLeftButtonUp: pairedInputType = SynchronizedInputType.MouseLeftButtonDown; break; case SynchronizedInputType.MouseRightButtonDown: pairedInputType = SynchronizedInputType.MouseRightButtonUp; break; case SynchronizedInputType.MouseRightButtonUp: pairedInputType = SynchronizedInputType.MouseRightButtonDown; break; } return pairedInputType; } // Check whether InputManager is listening for this input. internal static bool IsListening(RoutedEventArgs args) { if (Array.IndexOf(InputManager.SynchronizedInputEvents, args.RoutedEvent) >= 0) { return true; } else { return false; } } // Check whether this element is listening for input. internal static bool IsListening(DependencyObject o, RoutedEventArgs args) { if (InputManager.ListeningElement == o && Array.IndexOf(InputManager.SynchronizedInputEvents, args.RoutedEvent) >= 0) { return true; } else { return false; } } internal static bool ShouldContinueListening(RoutedEventArgs args) { return args.RoutedEvent == Keyboard.KeyDownEvent; } // Add a preopportunity handler for the logical parent incase of templated element. internal static void AddParentPreOpportunityHandler(DependencyObject o, EventRoute route, RoutedEventArgs args) { // If the logical parent is different from visual parent then add handler on behalf of the // parent into the route. This is to cover the templated elements, where event could be // handled by one of the child visual element but we should consider it as if event is handled by // parent element ( logical parent). DependencyObject visualParent = null; if(o is Visual || o is Visual3D) { visualParent = UIElementHelper.GetUIParent(o); } DependencyObject logicalParent = SynchronizedInputHelper.GetUIParentCore(o); if (logicalParent != null && logicalParent != visualParent) { UIElement e = logicalParent as UIElement; if (e != null) { e.AddSynchronizedInputPreOpportunityHandler(route, args); } else { ContentElement ce = logicalParent as ContentElement; if (ce != null) { ce.AddSynchronizedInputPreOpportunityHandler(route, args); } else { UIElement3D e3D = logicalParent as UIElement3D; if (e3D != null) { e3D.AddSynchronizedInputPreOpportunityHandler(route, args); } } } } } // If the routed event type matches one the element listening on then add handler to the event route. internal static void AddHandlerToRoute(DependencyObject o, EventRoute route, RoutedEventHandler eventHandler, bool handledToo) { // Add a synchronized input handler to the route. route.Add(o, eventHandler, handledToo); } // If this handler is invoked then it indicates the element had the opportunity to handle event. internal static void PreOpportunityHandler(object sender, RoutedEventArgs args) { KeyboardEventArgs kArgs = args as KeyboardEventArgs; // if it's the keyboard event then we have 1:1 mapping between handlers & events, // so no remapping required. if (kArgs != null) { InputManager.SynchronizedInputState = SynchronizedInputStates.HadOpportunity; } else { TextCompositionEventArgs tArgs = args as TextCompositionEventArgs; if (tArgs != null) { InputManager.SynchronizedInputState = SynchronizedInputStates.HadOpportunity; } else { // If this is an mouse event then we have handlers only for generic MouseDown & MouseUp events, // so we need additional logic here to decide between Mouse left and right button events. MouseButtonEventArgs mbArgs = args as MouseButtonEventArgs; if (mbArgs != null) { Debug.Assert(mbArgs != null); switch (mbArgs.ChangedButton) { case MouseButton.Left: if (InputManager.SynchronizeInputType == SynchronizedInputType.MouseLeftButtonDown || InputManager.SynchronizeInputType == SynchronizedInputType.MouseLeftButtonUp) { InputManager.SynchronizedInputState = SynchronizedInputStates.HadOpportunity; } break; case MouseButton.Right: if (InputManager.SynchronizeInputType == SynchronizedInputType.MouseRightButtonDown || InputManager.SynchronizeInputType == SynchronizedInputType.MouseRightButtonUp) { InputManager.SynchronizedInputState = SynchronizedInputStates.HadOpportunity; } break; default: break; } } } } } // This handler will be called after all class and instance handlers are called, here we // decide whether the event is handled by this element or some other element. internal static void PostOpportunityHandler(object sender, RoutedEventArgs args) { KeyboardEventArgs kArgs = args as KeyboardEventArgs; // if it's the keyboard event then we have 1:1 mapping between handlers & events, // so no remapping required. if (kArgs != null) { InputManager.SynchronizedInputState = SynchronizedInputStates.Handled; } else { TextCompositionEventArgs tArgs = args as TextCompositionEventArgs; if (tArgs != null) { InputManager.SynchronizedInputState = SynchronizedInputStates.Handled; } else { // If this is an mouse event then we have handlers only for generic MouseDown & MouseUp events, // so we need additional logic here to decide between Mouse left and right button events. MouseButtonEventArgs mbArgs = args as MouseButtonEventArgs; Debug.Assert(mbArgs != null); if (mbArgs != null) { switch (mbArgs.ChangedButton) { case MouseButton.Left: if (InputManager.SynchronizeInputType == SynchronizedInputType.MouseLeftButtonDown || InputManager.SynchronizeInputType == SynchronizedInputType.MouseLeftButtonUp) { InputManager.SynchronizedInputState = SynchronizedInputStates.Handled; } break; case MouseButton.Right: if (InputManager.SynchronizeInputType == SynchronizedInputType.MouseRightButtonDown || InputManager.SynchronizeInputType == SynchronizedInputType.MouseRightButtonUp) { InputManager.SynchronizedInputState = SynchronizedInputStates.Handled; } break; default: break; } } } } } // Map a Synchronized input type received from automation client to routed event internal static RoutedEvent[] MapInputTypeToRoutedEvents(SynchronizedInputType inputType) { RoutedEvent[] e = null; switch (inputType) { case SynchronizedInputType.KeyUp: e = new RoutedEvent[] {Keyboard.KeyUpEvent}; break; case SynchronizedInputType.KeyDown: e = new RoutedEvent[] {Keyboard.KeyDownEvent, TextCompositionManager.TextInputEvent}; break; case SynchronizedInputType.MouseLeftButtonDown: case SynchronizedInputType.MouseRightButtonDown: e = new RoutedEvent[] {Mouse.MouseDownEvent}; break; case SynchronizedInputType.MouseLeftButtonUp: case SynchronizedInputType.MouseRightButtonUp: e = new RoutedEvent[] {Mouse.MouseUpEvent}; break; default: Debug.Assert(false); e = null; break; } return e; } internal static void RaiseAutomationEvents() { if (InputElement.IsUIElement(InputManager.ListeningElement)) { UIElement e = (UIElement)InputManager.ListeningElement; //Raise InputDiscarded automation event SynchronizedInputHelper.RaiseAutomationEvent(e.GetAutomationPeer()); } else if (InputElement.IsContentElement(InputManager.ListeningElement)) { ContentElement ce = (ContentElement)InputManager.ListeningElement; //Raise InputDiscarded automation event SynchronizedInputHelper.RaiseAutomationEvent(ce.GetAutomationPeer()); } else if (InputElement.IsUIElement3D(InputManager.ListeningElement)) { UIElement3D e3D = (UIElement3D)InputManager.ListeningElement; //Raise InputDiscarded automation event SynchronizedInputHelper.RaiseAutomationEvent(e3D.GetAutomationPeer()); } } // Raise synchronized input automation events here. internal static void RaiseAutomationEvent(AutomationPeer peer) { if (peer != null) { switch (InputManager.SynchronizedInputState) { case SynchronizedInputStates.Handled: peer.RaiseAutomationEvent(AutomationEvents.InputReachedTarget); break; case SynchronizedInputStates.Discarded: peer.RaiseAutomationEvent(AutomationEvents.InputDiscarded); break; default: peer.RaiseAutomationEvent(AutomationEvents.InputReachedOtherElement); break; } } } } internal enum SynchronizedInputStates { NoOpportunity = 0x01, HadOpportunity = 0x02, Handled = 0x04, Discarded = 0x08 }; }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Medo.Security.Cryptography.PasswordSafe { /// <summary> /// Collection of record fields. /// </summary> [DebuggerDisplay("{Count} records")] public class RecordCollection : IList<Record> { /// <summary> /// Create a new instance. /// </summary> internal RecordCollection(Entry owner, ICollection<Record> fields) { foreach (var field in fields) { if (field.Owner != null) { throw new ArgumentOutOfRangeException(nameof(fields), "Item cannot be in other collection."); } } Owner = owner; BaseCollection.AddRange(fields); foreach (var field in fields) { field.Owner = this; } } internal Entry Owner { get; set; } internal void MarkAsChanged(RecordType type = 0) { if ((Owner != null) && (Owner.Owner != null)) { Owner.Owner.MarkAsChanged(); } if (Count == 0) { return; } //don't track times if there is no other elements if (!IsReadOnly && (Owner != null) && (this?.Owner?.Owner?.Owner?.TrackModify ?? false)) { switch (type) { case RecordType.CreationTime: case RecordType.PasswordModificationTime: case RecordType.LastModificationTime: case RecordType.LastAccessTime: break; //ignore changes to fields we auto-fill default: if (!Owner.Records.Contains(RecordType.CreationTime)) { //if there is no creation time yet, assume it is just now created. Owner.Records[RecordType.CreationTime].Time = DateTime.UtcNow; } else { Owner.Records[RecordType.LastModificationTime].Time = DateTime.UtcNow; } if (type == RecordType.Password) { Owner.Records[RecordType.PasswordModificationTime].Time = DateTime.UtcNow; } break; } } } internal void MarkAsAccessed(RecordType type = 0) { if (!IsReadOnly && (Owner != null) && (this?.Owner?.Owner?.Owner?.TrackAccess ?? false)) { switch (type) { case RecordType.Uuid: case RecordType.Group: case RecordType.Title: break; //ignore access to fields we need for normal display case RecordType.CreationTime: case RecordType.PasswordModificationTime: case RecordType.LastModificationTime: case RecordType.LastAccessTime: break; //ignore access to fields we auto-fill default: Owner.Records[RecordType.LastAccessTime].Time = DateTime.UtcNow; break; } } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly List<Record> BaseCollection = new List<Record>(); #region ICollection /// <summary> /// Adds an item. /// </summary> /// <param name="item">Item.</param> /// <exception cref="ArgumentNullException">Item cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Item cannot be in other collection.</exception> /// <exception cref="NotSupportedException">Collection is read-only.</exception> public void Add(Record item) { if (item == null) { throw new ArgumentNullException(nameof(item), "Item cannot be null."); } if (item.Owner != null) { throw new ArgumentOutOfRangeException(nameof(item), "Item cannot be in other collection."); } if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); } BaseCollection.Add(item); item.Owner = this; MarkAsChanged(item.RecordType); } /// <summary> /// Adds multiple items. /// </summary> /// <param name="items">Item.</param> /// <exception cref="ArgumentNullException">Items cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Item cannot be in other collection.</exception> /// <exception cref="NotSupportedException">Collection is read-only.</exception> public void AddRange(IEnumerable<Record> items) { if (items == null) { throw new ArgumentNullException(nameof(items), "Item cannot be null."); } foreach (var item in items) { if (item.Owner != null) { throw new ArgumentOutOfRangeException(nameof(items), "Item cannot be in other collection."); } } if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); } BaseCollection.AddRange(items); foreach (var item in items) { item.Owner = this; } MarkAsChanged(); } /// <summary> /// Removes all items. /// </summary> /// <exception cref="NotSupportedException">Collection is read-only.</exception> public void Clear() { if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); } foreach (var item in BaseCollection) { item.Owner = null; } BaseCollection.Clear(); MarkAsChanged(); } /// <summary> /// Determines whether the collection contains a specific item. /// </summary> /// <param name="item">The item to locate.</param> public bool Contains(Record item) { if (item == null) { return false; } return BaseCollection.Contains(item); } /// <summary> /// Copies the elements of the collection to an array, starting at a particular array index. /// </summary> /// <param name="array">The one-dimensional array that is the destination of the elements copied from collection.</param> /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param> public void CopyTo(Record[] array, int arrayIndex) { BaseCollection.CopyTo(array, arrayIndex); } /// <summary> /// Gets the number of items contained in the collection. /// </summary> public int Count { get { return BaseCollection.Count; } } /// <summary> /// Searches for the specified item and returns the zero-based index of the first occurrence within the entire collection. /// </summary> /// <param name="item">The item to locate.</param> public int IndexOf(Record item) { return BaseCollection.IndexOf(item); } /// <summary> /// Inserts an element into the collection at the specified index. /// </summary> /// <param name="index">The zero-based index at which item should be inserted.</param> /// <param name="item">The item to insert.</param> /// <exception cref="ArgumentNullException">Item cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Index is less than 0. -or- Index is greater than collection count.</exception> /// <exception cref="NotSupportedException">Collection is read-only.</exception> public void Insert(int index, Record item) { if (item == null) { throw new ArgumentNullException(nameof(item), "Item cannot be null."); } if (item.Owner != null) { throw new ArgumentOutOfRangeException(nameof(item), "Item cannot be in other collection."); } if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); } BaseCollection.Insert(index, item); item.Owner = this; MarkAsChanged(item.RecordType); } /// <summary> /// Gets a value indicating whether the collection is read-only. /// </summary> public bool IsReadOnly { get { return Owner?.Owner?.Owner?.IsReadOnly ?? false; } } /// <summary> /// Removes the item from the collection. /// </summary> /// <param name="item">The item to remove.</param> /// <exception cref="ArgumentNullException">Item cannot be null.</exception> /// <exception cref="NotSupportedException">Collection is read-only.</exception> public bool Remove(Record item) { if (item == null) { throw new ArgumentNullException(nameof(item), "Item cannot be null."); } if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); } if (BaseCollection.Remove(item)) { item.Owner = null; MarkAsChanged(item.RecordType); return true; } else { return false; } } /// <summary> /// Removes the element at the specified index of the collection. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="ArgumentOutOfRangeException">Index is less than 0. -or- Index is equal to or greater than collection count.</exception> /// <exception cref="NotSupportedException">Collection is read-only.</exception> public void RemoveAt(int index) { if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); } var item = this[index]; BaseCollection.Remove(item); item.Owner = null; MarkAsChanged(item.RecordType); } /// <summary> /// Exposes the enumerator, which supports a simple iteration over a collection of a specified type. /// </summary> public IEnumerator<Record> GetEnumerator() { var items = new List<Record>(BaseCollection); //to avoid exception if collection is changed while in foreach foreach (var item in items) { yield return item; } } /// <summary> /// Exposes the enumerator, which supports a simple iteration over a non-generic collection. /// </summary> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <exception cref="ArgumentNullException">Value cannot be null.</exception> /// <exception cref="ArgumentOutOfRangeException">Index is less than 0. -or- Index is equal to or greater than collection count. -or- Duplicate name in collection.</exception> /// <exception cref="NotSupportedException">Collection is read-only.</exception> public Record this[int index] { get { return BaseCollection[index]; } set { if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); } if (value == null) { throw new ArgumentNullException(nameof(value), "Value cannot be null."); } if (value.Owner != null) { throw new ArgumentOutOfRangeException(nameof(value), "Item cannot be in other collection."); } if (Contains(value)) { throw new ArgumentOutOfRangeException(nameof(value), "Duplicate item in collection."); } var item = BaseCollection[index]; item.Owner = null; BaseCollection.RemoveAt(index); BaseCollection.Insert(index, value); value.Owner = this; MarkAsChanged(value.RecordType); } } #endregion #region ICollection extra /// <summary> /// Determines whether the collection contains a specific type. /// </summary> /// <param name="type">The item type to locate.</param> public bool Contains(RecordType type) { foreach (var item in BaseCollection) { if (item.RecordType == type) { return true; } } return false; } /// <summary> /// Gets field based on a type. /// If multiple elements exist with the same field type, the first one is returned. /// If type does not exist, it is created. /// /// If value is set to null, field is removed. /// </summary> /// <param name="type">Type.</param> /// <exception cref="ArgumentOutOfRangeException">Only null value is supported.</exception> /// <exception cref="NotSupportedException">Collection is read-only.</exception> public Record this[RecordType type] { get { foreach (var field in BaseCollection) { if (field.RecordType == type) { return field; } } if (IsReadOnly) { return new Record(type); } //return dummy record if collection is read-only var newField = new Record(this, type); //create a new field if one cannot be found int index; for (index = 0; index < BaseCollection.Count; index++) { if (BaseCollection[index].RecordType > type) { break; } } BaseCollection.Insert(index, newField); //insert it in order (does not change order for existing ones) return newField; } set { if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); } if (value != null) { throw new ArgumentOutOfRangeException(nameof(value), "Only null value is supported."); } Record fieldToRemove = null; foreach (var field in BaseCollection) { if (field.RecordType == type) { fieldToRemove = field; break; } } if (fieldToRemove != null) { Remove(fieldToRemove); } } } #endregion } }