context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// StreamManipulator.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace PdfSharp.SharpZipLib.Zip.Compression.Streams { /// <summary> /// This class allows us to retrieve a specified number of bits from /// the input buffer, as well as copy big byte blocks. /// /// It uses an int buffer to store up to 31 bits for direct /// manipulation. This guarantees that we can get at least 16 bits, /// but we only need at most 15, so this is all safe. /// /// There are some optimizations in this class, for example, you must /// never peek more than 8 bits more than needed, and you must first /// peek bits before you may drop them. This is not a general purpose /// class but optimized for the behaviour of the Inflater. /// /// Authors of the original java version: John Leuner, Jochen Hoenicke /// </summary> internal class StreamManipulator { private byte[] window; private int window_start = 0; private int window_end = 0; private uint buffer = 0; private int bits_in_buffer = 0; /// <summary> /// Get the next n bits but don't increase input pointer. n must be /// less or equal 16 and if this call succeeds, you must drop /// at least n - 8 bits in the next call. /// </summary> /// <returns> /// the value of the bits, or -1 if not enough bits available. */ /// </returns> public int PeekBits(int n) { if (bits_in_buffer < n) { if (window_start == window_end) { return -1; // ok } buffer |= (uint)((window[window_start++] & 0xff | (window[window_start++] & 0xff) << 8) << bits_in_buffer); bits_in_buffer += 16; } return (int)(buffer & ((1 << n) - 1)); } /// <summary> /// Drops the next n bits from the input. You should have called PeekBits /// with a bigger or equal n before, to make sure that enough bits are in /// the bit buffer. /// </summary> public void DropBits(int n) { buffer >>= n; bits_in_buffer -= n; } /// <summary> /// Gets the next n bits and increases input pointer. This is equivalent /// to PeekBits followed by dropBits, except for correct error handling. /// </summary> /// <returns> /// the value of the bits, or -1 if not enough bits available. /// </returns> public int GetBits(int n) { int bits = PeekBits(n); if (bits >= 0) { DropBits(n); } return bits; } /// <summary> /// Gets the number of bits available in the bit buffer. This must be /// only called when a previous PeekBits() returned -1. /// </summary> /// <returns> /// the number of bits available. /// </returns> public int AvailableBits { get { return bits_in_buffer; } } /// <summary> /// Gets the number of bytes available. /// </summary> /// <returns> /// The number of bytes available. /// </returns> public int AvailableBytes { get { return window_end - window_start + (bits_in_buffer >> 3); } } /// <summary> /// Skips to the next byte boundary. /// </summary> public void SkipToByteBoundary() { buffer >>= (bits_in_buffer & 7); bits_in_buffer &= ~7; } /// <summary> /// Returns true when SetInput can be called /// </summary> public bool IsNeedingInput { get { return window_start == window_end; } } /// <summary> /// Copies length bytes from input buffer to output buffer starting /// at output[offset]. You have to make sure, that the buffer is /// byte aligned. If not enough bytes are available, copies fewer /// bytes. /// </summary> /// <param name="output"> /// The buffer to copy bytes to. /// </param> /// <param name="offset"> /// The offset in the buffer at which copying starts /// </param> /// <param name="length"> /// The length to copy, 0 is allowed. /// </param> /// <returns> /// The number of bytes copied, 0 if no bytes were available. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Length is less than zero /// </exception> /// <exception cref="InvalidOperationException"> /// Bit buffer isnt byte aligned /// </exception> public int CopyBytes(byte[] output, int offset, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } if ((bits_in_buffer & 7) != 0) { /* bits_in_buffer may only be 0 or a multiple of 8 */ throw new InvalidOperationException("Bit buffer is not byte aligned!"); } int count = 0; while (bits_in_buffer > 0 && length > 0) { output[offset++] = (byte)buffer; buffer >>= 8; bits_in_buffer -= 8; length--; count++; } if (length == 0) { return count; } int avail = window_end - window_start; if (length > avail) { length = avail; } System.Array.Copy(window, window_start, output, offset, length); window_start += length; if (((window_start - window_end) & 1) != 0) { /* We always want an even number of bytes in input, see peekBits */ buffer = (uint)(window[window_start++] & 0xff); bits_in_buffer = 8; } return count + length; } /// <summary> /// Constructs a default StreamManipulator with all buffers empty /// </summary> public StreamManipulator() { } /// <summary> /// resets state and empties internal buffers /// </summary> public void Reset() { buffer = (uint)(window_start = window_end = bits_in_buffer = 0); } /// <summary> /// Add more input for consumption. /// Only call when IsNeedingInput returns true /// </summary> /// <param name="buf">data to be input</param> /// <param name="off">offset of first byte of input</param> /// <param name="len">length of input</param> public void SetInput(byte[] buf, int off, int len) { if (window_start < window_end) { throw new InvalidOperationException("Old input was not completely processed"); } int end = off + len; /* We want to throw an ArrayIndexOutOfBoundsException early. The * check is very tricky: it also handles integer wrap around. */ if (0 > off || off > end || end > buf.Length) { throw new ArgumentOutOfRangeException(); } if ((len & 1) != 0) { /* We always want an even number of bytes in input, see peekBits */ buffer |= (uint)((buf[off++] & 0xff) << bits_in_buffer); bits_in_buffer += 8; } window = buf; window_start = off; window_end = end; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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.IO; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Sensus { public class Logger { private const int MAX_LOG_SIZE_MEGABYTES = 20; private string _path; private LoggingLevel _level; private TextWriter[] _otherOutputs; private List<string> _messageBuffer; private Regex _extraWhiteSpace; public LoggingLevel Level { get { return _level; } set { _level = value; } } public Logger(string path, LoggingLevel level, params TextWriter[] otherOutputs) { _path = path; _level = level; _otherOutputs = otherOutputs; _messageBuffer = new List<string>(); _extraWhiteSpace = new Regex(@"\s\s+"); } public void Log(string message, LoggingLevel level, Type callingType, bool throwException = false) { // if we're throwing an exception, use the caller's version of the message instead of our modified version below. Exception ex = null; if (throwException) ex = new Exception(message); if (level <= _level) { // remove newlines and extra white space, and only log if the result is non-empty message = _extraWhiteSpace.Replace(message.Replace('\r', ' ').Replace('\n', ' ').Trim(), " "); if (!string.IsNullOrWhiteSpace(message)) { // add timestamp and calling type type message = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + ": " + (callingType == null ? "" : "[" + callingType.Name + "] ") + message; lock (_messageBuffer) { _messageBuffer.Add(message); if (_otherOutputs != null) foreach (TextWriter otherOutput in _otherOutputs) { try { otherOutput.WriteLine(message); } catch (Exception writeException) { Console.Error.WriteLine("Failed to write to output: " + writeException.Message); } } // append buffer to file periodically if (_messageBuffer.Count % 100 == 0) { try { CommitMessageBuffer(); } catch (Exception commitException) { // try switching the log path to a random file, since access violations might prevent us from writing the current _path (e.g., in the case of crashes) _path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), Guid.NewGuid().ToString() + ".txt"); _messageBuffer.Add("Switched log path to \"" + _path + "\" due to exception: " + commitException.Message); } } } } } if (ex != null) throw ex; } public void CommitMessageBuffer() { lock (_messageBuffer) { if (_messageBuffer.Count > 0) { try { using (StreamWriter file = new StreamWriter(_path, true)) { foreach (string bufferedMessage in _messageBuffer) file.WriteLine(bufferedMessage); } // keep log file under a certain size by reading the most recent MAX_LOG_SIZE_MEGABYTES. long currSizeBytes = new FileInfo(_path).Length; if (currSizeBytes > MAX_LOG_SIZE_MEGABYTES * 1024 * 1024) { int newSizeBytes = (MAX_LOG_SIZE_MEGABYTES - 5) * 1024 * 1024; byte[] newBytes = new byte[newSizeBytes]; using (FileStream file = new FileStream(_path, FileMode.Open, FileAccess.Read)) { file.Position = currSizeBytes - newSizeBytes; file.Read(newBytes, 0, newSizeBytes); } File.Delete(_path); File.WriteAllBytes(_path, newBytes); } } catch (Exception ex) { Log("Error committing message buffer: " + ex.Message, LoggingLevel.Normal, GetType()); } _messageBuffer.Clear(); } } } public List<string> Read(int maxMessages, bool mostRecentFirst) { lock (_messageBuffer) { CommitMessageBuffer(); List<string> messages = new List<string>(); try { using (StreamReader file = new StreamReader(_path)) { if (maxMessages > 0) { int numLines = 0; while (file.ReadLine() != null) ++numLines; file.BaseStream.Position = 0; file.DiscardBufferedData(); int linesToSkip = Math.Max(numLines - maxMessages, 0); for (int i = 1; i <= linesToSkip; ++i) file.ReadLine(); } string line; while ((line = file.ReadLine()) != null) messages.Add(line); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Error reading log file: " + ex.Message, LoggingLevel.Normal, GetType()); } if (mostRecentFirst) messages.Reverse(); return messages; } } public void CopyTo(string path) { lock (_messageBuffer) { CommitMessageBuffer(); try { File.Copy(_path, path); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to copy log file to \"" + path + "\": " + ex.Message, LoggingLevel.Normal, GetType()); } } } public virtual void Clear() { lock (_messageBuffer) { try { File.Delete(_path); } catch (Exception) { } _messageBuffer.Clear(); } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo; using Vevo.DataAccessLib; using Vevo.DataAccessLib.Cart; using Vevo.Domain; using Vevo.Domain.DataInterfaces; using Vevo.Shared.DataAccess; using Vevo.WebAppLib; using Vevo.WebUI.International; using Vevo.Base.Domain; public partial class AdminAdvanced_MainControls_CultureList : AdminAdvancedBaseListControl { private const int ColumnCultureID = 1; private const int ColumnName = 2; private void PopulateControls() { RefreshGrid(); if (uxGridCulture.Rows.Count > 0) { uxPagingControl.Visible = true; DeleteVisible( true ); } else { uxPagingControl.Visible = false; DeleteVisible( false ); } if (!IsAdminModifiable()) { uxAddButton.Visible = false; DeleteVisible( false ); } } private void DeleteVisible( bool value ) { uxDeleteButton.Visible = value; if (value) { if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { uxDeleteConfirmButton.TargetControlID = "uxDeleteButton"; uxConfirmModalPopup.TargetControlID = "uxDeleteButton"; } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } private void uxGridCulture_ClearSearchtHandler( object sender, EventArgs e ) { uxSearchFilter.ClearFilter(); RefreshGrid(); } private void uxGridCulture_RefreshHandler( object sender, EventArgs e ) { RefreshGrid(); } private void uxGridCulture_ResetHandler( object sender, EventArgs e ) { uxPagingControl.CurrentPage = 1; RefreshGrid(); } private void DeleteAllRelateFieldCultureID( string cultureID ) { DataAccessContext.CategoryRepository.DeleteLocalesByCultureID( cultureID ); DataAccessContext.ContentRepository.DeleteLocalesByCultureID( cultureID ); DataAccessContext.OptionItemRepository.DeleteLocalesByCultureID( cultureID ); DataAccessContext.OptionGroupRepository.DeleteLocalesByCultureID( cultureID ); DataAccessContext.ProductRepository.DeleteLocalesByCultureID( cultureID ); DataAccessContext.NewsRepository.DeleteLocalesByCultureID( cultureID ); DataAccessContext.ShippingOptionRepository.DeleteLocalesByCultureID( cultureID ); LanguageTextAccess.DeleteByCultureID( cultureID ); } private void SetUpSearchFilter() { IList<TableSchemaItem> list = DataAccessContext.CultureRepository.GetTableSchema(); uxSearchFilter.SetUpSchema( list ); } private void SetUpGridSupportControls() { if (!MainContext.IsPostBack) { uxPagingControl.ItemsPerPages = AdminConfig.CultureItemsPerPage; SetUpSearchFilter(); } RegisterGridView( uxGridCulture, "CultureID" ); RegisterSearchFilter( uxSearchFilter ); RegisterPagingControl( uxPagingControl ); uxSearchFilter.BubbleEvent += new EventHandler( uxSearchFilter_BubbleEvent ); uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_BubbleEvent ); } private void DeleteCultureInformation( string cultureID ) { DeleteEmailTemplate( cultureID ); } private void DeleteEmailTemplate( string cultureID ) { DataAccessContext.EmailTemplateDetailRepository.DeleteLocalesByCultureID( cultureID ); } protected void Page_Load( object sender, EventArgs e ) { SetUpGridSupportControls(); } protected void Page_PreRender( object sender, EventArgs e ) { PopulateControls(); } protected void uxAddButton_Click( object sender, EventArgs e ) { MainContext.RedirectMainControl( "CultureAdd.ascx", "" ); } protected void uxDeleteButton_Click( object sender, EventArgs e ) { try { bool deleted = false; foreach (GridViewRow row in uxGridCulture.Rows) { CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" ); if (deleteCheck.Checked) { string defaultLanguage = row.Cells[ColumnName].Text.Trim(); CultureConfigs cultureConfigs = new CultureConfigs(); if (cultureConfigs.UseCultureName( defaultLanguage )) { uxMessage.DisplayError( Resources.CultureMessages.DeleteErrorExistingConfig ); return; } string id = row.Cells[ColumnCultureID].Text.Trim(); DataAccessContext.CultureRepository.Delete( id ); //Delete Relate Table (CultureID) DeleteAllRelateFieldCultureID( id ); deleted = true; //Delete Email Template DeleteCultureInformation( id ); } } if (deleted) { AdminUtilities.ClearLanguageCache(); uxMessage.DisplayMessage( Resources.CultureMessages.DeleteSuccess ); } } catch (DataAccessException ex) { uxMessage.DisplayError( "Error:<br/>" + ex.Message ); } catch { uxMessage.DisplayError( Resources.CultureMessages.DeleteError ); } RefreshGrid(); if (uxGridCulture.Rows.Count == 0 && uxPagingControl.CurrentPage >= uxPagingControl.NumberOfPages) { uxPagingControl.CurrentPage = uxPagingControl.NumberOfPages; RefreshGrid(); } } protected override void RefreshGrid() { int totalItems; uxGridCulture.DataSource = DataAccessContext.CultureRepository.SearchCulture( GridHelper.GetFullSortText(), uxSearchFilter.SearchFilterObj, uxPagingControl.StartIndex, uxPagingControl.EndIndex, out totalItems ); uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages ); uxGridCulture.DataBind(); } }
// #define IMITATE_BATCH_MODE //uncomment if you want to imitate batch mode behaviour in non-batch mode mode run using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityTest.IntegrationTestRunner; using System.IO; using UnityEngine.SceneManagement; using XposeCraft.GameInternal; namespace UnityTest { [Serializable] [ExecuteInEditMode] public class TestRunner : MonoBehaviour { public static bool ApplicationIsPlaying { get; set; } static private int TestSceneNumber; static private readonly TestResultRenderer k_ResultRenderer = new TestResultRenderer(); public TestComponent currentTest; private List<TestResult> m_ResultList = new List<TestResult>(); private List<TestComponent> m_TestComponents; public bool isInitializedByRunner { get { #if !IMITATE_BATCH_MODE if (Application.isEditor) return true; #endif return false; } } private double m_StartTime; private bool m_ReadyToRun; private string m_TestMessages; private string m_Stacktrace; private TestState m_TestState = TestState.Running; private TestRunnerConfigurator m_Configurator; public TestRunnerCallbackList TestRunnerCallback = new TestRunnerCallbackList(); private IntegrationTestsProvider m_TestsProvider; private const string k_Prefix = "IntegrationTest"; private const string k_StartedMessage = k_Prefix + " Started"; private const string k_FinishedMessage = k_Prefix + " Finished"; private const string k_TimeoutMessage = k_Prefix + " Timeout"; private const string k_FailedMessage = k_Prefix + " Failed"; private const string k_FailedExceptionMessage = k_Prefix + " Failed with exception"; private const string k_IgnoredMessage = k_Prefix + " Ignored"; private const string k_InterruptedMessage = k_Prefix + " Run interrupted"; public void Awake() { m_Configurator = new TestRunnerConfigurator(); if (isInitializedByRunner) return; TestComponent.DisableAllTests(); } public void Start() { // Preventing OnDestroy call with invalid internal state currentTest = null; if (isInitializedByRunner) return; if (m_Configurator.sendResultsOverNetwork) { var nrs = m_Configurator.ResolveNetworkConnection(); if (nrs != null) TestRunnerCallback.Add(nrs); } TestComponent.DestroyAllDynamicTests(); var dynamicTestTypes = TestComponent.GetTypesWithHelpAttribute(SceneManager.GetActiveScene().name); foreach (var dynamicTestType in dynamicTestTypes) TestComponent.CreateDynamicTest(dynamicTestType); var tests = TestComponent.FindAllTestsOnScene(); InitRunner(tests, dynamicTestTypes.Select(type => type.AssemblyQualifiedName).ToList()); } public void InitRunner(List<TestComponent> tests, List<string> dynamicTestsToRun) { Application.logMessageReceived += LogHandler; // Init dynamic tests foreach (var typeName in dynamicTestsToRun) { var t = Type.GetType(typeName); if (t == null) continue; var scriptComponents = Resources.FindObjectsOfTypeAll(t) as MonoBehaviour[]; if (scriptComponents.Length == 0) { Debug.LogWarning(t + " not found. Skipping."); continue; } if (scriptComponents.Length > 1) Debug.LogWarning("Multiple GameObjects refer to " + typeName); tests.Add(scriptComponents.First().GetComponent<TestComponent>()); } // create test structure m_TestComponents = ParseListForGroups(tests).ToList(); // create results for tests m_ResultList = m_TestComponents.Select(component => new TestResult(component)).ToList(); // init test provider m_TestsProvider = new IntegrationTestsProvider(m_ResultList.Select(result => result.TestComponent as ITestComponent)); m_ReadyToRun = true; } private static IEnumerable<TestComponent> ParseListForGroups(IEnumerable<TestComponent> tests) { var results = new HashSet<TestComponent>(); foreach (var testResult in tests) { if (testResult.IsTestGroup()) { var childrenTestResult = testResult.gameObject.GetComponentsInChildren(typeof(TestComponent), true) .Where(t => t != testResult) .Cast<TestComponent>() .ToArray(); foreach (var result in childrenTestResult) { if (!result.IsTestGroup()) results.Add(result); } continue; } results.Add(testResult); } return results; } public void Update() { ApplicationIsPlaying = Application.isPlaying; if (!ApplicationIsPlaying) { return; } if (m_ReadyToRun && Time.frameCount > 1) { m_ReadyToRun = false; StartCoroutine("StateMachine"); } } public void OnDestroy() { if (currentTest != null) { var testResult = m_ResultList.Single(result => result.TestComponent == currentTest); testResult.messages += "Test run interrupted (crash?)"; LogMessage(k_InterruptedMessage); FinishTest(TestResult.ResultType.Failed); } if (currentTest != null || (m_TestsProvider != null && m_TestsProvider.AnyTestsLeft())) { var remainingTests = m_TestsProvider.GetRemainingTests(); TestRunnerCallback.TestRunInterrupted(remainingTests.ToList()); } Application.logMessageReceived -= LogHandler; } private void LogHandler(string condition, string stacktrace, LogType type) { if (!condition.StartsWith(k_StartedMessage) && !condition.StartsWith(k_FinishedMessage)) { var msg = condition; if (msg.StartsWith(k_Prefix)) msg = msg.Substring(k_Prefix.Length + 1); if (currentTest != null && msg.EndsWith("(" + currentTest.name + ')')) msg = msg.Substring(0, msg.LastIndexOf('(')); m_TestMessages += msg + "\n"; } switch (type) { case LogType.Exception: { var exceptionType = condition.Substring(0, condition.IndexOf(':')); if (currentTest != null && currentTest.IsExceptionExpected(exceptionType)) { m_TestMessages += exceptionType + " was expected\n"; if (currentTest.ShouldSucceedOnException()) { m_TestState = TestState.Success; } } else { m_TestState = TestState.Exception; m_Stacktrace = stacktrace; } } break; case LogType.Assert: case LogType.Error: m_TestState = TestState.Failure; m_Stacktrace = stacktrace; break; case LogType.Log: if (m_TestState == TestState.Running && condition.StartsWith(IntegrationTest.passMessage)) { m_TestState = TestState.Success; } if (condition.StartsWith(IntegrationTest.failMessage)) { m_TestState = TestState.Failure; } break; } } public IEnumerator StateMachine() { TestRunnerCallback.RunStarted(Application.platform.ToString(), m_TestComponents); while (true) { if (!m_TestsProvider.AnyTestsLeft() && currentTest == null) { FinishTestRun(); yield break; } if (currentTest == null) { StartNewTest(); } if (currentTest != null) { if (m_TestState == TestState.Running) { if(currentTest.ShouldSucceedOnAssertions()) { var assertionsToCheck = currentTest.gameObject.GetComponentsInChildren<AssertionComponent>().Where(a => a.enabled).ToArray(); if (assertionsToCheck.Any () && assertionsToCheck.All(a => a.checksPerformed > 0)) { IntegrationTest.Pass(currentTest.gameObject); m_TestState = TestState.Success; } } if (currentTest != null && Time.time > m_StartTime + currentTest.GetTimeout()) { m_TestState = TestState.Timeout; } } switch (m_TestState) { case TestState.Success: LogMessage(k_FinishedMessage); FinishTest(TestResult.ResultType.Success); break; case TestState.Failure: LogMessage(k_FailedMessage); FinishTest(TestResult.ResultType.Failed); break; case TestState.Exception: LogMessage(k_FailedExceptionMessage); FinishTest(TestResult.ResultType.FailedException); break; case TestState.Timeout: LogMessage(k_TimeoutMessage); FinishTest(TestResult.ResultType.Timeout); break; case TestState.Ignored: LogMessage(k_IgnoredMessage); FinishTest(TestResult.ResultType.Ignored); break; } } yield return null; } } private void LogMessage(string message) { if (currentTest != null) Debug.Log(message + " (" + currentTest.Name + ")", currentTest.gameObject); else Debug.Log(message); } private void FinishTestRun() { PrintResultToLog(); TestRunnerCallback.RunFinished(m_ResultList); LoadNextLevelOrQuit(); } private void PrintResultToLog() { var resultString = ""; resultString += "Passed: " + m_ResultList.Count(t => t.IsSuccess); if (m_ResultList.Any(result => result.IsFailure)) { resultString += " Failed: " + m_ResultList.Count(t => t.IsFailure); Debug.Log("Failed tests: " + string.Join(", ", m_ResultList.Where(t => t.IsFailure).Select(result => result.Name).ToArray())); } if (m_ResultList.Any(result => result.IsIgnored)) { resultString += " Ignored: " + m_ResultList.Count(t => t.IsIgnored); Debug.Log("Ignored tests: " + string.Join(", ", m_ResultList.Where(t => t.IsIgnored).Select(result => result.Name).ToArray())); } Debug.Log(resultString); } private void LoadNextLevelOrQuit() { if (isInitializedByRunner) return; TestSceneNumber += 1; string testScene = m_Configurator.GetIntegrationTestScenes(TestSceneNumber); if (testScene != null) SceneManager.LoadScene(Path.GetFileNameWithoutExtension(testScene)); else { TestRunnerCallback.AllScenesFinished(); k_ResultRenderer.ShowResults(); #if UNITY_EDITOR var prevScenes = m_Configurator.GetPreviousScenesToRestore(); if(prevScenes!=null) { UnityEditor.EditorBuildSettings.scenes = prevScenes; } #endif if (m_Configurator.isBatchRun && m_Configurator.sendResultsOverNetwork) Application.Quit(); } } public void OnGUI() { k_ResultRenderer.Draw(); } private void StartNewTest() { m_TestMessages = ""; m_Stacktrace = ""; m_TestState = TestState.Running; m_StartTime = Time.time; currentTest = m_TestsProvider.GetNextTest() as TestComponent; Log.d(this, "Starting a new test component " + (currentTest == null ? "null " : currentTest.name)); var testResult = m_ResultList.Single(result => result.TestComponent == currentTest); if (currentTest != null && currentTest.IsExludedOnThisPlatform()) { m_TestState = TestState.Ignored; Debug.Log(currentTest.gameObject.name + " is excluded on this platform"); } // don't ignore test if user initiated it from the runner and it's the only test that is being run if (currentTest != null && (currentTest.IsIgnored() && !(isInitializedByRunner && m_ResultList.Count == 1))) m_TestState = TestState.Ignored; LogMessage(k_StartedMessage); TestRunnerCallback.TestStarted(testResult); } private void FinishTest(TestResult.ResultType result) { // Hot-swap can cause the test provider to be lost if (m_TestsProvider != null) { m_TestsProvider.FinishTest(currentTest); } var testResult = m_ResultList.Single(t => t.GameObject == currentTest.gameObject); testResult.resultType = result; testResult.duration = Time.time - m_StartTime; testResult.messages = m_TestMessages; testResult.stacktrace = m_Stacktrace; TestRunnerCallback.TestFinished(testResult); currentTest = null; if (!testResult.IsSuccess && testResult.Executed && !testResult.IsIgnored) k_ResultRenderer.AddResults(SceneManager.GetActiveScene().name, testResult); } #region Test Runner Helpers public static TestRunner GetTestRunner() { TestRunner testRunnerComponent = null; var testRunnerComponents = Resources.FindObjectsOfTypeAll(typeof(TestRunner)); if (testRunnerComponents.Count() > 1) foreach (var t in testRunnerComponents) DestroyImmediate(((TestRunner)t).gameObject); else if (!testRunnerComponents.Any()) testRunnerComponent = Create().GetComponent<TestRunner>(); else testRunnerComponent = testRunnerComponents.Single() as TestRunner; return testRunnerComponent; } private static GameObject Create() { var runner = new GameObject("TestRunner"); runner.AddComponent<TestRunner>(); Debug.Log("Created Test Runner"); return runner; } private static bool IsBatchMode() { #if !UNITY_METRO const string internalEditorUtilityClassName = "UnityEditorInternal.InternalEditorUtility, UnityEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"; var t = Type.GetType(internalEditorUtilityClassName, false); if (t == null) return false; const string inBatchModeProperty = "inBatchMode"; var prop = t.GetProperty(inBatchModeProperty); return (bool)prop.GetValue(null, null); #else // if !UNITY_METRO return false; #endif // if !UNITY_METRO } #endregion enum TestState { Running, Success, Failure, Exception, Timeout, Ignored } } }
#region Copyright (c) Roni Schuetz - All Rights Reserved // * --------------------------------------------------------------------- * // * Roni Schuetz * // * Copyright (c) 2008 All Rights reserved * // * * // * Shared Cache high-performance, distributed caching and * // * replicated caching system, generic in nature, but intended to * // * speeding up dynamic web and / or win applications by alleviating * // * database load. * // * * // * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) * // * * // * This library is free software; you can redistribute it and/or * // * modify it under the terms of the GNU Lesser General Public License * // * as published by the Free Software Foundation; either version 2.1 * // * of the License, or (at your option) any later version. * // * * // * This library is distributed in the hope that it will be useful, * // * but WITHOUT ANY WARRANTY; without even the implied warranty of * // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * // * Lesser General Public License for more details. * // * * // * You should have received a copy of the GNU Lesser General Public * // * License along with this library; if not, write to the Free * // * Software Foundation, Inc., 59 Temple Place, Suite 330, * // * Boston, MA 02111-1307 USA * // * * // * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. * // * --------------------------------------------------------------------- * #endregion // ************************************************************************* // // Name: Indexus.cs // // Created: 21-01-2007 SharedCache.com, rschuetz // Modified: 21-01-2007 SharedCache.com, rschuetz : Creation // Modified: 31-12-2007 SharedCache.com, rschuetz : updated consistency of logging calls // ************************************************************************* using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Configuration.Install; using System.Data; using System.Diagnostics; using System.IO; using System.ServiceProcess; using System.Text; using System.Threading; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Net; using System.Net.Sockets; using System.Security.Permissions; using System.Xml; using System.Xml.Serialization; using COM = SharedCache.WinServiceCommon; namespace SharedCache.WinService { partial class Indexus : ServiceBase { /// <summary> /// running thread /// </summary> private Thread runThread; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Singleton: ServiceLogic private ServiceLogic serviceLogicInstance; /// <summary> /// Singleton for <see cref="ServiceLogic" /> /// </summary> public ServiceLogic ServiceLogicInstance { [System.Diagnostics.DebuggerStepThrough] get { if (serviceLogicInstance == null) this.serviceLogicInstance = new ServiceLogic(); return this.serviceLogicInstance; } } #endregion /// <summary> /// Initializes a new instance of the <see cref="T:Indexus"/> class. /// sets the default port to 48888 /// </summary> public Indexus() { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log InitializeComponent(); } #region Methods /// <summary> /// The main entry point for the process /// options: /// - Install /// 1. /install /// 2. /i /// - Uninstall /// 1. /uninstall /// 2. /u /// </summary> /// <param name="args">The args. A <see cref="T:System.String[]"/> Object.</param> public static void Main(string[] args) { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + typeof(Indexus).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log string optionalArgs = string.Empty; if (args.Length > 0) { optionalArgs = args[0]; } #region args Handling if (!string.IsNullOrEmpty(optionalArgs)) { if("/?".Equals(optionalArgs.ToLower())) { Console.WriteLine("Help Menu"); Console.ReadLine(); return; } else if("/local".Equals(optionalArgs.ToLower())) { Console.Title = "Shared Cache - Server"; Console.BackgroundColor = ConsoleColor.DarkBlue; Console.ForegroundColor = ConsoleColor.White; // running as cmd appliacation Indexus SrvIndexus = new Indexus(); SrvIndexus.StartService(); Console.ReadLine(); SrvIndexus.StopService(); return; } else if(@"/verbose".Equals(optionalArgs.ToLower())) { // Console.SetOut(this); // Console.SetIn(Console.Out); // Console.ReadLine(); return; } TransactedInstaller ti = new TransactedInstaller(); IndexusInstaller ii = new IndexusInstaller(); ti.Installers.Add(ti); string path = string.Format("/assemblypath={0}", System.Reflection.Assembly.GetExecutingAssembly().Location); string[] cmd = { path }; InstallContext context = new InstallContext(string.Empty, cmd); ti.Context = context; if ("/install".Equals(optionalArgs.ToLower()) || "/i".Equals(optionalArgs.ToLower())) { ti.Install(new Hashtable()); } else if ("/uninstall".Equals(optionalArgs.ToLower()) || "/u".Equals(optionalArgs.ToLower())) { ti.Uninstall(null); } else { StringBuilder sb = new StringBuilder(); sb.Append(@"Your provided Argument is not available." + Environment.NewLine); sb.Append(@"Use one of the following once:" + Environment.NewLine); sb.AppendFormat(@"To Install the service '{0}': '/install' or '/i'" + Environment.NewLine, @"IndeXus.Net"); sb.AppendFormat(@"To Un-Install the service'{0}': '/uninstall' or '/u'" + Environment.NewLine, @"IndeXus.Net"); Console.WriteLine(sb.ToString()); } } else { // nothing received as input argument ServiceBase[] servicesToRun; servicesToRun = new ServiceBase[] { new Indexus() }; ServiceBase.Run(servicesToRun); } #endregion args Handling } /// <summary> /// Starts the service. /// </summary> private void StartService() { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log COM.Handler.LogHandler.Info("SharedCache.com Service Starting"); this.ServiceLogicInstance.Init(); COM.Handler.LogHandler.Info("SharedCache.com Service Started"); } /// <summary> /// Stops the service. /// </summary> private void StopService() { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log COM.Handler.LogHandler.Info("SharedCache.com Service Stopping" + COM.Enums.LogCategory.ServiceCleanUpStop.ToString()); this.ServiceLogicInstance.ShutDown(); COM.Handler.LogHandler.Info("SharedCache.com Service Stopped" + COM.Enums.LogCategory.ServiceCleanUpStop.ToString()); } #endregion Methods #region override Methods /// <summary> /// When implemented in a derived class, executes when a Start command is sent /// to the service by the Service Control Manager (SCM) or when the operating /// system starts (for a service that starts automatically). Specifies actions /// to take when the service starts. /// </summary> /// <param name="args">data passed by the start command.</param> protected override void OnStart(string[] args) { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log runThread = new Thread(new ThreadStart(StartService)); runThread.Start(); } /// <summary> /// When implemented in a derived class, executes when a Stop command is sent to /// the service by the Service Control Manager (SCM). Specifies actions to take /// when a service stops running. /// </summary> protected override void OnStop() { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log this.StopService(); } /// <summary> /// When implemented in a derived class, <see cref="M:System.ServiceProcess.ServiceBase.OnContinue"></see> runs when a Continue command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service resumes normal functioning after being paused. /// </summary> protected override void OnContinue() { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log this.StopService(); this.StartService(); base.OnContinue(); } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { #region Access Log #if TRACE { COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #endregion override Methods #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { #region Access Log COM.Handler.LogHandler.Tracking( "Access Method: " + this.GetType().ToString()+ "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;" ); #endregion Access Log components = new System.ComponentModel.Container(); this.CanHandlePowerEvent = false; this.CanPauseAndContinue = true; this.CanShutdown = true; // renamed service from to SharedCache.com this.ServiceName = "SharedCache.com"; } #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! 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="ReachPlanServiceClient"/> instances.</summary> public sealed partial class ReachPlanServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ReachPlanServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ReachPlanServiceSettings"/>.</returns> public static ReachPlanServiceSettings GetDefault() => new ReachPlanServiceSettings(); /// <summary>Constructs a new <see cref="ReachPlanServiceSettings"/> object with default settings.</summary> public ReachPlanServiceSettings() { } private ReachPlanServiceSettings(ReachPlanServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListPlannableLocationsSettings = existing.ListPlannableLocationsSettings; ListPlannableProductsSettings = existing.ListPlannableProductsSettings; GenerateProductMixIdeasSettings = existing.GenerateProductMixIdeasSettings; GenerateReachForecastSettings = existing.GenerateReachForecastSettings; OnCopy(existing); } partial void OnCopy(ReachPlanServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ReachPlanServiceClient.ListPlannableLocations</c> and /// <c>ReachPlanServiceClient.ListPlannableLocationsAsync</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 ListPlannableLocationsSettings { 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>ReachPlanServiceClient.ListPlannableProducts</c> and <c>ReachPlanServiceClient.ListPlannableProductsAsync</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 ListPlannableProductsSettings { 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>ReachPlanServiceClient.GenerateProductMixIdeas</c> and /// <c>ReachPlanServiceClient.GenerateProductMixIdeasAsync</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 GenerateProductMixIdeasSettings { 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>ReachPlanServiceClient.GenerateReachForecast</c> and <c>ReachPlanServiceClient.GenerateReachForecastAsync</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 GenerateReachForecastSettings { 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="ReachPlanServiceSettings"/> object.</returns> public ReachPlanServiceSettings Clone() => new ReachPlanServiceSettings(this); } /// <summary> /// Builder class for <see cref="ReachPlanServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class ReachPlanServiceClientBuilder : gaxgrpc::ClientBuilderBase<ReachPlanServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ReachPlanServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ReachPlanServiceClientBuilder() { UseJwtAccessWithScopes = ReachPlanServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ReachPlanServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ReachPlanServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ReachPlanServiceClient Build() { ReachPlanServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ReachPlanServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ReachPlanServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ReachPlanServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ReachPlanServiceClient.Create(callInvoker, Settings); } private async stt::Task<ReachPlanServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ReachPlanServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ReachPlanServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ReachPlanServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ReachPlanServiceClient.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>ReachPlanService client wrapper, for convenient use.</summary> /// <remarks> /// Reach Plan Service gives users information about audience size that can /// be reached through advertisement on YouTube. In particular, /// GenerateReachForecast provides estimated number of people of specified /// demographics that can be reached by an ad in a given market by a campaign of /// certain duration with a defined budget. /// </remarks> public abstract partial class ReachPlanServiceClient { /// <summary> /// The default endpoint for the ReachPlanService 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 ReachPlanService scopes.</summary> /// <remarks> /// The default ReachPlanService 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="ReachPlanServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ReachPlanServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ReachPlanServiceClient"/>.</returns> public static stt::Task<ReachPlanServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ReachPlanServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ReachPlanServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ReachPlanServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ReachPlanServiceClient"/>.</returns> public static ReachPlanServiceClient Create() => new ReachPlanServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ReachPlanServiceClient"/> 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="ReachPlanServiceSettings"/>.</param> /// <returns>The created <see cref="ReachPlanServiceClient"/>.</returns> internal static ReachPlanServiceClient Create(grpccore::CallInvoker callInvoker, ReachPlanServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ReachPlanService.ReachPlanServiceClient grpcClient = new ReachPlanService.ReachPlanServiceClient(callInvoker); return new ReachPlanServiceClientImpl(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 ReachPlanService client</summary> public virtual ReachPlanService.ReachPlanServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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 ListPlannableLocationsResponse ListPlannableLocations(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, st::CancellationToken cancellationToken) => ListPlannableLocationsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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 ListPlannableProductsResponse ListPlannableProducts(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, st::CancellationToken cancellationToken) => ListPlannableProductsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v8.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListPlannableProductsResponse ListPlannableProducts(string plannableLocationId, gaxgrpc::CallSettings callSettings = null) => ListPlannableProducts(new ListPlannableProductsRequest { PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), }, callSettings); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v8.services.ReachPlanService.ListPlannableLocations]. /// </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<ListPlannableProductsResponse> ListPlannableProductsAsync(string plannableLocationId, gaxgrpc::CallSettings callSettings = null) => ListPlannableProductsAsync(new ListPlannableProductsRequest { PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), }, callSettings); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v8.services.ReachPlanService.ListPlannableLocations]. /// </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<ListPlannableProductsResponse> ListPlannableProductsAsync(string plannableLocationId, st::CancellationToken cancellationToken) => ListPlannableProductsAsync(plannableLocationId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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 GenerateProductMixIdeasResponse GenerateProductMixIdeas(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, st::CancellationToken cancellationToken) => GenerateProductMixIdeasAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v8.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual GenerateProductMixIdeasResponse GenerateProductMixIdeas(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, gaxgrpc::CallSettings callSettings = null) => GenerateProductMixIdeas(new GenerateProductMixIdeasRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), CurrencyCode = gax::GaxPreconditions.CheckNotNullOrEmpty(currencyCode, nameof(currencyCode)), BudgetMicros = budgetMicros, }, callSettings); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v8.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, gaxgrpc::CallSettings callSettings = null) => GenerateProductMixIdeasAsync(new GenerateProductMixIdeasRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), CurrencyCode = gax::GaxPreconditions.CheckNotNullOrEmpty(currencyCode, nameof(currencyCode)), BudgetMicros = budgetMicros, }, callSettings); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v8.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, st::CancellationToken cancellationToken) => GenerateProductMixIdeasAsync(customerId, plannableLocationId, currencyCode, budgetMicros, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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 GenerateReachForecastResponse GenerateReachForecast(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, st::CancellationToken cancellationToken) => GenerateReachForecastAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual GenerateReachForecastResponse GenerateReachForecast(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, gaxgrpc::CallSettings callSettings = null) => GenerateReachForecast(new GenerateReachForecastRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), CampaignDuration = gax::GaxPreconditions.CheckNotNull(campaignDuration, nameof(campaignDuration)), PlannedProducts = { gax::GaxPreconditions.CheckNotNull(plannedProducts, nameof(plannedProducts)), }, }, callSettings); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </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<GenerateReachForecastResponse> GenerateReachForecastAsync(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, gaxgrpc::CallSettings callSettings = null) => GenerateReachForecastAsync(new GenerateReachForecastRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), CampaignDuration = gax::GaxPreconditions.CheckNotNull(campaignDuration, nameof(campaignDuration)), PlannedProducts = { gax::GaxPreconditions.CheckNotNull(plannedProducts, nameof(plannedProducts)), }, }, callSettings); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </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<GenerateReachForecastResponse> GenerateReachForecastAsync(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, st::CancellationToken cancellationToken) => GenerateReachForecastAsync(customerId, campaignDuration, plannedProducts, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ReachPlanService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Reach Plan Service gives users information about audience size that can /// be reached through advertisement on YouTube. In particular, /// GenerateReachForecast provides estimated number of people of specified /// demographics that can be reached by an ad in a given market by a campaign of /// certain duration with a defined budget. /// </remarks> public sealed partial class ReachPlanServiceClientImpl : ReachPlanServiceClient { private readonly gaxgrpc::ApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse> _callListPlannableLocations; private readonly gaxgrpc::ApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse> _callListPlannableProducts; private readonly gaxgrpc::ApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse> _callGenerateProductMixIdeas; private readonly gaxgrpc::ApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse> _callGenerateReachForecast; /// <summary> /// Constructs a client wrapper for the ReachPlanService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ReachPlanServiceSettings"/> used within this client.</param> public ReachPlanServiceClientImpl(ReachPlanService.ReachPlanServiceClient grpcClient, ReachPlanServiceSettings settings) { GrpcClient = grpcClient; ReachPlanServiceSettings effectiveSettings = settings ?? ReachPlanServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListPlannableLocations = clientHelper.BuildApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse>(grpcClient.ListPlannableLocationsAsync, grpcClient.ListPlannableLocations, effectiveSettings.ListPlannableLocationsSettings); Modify_ApiCall(ref _callListPlannableLocations); Modify_ListPlannableLocationsApiCall(ref _callListPlannableLocations); _callListPlannableProducts = clientHelper.BuildApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse>(grpcClient.ListPlannableProductsAsync, grpcClient.ListPlannableProducts, effectiveSettings.ListPlannableProductsSettings); Modify_ApiCall(ref _callListPlannableProducts); Modify_ListPlannableProductsApiCall(ref _callListPlannableProducts); _callGenerateProductMixIdeas = clientHelper.BuildApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse>(grpcClient.GenerateProductMixIdeasAsync, grpcClient.GenerateProductMixIdeas, effectiveSettings.GenerateProductMixIdeasSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callGenerateProductMixIdeas); Modify_GenerateProductMixIdeasApiCall(ref _callGenerateProductMixIdeas); _callGenerateReachForecast = clientHelper.BuildApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse>(grpcClient.GenerateReachForecastAsync, grpcClient.GenerateReachForecast, effectiveSettings.GenerateReachForecastSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callGenerateReachForecast); Modify_GenerateReachForecastApiCall(ref _callGenerateReachForecast); 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_ListPlannableLocationsApiCall(ref gaxgrpc::ApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse> call); partial void Modify_ListPlannableProductsApiCall(ref gaxgrpc::ApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse> call); partial void Modify_GenerateProductMixIdeasApiCall(ref gaxgrpc::ApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse> call); partial void Modify_GenerateReachForecastApiCall(ref gaxgrpc::ApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse> call); partial void OnConstruction(ReachPlanService.ReachPlanServiceClient grpcClient, ReachPlanServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ReachPlanService client</summary> public override ReachPlanService.ReachPlanServiceClient GrpcClient { get; } partial void Modify_ListPlannableLocationsRequest(ref ListPlannableLocationsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListPlannableProductsRequest(ref ListPlannableProductsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GenerateProductMixIdeasRequest(ref GenerateProductMixIdeasRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GenerateReachForecastRequest(ref GenerateReachForecastRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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 ListPlannableLocationsResponse ListPlannableLocations(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableLocationsRequest(ref request, ref callSettings); return _callListPlannableLocations.Sync(request, callSettings); } /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableLocationsRequest(ref request, ref callSettings); return _callListPlannableLocations.Async(request, callSettings); } /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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 ListPlannableProductsResponse ListPlannableProducts(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableProductsRequest(ref request, ref callSettings); return _callListPlannableProducts.Sync(request, callSettings); } /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableProductsRequest(ref request, ref callSettings); return _callListPlannableProducts.Async(request, callSettings); } /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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 GenerateProductMixIdeasResponse GenerateProductMixIdeas(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateProductMixIdeasRequest(ref request, ref callSettings); return _callGenerateProductMixIdeas.Sync(request, callSettings); } /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateProductMixIdeasRequest(ref request, ref callSettings); return _callGenerateProductMixIdeas.Async(request, callSettings); } /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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 GenerateReachForecastResponse GenerateReachForecast(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateReachForecastRequest(ref request, ref callSettings); return _callGenerateReachForecast.Sync(request, callSettings); } /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateReachForecastRequest(ref request, ref callSettings); return _callGenerateReachForecast.Async(request, callSettings); } } }
using Halforbit.DataStores.FileStores.Serialization.Yaml.Implementation; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using Xunit; using static Halforbit.DataStores.YamlOptions; namespace Halforbit.DataStores.FileStores.Serialization.Yaml.Tests { public class YamlSerializerTests { readonly Encoding _encoding = new UTF8Encoding(false); // SERIALIZE - OPTIONS //////////////////////////////////////////////// [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = _encoding.GetBytes(@" itemId: 7e900426dbc246bcbe100d503644b830 itemName: alfa subItems: - bravo - charlie options: all createTime: 2019-01-02T03:04:05.0060007Z ".TrimStart()); var actual = await yamlSerializer.Serialize(TestItem); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeNullClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Serialize(null as Item); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeIntegerEnumValues_Success() { var yamlSerializer = new YamlSerializer($"{CamelCasePropertyNames | RemoveDefaultValues | OmitGuidDashes}"); var expected = _encoding.GetBytes(@" itemId: 7e900426dbc246bcbe100d503644b830 itemName: alfa subItems: - bravo - charlie options: 3 createTime: 2019-01-02T03:04:05.0060007Z ".TrimStart()); var actual = await yamlSerializer.Serialize(TestItem); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializePascalCasePropertyNames_Success() { var yamlSerializer = new YamlSerializer($"{CamelCaseEnumValues | RemoveDefaultValues | OmitGuidDashes }"); var expected = _encoding.GetBytes(@" ItemId: 7e900426dbc246bcbe100d503644b830 ItemName: alfa SubItems: - bravo - charlie Options: all CreateTime: 2019-01-02T03:04:05.0060007Z ".TrimStart()); var actual = await yamlSerializer.Serialize(TestItem); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeIncludeDefaultValues_Success() { var yamlSerializer = new YamlSerializer($"{CamelCaseEnumValues | CamelCasePropertyNames | OmitGuidDashes}"); var expected = _encoding.GetBytes(@" itemId: 7e900426dbc246bcbe100d503644b830 itemName: alfa defaultValue: subItems: - bravo - charlie options: all createTime: 2019-01-02T03:04:05.0060007Z ".TrimStart()); var actual = await yamlSerializer.Serialize(TestItem); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeWithGuidDashes_Success() { var yamlSerializer = new YamlSerializer($"{CamelCaseEnumValues | CamelCasePropertyNames | RemoveDefaultValues}"); var expected = _encoding.GetBytes(@" itemId: 7e900426-dbc2-46bc-be10-0d503644b830 itemName: alfa subItems: - bravo - charlie options: all createTime: 2019-01-02T03:04:05.0060007Z ".TrimStart()); var actual = await yamlSerializer.Serialize(TestItem); Assert.Equal(expected, actual); } // SERIALIZE - SIMPLE TYPES ///////////////////////////////////////////////////// [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeStringDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = _encoding.GetBytes("hello, world\r\n"); var actual = await yamlSerializer.Serialize("hello, world"); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeDateTimeDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var dateTime = new DateTime(2019, 01, 02, 03, 04, 05, 006, DateTimeKind.Utc).AddTicks(0007); var expected = _encoding.GetBytes("2019-01-02T03:04:05.0060007Z\r\n"); var actual = await yamlSerializer.Serialize(dateTime); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeNullDateTimeDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Serialize(null as DateTime?); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeNullableGuidDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var guid = new Guid("7e900426dbc246bcbe100d503644b830") as Guid?; var expected = _encoding.GetBytes("7e900426dbc246bcbe100d503644b830\r\n"); var actual = await yamlSerializer.Serialize(guid); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeNullGuidDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Serialize(null as Guid?); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeGuidWithGuidDashes_Success() { var yamlSerializer = new YamlSerializer($"{CamelCaseEnumValues | CamelCasePropertyNames | RemoveDefaultValues}"); var guid = new Guid("7e900426dbc246bcbe100d503644b830"); var expected = _encoding.GetBytes("7e900426-dbc2-46bc-be10-0d503644b830\r\n"); var actual = await yamlSerializer.Serialize(guid); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeBigInteger_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var sourceString = string.Join(string.Empty, Enumerable.Repeat("1234567890", 10)); var actual = await yamlSerializer.Serialize(BigInteger.Parse(sourceString)); Assert.Equal( _encoding.GetBytes($"{sourceString}\r\n"), actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeImmutableBigInteger_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var sourceString = string.Join(string.Empty, Enumerable.Repeat("1234567890", 10)); var source = new Immutable<BigInteger>(BigInteger.Parse(sourceString)); var expected = _encoding.GetBytes($@" property: {sourceString} ".TrimStart()); var actual = await yamlSerializer.Serialize(source); Assert.Equal(expected, actual); } // SERIALIZE - ARRAY TYPES //////////////////////////////////////////// [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeIReadOnlyListOfClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = _encoding.GetBytes(@" - itemId: 7e900426dbc246bcbe100d503644b830 itemName: alfa subItems: - bravo - charlie options: all createTime: 2019-01-02T03:04:05.0060007Z - itemId: 7e900426dbc246bcbe100d503644b830 itemName: alfa subItems: - bravo - charlie options: all createTime: 2019-01-02T03:04:05.0060007Z ".TrimStart()); var actual = await yamlSerializer.Serialize(new List<Item> { TestItem, TestItem } as IReadOnlyList<Item>); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeIReadOnlyListOfStringDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = _encoding.GetBytes(@" - alfa - bravo ".TrimStart()); var actual = await yamlSerializer.Serialize(new List<string> { "alfa", "bravo" } as IReadOnlyList<string>); Assert.Equal(expected, actual); } // SERIALIZE - JTOKEN TYPES /////////////////////////////////////////// [Fact, Trait("Type", "RunOnBuild")] public async Task SerializeJObjectDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var jObject = JObject.FromObject(new { Alfa = "Bravo", Charlie = 123 }); var expected = _encoding.GetBytes(@" Alfa: Bravo Charlie: 123 ".TrimStart()); var actual = await yamlSerializer.Serialize(jObject); Assert.Equal(expected, actual); } // DESERIALIZE //////////////////////////////////////////////////////// [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = await yamlSerializer.Serialize(TestItem); var actual = await yamlSerializer.Deserialize<Item>(serialized); Assert.Equal( JsonConvert.SerializeObject(TestItem), JsonConvert.SerializeObject(actual)); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeNullClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Deserialize<Item>(serialized); Assert.Null(actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeClassWithByteOrderMark_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = new byte[] { 0xEF, 0xBB, 0xBF } .Concat(await yamlSerializer.Serialize(TestItem)) .ToArray(); var actual = await yamlSerializer.Deserialize<Item>(serialized); Assert.Equal( JsonConvert.SerializeObject(TestItem), JsonConvert.SerializeObject(actual)); } // DESERIALIZE - SIMPLE TYPES ///////////////////////////////////////// [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeStringDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = "hello, world"; var serialized = _encoding.GetBytes("hello, world\r\n"); var actual = await yamlSerializer.Deserialize<string>(serialized); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeDateTimeDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = new DateTime(2019, 01, 02, 03, 04, 05, 006, DateTimeKind.Utc).AddTicks(0007); var serialized = await yamlSerializer.Serialize(expected); var actual = await yamlSerializer.Deserialize<DateTime>(serialized); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeGuidDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = new Guid("7e900426dbc246bcbe100d503644b830"); var serialized = await yamlSerializer.Serialize(expected); var actual = await yamlSerializer.Deserialize<Guid>(serialized); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeNullStringDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Deserialize<string>(serialized); Assert.Null(actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeNullDateTimeDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Deserialize<DateTime?>(serialized); Assert.Null(actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeNullGuidDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = await yamlSerializer.Serialize(null as Guid?); var actual = await yamlSerializer.Deserialize<Guid?>(serialized); Assert.Null(actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeBigInteger_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var sourceString = string.Join(string.Empty, Enumerable.Repeat("1234567890", 10)); var source = _encoding.GetBytes($"{sourceString}\r\n"); var actual = await yamlSerializer.Deserialize<BigInteger>(source); Assert.Equal( BigInteger.Parse(sourceString), actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeImmutableBigInteger_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var sourceString = string.Join(string.Empty, Enumerable.Repeat("1234567890", 10)); var source = _encoding.GetBytes($@" property: {sourceString} ".TrimStart()); var actual = await yamlSerializer.Deserialize<Immutable<BigInteger>>(source); Assert.Equal( sourceString, actual.Property.ToString()); } // DESERIALIZE - ARRAY TYPES ////////////////////////////////////////// [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeIReadOnlyListOfClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = new List<Item> { TestItem, TestItem } as IReadOnlyList<Item>; var serialized = await yamlSerializer.Serialize(expected); var actual = await yamlSerializer.Deserialize<IReadOnlyList<Item>>(serialized); Assert.Equal( JsonConvert.SerializeObject(expected), JsonConvert.SerializeObject(actual)); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeArrayOfClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = new[] { TestItem, TestItem }; var serialized = await yamlSerializer.Serialize(expected); var actual = await yamlSerializer.Deserialize<Item[]>(serialized); Assert.Equal( JsonConvert.SerializeObject(expected), JsonConvert.SerializeObject(actual)); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeIReadOnlyListOfStringDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = new List<string> { "alfa", "bravo" } as IReadOnlyList<string>; var serialized = await yamlSerializer.Serialize(expected); var actual = await yamlSerializer.Deserialize<IReadOnlyList<string>>(serialized); Assert.Equal(expected, actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeNullIReadOnlyListOfClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Deserialize<IReadOnlyList<Item>>(serialized); Assert.Null(actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeNullArrayOfClassDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Deserialize<Item[]>(serialized); Assert.Null(actual); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeNullIReadOnlyListOfStringDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Deserialize<IReadOnlyList<string>>(serialized); Assert.Null(actual); } // DESERIALIZE - JTOKEN TYPES ///////////////////////////////////////// [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeJObjectDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var expected = JObject.FromObject(new { alfa = "Bravo", charlie = "Delta" }); var serialized = await yamlSerializer.Serialize(expected); var actual = await yamlSerializer.Deserialize<JObject>(serialized); Assert.Equal( JsonConvert.SerializeObject(expected), JsonConvert.SerializeObject(actual)); } [Fact, Trait("Type", "RunOnBuild")] public async Task DeserializeNullJObjectDefaultOptions_Success() { var yamlSerializer = new YamlSerializer($"{Default}"); var serialized = _encoding.GetBytes("--- \r\n"); var actual = await yamlSerializer.Deserialize<JObject>(serialized); Assert.Null(actual); } // TEST HELPERS /////////////////////////////////////////////////////// Item TestItem => new Item( itemId: new Guid("7e900426dbc246bcbe100d503644b830"), itemName: "alfa", defaultValue: default, subItems: new[] { "bravo", "charlie" }, options: Options.All, createTime: new DateTime(2019, 01, 02, 03, 04, 05, 006, DateTimeKind.Utc).AddTicks(0007)); [Flags] enum Options { None = 0, Apples = 1, Oranges = 2, All = Apples | Oranges } class Item { public Item( Guid itemId, string itemName, string defaultValue, IReadOnlyList<string> subItems, Options options, DateTime createTime) { ItemId = itemId; ItemName = itemName; DefaultValue = defaultValue; SubItems = subItems; Options = options; CreateTime = createTime; } public Guid ItemId { get; } public string ItemName { get; } public string DefaultValue { get; } public IReadOnlyList<string> SubItems { get; } public Options Options { get; } public DateTime CreateTime { get; } } class Immutable<TProperty> { public Immutable(TProperty property) { Property = property; } public TProperty Property { get; } } } }
// 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.Runtime.InteropServices; using System.Threading; using Xunit; public partial class ThreadPoolBoundHandleTests { [Fact] public unsafe void SingleOperationOverSingleHandle() { const int DATA_SIZE = 2; SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"SingleOverlappedOverSingleHandle.tmp"); ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle); OverlappedContext result = new OverlappedContext(); byte[] data = new byte[DATA_SIZE]; data[0] = (byte)'A'; data[1] = (byte)'B'; NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result, data); fixed (byte* p = data) { int retval = DllImport.WriteFile(boundHandle.Handle, p, DATA_SIZE, IntPtr.Zero, overlapped); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Wait for overlapped operation to complete result.Event.WaitOne(); } boundHandle.FreeNativeOverlapped(overlapped); boundHandle.Dispose(); handle.Dispose(); Assert.Equal(0, result.ErrorCode); Assert.Equal(DATA_SIZE, result.BytesWritten); } [Fact] public unsafe void MultipleOperationsOverSingleHandle() { const int DATA_SIZE = 2; SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverSingleHandle.tmp"); ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle); OverlappedContext result1 = new OverlappedContext(); OverlappedContext result2 = new OverlappedContext(); byte[] data1 = new byte[DATA_SIZE]; data1[0] = (byte)'A'; data1[1] = (byte)'B'; byte[] data2 = new byte[DATA_SIZE]; data2[0] = (byte)'C'; data2[1] = (byte)'D'; NativeOverlapped* overlapped1 = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result1, data1); NativeOverlapped* overlapped2 = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result2, data2); fixed (byte* p1 = data1, p2 = data2) { int retval = DllImport.WriteFile(boundHandle.Handle, p1, DATA_SIZE, IntPtr.Zero, overlapped1); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Start the offset after the above write, so that it doesn't overwrite the previous write overlapped2->OffsetLow = DATA_SIZE; retval = DllImport.WriteFile(boundHandle.Handle, p2, DATA_SIZE, IntPtr.Zero, overlapped2); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Wait for overlapped operations to complete WaitHandle.WaitAll(new WaitHandle[] { result1.Event, result2.Event }); } boundHandle.FreeNativeOverlapped(overlapped1); boundHandle.FreeNativeOverlapped(overlapped2); boundHandle.Dispose(); handle.Dispose(); Assert.Equal(0, result1.ErrorCode); Assert.Equal(0, result2.ErrorCode); Assert.Equal(DATA_SIZE, result1.BytesWritten); Assert.Equal(DATA_SIZE, result2.BytesWritten); } [Fact] public unsafe void MultipleOperationsOverMultipleHandles() { const int DATA_SIZE = 2; SafeHandle handle1 = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverMultipleHandle1.tmp"); SafeHandle handle2 = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverMultipleHandle2.tmp"); ThreadPoolBoundHandle boundHandle1 = ThreadPoolBoundHandle.BindHandle(handle1); ThreadPoolBoundHandle boundHandle2 = ThreadPoolBoundHandle.BindHandle(handle2); OverlappedContext result1 = new OverlappedContext(); OverlappedContext result2 = new OverlappedContext(); byte[] data1 = new byte[DATA_SIZE]; data1[0] = (byte)'A'; data1[1] = (byte)'B'; byte[] data2 = new byte[DATA_SIZE]; data2[0] = (byte)'C'; data2[1] = (byte)'D'; PreAllocatedOverlapped preAlloc1 = new PreAllocatedOverlapped(OnOverlappedOperationCompleted, result1, data1); PreAllocatedOverlapped preAlloc2 = new PreAllocatedOverlapped(OnOverlappedOperationCompleted, result2, data2); for (int i = 0; i < 10; i++) { NativeOverlapped* overlapped1 = boundHandle1.AllocateNativeOverlapped(preAlloc1); NativeOverlapped* overlapped2 = boundHandle2.AllocateNativeOverlapped(preAlloc2); fixed (byte* p1 = data1, p2 = data2) { int retval = DllImport.WriteFile(boundHandle1.Handle, p1, DATA_SIZE, IntPtr.Zero, overlapped1); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } retval = DllImport.WriteFile(boundHandle2.Handle, p2, DATA_SIZE, IntPtr.Zero, overlapped2); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Wait for overlapped operations to complete WaitHandle.WaitAll(new WaitHandle[] { result1.Event, result2.Event }); } boundHandle1.FreeNativeOverlapped(overlapped1); boundHandle2.FreeNativeOverlapped(overlapped2); result1.Event.Reset(); result2.Event.Reset(); Assert.Equal(0, result1.ErrorCode); Assert.Equal(0, result2.ErrorCode); Assert.Equal(DATA_SIZE, result1.BytesWritten); Assert.Equal(DATA_SIZE, result2.BytesWritten); } boundHandle1.Dispose(); boundHandle2.Dispose(); preAlloc1.Dispose(); preAlloc2.Dispose(); handle1.Dispose(); handle2.Dispose(); } [Fact] public unsafe void FlowsAsyncLocalsToCallback() { // Makes sure that we flow async locals to callback const int DATA_SIZE = 2; SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"AsyncLocal.tmp"); ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle); OverlappedContext context = new OverlappedContext(); byte[] data = new byte[DATA_SIZE]; AsyncLocal<int> asyncLocal = new AsyncLocal<int>(); asyncLocal.Value = 10; int? result = null; IOCompletionCallback callback = (_, __, ___) => { result = asyncLocal.Value; OnOverlappedOperationCompleted(_, __, ___); }; NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(callback, context, data); fixed (byte* p = data) { int retval = DllImport.WriteFile(boundHandle.Handle, p, DATA_SIZE, IntPtr.Zero, overlapped); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Wait for overlapped operation to complete context.Event.WaitOne(); } boundHandle.FreeNativeOverlapped(overlapped); boundHandle.Dispose(); handle.Dispose(); Assert.Equal(10, result); } private static unsafe void OnOverlappedOperationCompleted(uint errorCode, uint numBytes, NativeOverlapped* overlapped) { OverlappedContext result = (OverlappedContext)ThreadPoolBoundHandle.GetNativeOverlappedState(overlapped); result.ErrorCode = (int)errorCode; result.BytesWritten = (int)numBytes; // Signal original thread to indicate overlapped completed result.Event.Set(); } private class OverlappedContext { public readonly ManualResetEvent Event = new ManualResetEvent(false); public int ErrorCode; public int BytesWritten; } }
using System; namespace SharpVectors.Polynomials { /// <summary> /// Summary description for Polynomial. /// </summary> /// <developer>kevin@kevlindev.com</developer> /// <completed>100</completed> public class Polynomial { #region fields private double[] coefficients; private double s; #endregion #region properties public int Degree { get { return this.coefficients.Length - 1; } } public double this[int index] { get { return this.coefficients[index]; } } #endregion #region constructors /// <summary> /// Polynomial constuctor /// </summary> /// <param name="coefficients"></param> public Polynomial(params double[] coefficients) { int end = 0; double TOLERANCE = 1e-9; for ( end = coefficients.Length; end > 0; end-- ) { if ( Math.Abs(coefficients[end-1]) > TOLERANCE ) break; } if ( end > 0 ) { this.coefficients = new double[coefficients.Length - (coefficients.Length - end)]; for ( int i = 0; i < end; i++ ) { this.coefficients[i] = coefficients[i]; } } else { this.coefficients = new double[0]; } } public Polynomial(Polynomial that) { this.coefficients = that.coefficients; } #endregion #region class methods /// <summary> /// Interpolate - adapted from "Numerical Recipes in C" /// </summary> /// <param name="xs"></param> /// <param name="ys"></param> /// <param name="n"></param> /// <param name="offset"></param> /// <param name="x"></param> /// <returns></returns> static public ValueWithError Interpolate(double[] xs, double[] ys, int n, int offset, double x) { double y; double dy = 0.0; double[] c = new double[n]; double[] d = new double[n]; int ns = 0; double diff = Math.Abs(x - xs[offset]); for ( int i = 0; i < n; i++ ) { double dift = Math.Abs(x - xs[offset+i]); if ( dift < diff ) { ns = i; diff = dift; } c[i] = d[i] = ys[offset+i]; } y = ys[offset+ns]; ns--; for ( int m = 1; m < n; m++ ) { for ( int i = 0; i < n-m; i++ ) { double ho = xs[offset+i] - x; double hp = xs[offset+i+m] - x; double w = c[i+1]-d[i]; double den = ho - hp; if ( den == 0.0 ) return new ValueWithError(0,0); den = w / den; d[i] = hp*den; c[i] = ho*den; } dy = (2*(ns+1) < (n-m)) ? c[ns+1] : d[ns--]; y += dy; } return new ValueWithError(y, dy); } #endregion #region protected methods /// <summary> /// trapezoid - adapted from "Numerical Recipes in C" /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <param name="n"></param> /// <returns></returns> protected double trapezoid(double min, double max, int n) { double range = max - min; if ( n == 1 ) { this.s = 0.5*range*(this.Evaluate(min)+this.Evaluate(max)); } else { int it = 1 << (n-2); double delta = range / it; double x = min + 0.5*delta; double sum = 0.0; for ( int i = 0; i < it; i++ ) { sum += this.Evaluate(x); x += delta; } this.s = 0.5*(this.s + range*sum/it); } return this.s; } #endregion #region public methods /// <summary> /// Evaluate /// </summary> /// <param name="t"></param> /// <returns></returns> public virtual double Evaluate(double t) { double result = 0.0; for ( int i = this.coefficients.Length - 1; i >= 0; i-- ) { result = result * t + this.coefficients[i]; } return result; } /// <summary> /// Simspon - adapted from "Numerical Recipes in C" /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public double Simpson(double min, double max) { double s = 0.0; double st = 0.0; double os = 0.0; double ost = 0.0; int MAX = 20; double TOLERANCE = 1e-7; for ( int j = 1; j <= MAX; j++ ) { st = this.trapezoid(min, max, j); s = (4.0 * st - ost) / 3.0; if ( Math.Abs(s - os) < TOLERANCE*Math.Abs(os)) break; os = s; ost = st; } return s; } /// <summary> /// Romberg - adapted from "Numerical Recipes in C" /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public double Romberg(double min, double max) { int MAX = 20; double TOLERANCE = 1e-7; int K = 4; double[] s = new double[MAX+1]; double[] h = new double[MAX+1]; ValueWithError result = new ValueWithError(0,0); h[0] = 1.0; for ( int j = 1; j <= MAX; j++ ) { s[j-1] = trapezoid(min, max, j); if ( j >= K ) { result = Polynomial.Interpolate(h, s, K, j-K, 0.0); if ( Math.Abs(result.Error) < TOLERANCE*result.Value ) break; } s[j] = s[j-1]; h[j] = 0.25 * h[j-1]; } return result.Value; } #endregion #region unit tests #endregion } /// <summary> /// Stucture used to return values with associated error tolerances /// </summary> public struct ValueWithError { public double Value; public double Error; public ValueWithError(double value, double error) { this.Value = value; this.Error = error; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if FEATURE_SYSTEM_CONFIGURATION using System.Configuration; using Microsoft.Win32; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Shared; using ToolsetConfigurationSection = Microsoft.Build.Evaluation.ToolsetConfigurationSection; using Xunit; using System; using System.Collections.Generic; namespace Microsoft.Build.UnitTests.Definition { /// <summary> /// Unit tests for ToolsetConfigurationReader class /// </summary> public class ToolsetConfigurationReaderTests : IDisposable { private static string s_msbuildToolsets = "msbuildToolsets"; public void Dispose() { ToolsetConfigurationReaderTestHelper.CleanUp(); } #region "msbuildToolsets element tests" /// <summary> /// msbuildToolsets element is empty /// </summary> [Fact] public void MSBuildToolsetsTest_EmptyElement() { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets /> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection; Assert.Null(msbuildToolsetSection.MSBuildOverrideTasksPath); Assert.NotNull(msbuildToolsetSection); Assert.Null(msbuildToolsetSection.Default); Assert.NotNull(msbuildToolsetSection.Toolsets); Assert.Empty(msbuildToolsetSection.Toolsets); } /// <summary> /// tests if ToolsetConfigurationReaderTests is successfully initialized from the config file /// </summary> [Fact] public void MSBuildToolsetsTest_Basic() { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0""> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ConfigurationSection section = config.GetSection(s_msbuildToolsets); ToolsetConfigurationSection msbuildToolsetSection = section as ToolsetConfigurationSection; Assert.Null(msbuildToolsetSection.MSBuildOverrideTasksPath); Assert.Equal("2.0", msbuildToolsetSection.Default); Assert.Single(msbuildToolsetSection.Toolsets); Assert.Equal("2.0", msbuildToolsetSection.Toolsets.GetElement(0).toolsVersion); Assert.Single(msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements); Assert.Equal( @"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\", msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value); Assert.Empty(msbuildToolsetSection.Toolsets.GetElement(0).AllProjectImportSearchPaths); } /// <summary> /// Tests if ToolsetConfigurationReaderTests is successfully initialized from the config file when msbuildOVerrideTasksPath is set. /// Also verify the msbuildOverrideTasksPath is properly read in. /// </summary> [Fact] public void MSBuildToolsetsTest_Basic2() { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0"" msbuildOverrideTasksPath=""c:\foo""> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ConfigurationSection section = config.GetSection(s_msbuildToolsets); ToolsetConfigurationSection msbuildToolsetSection = section as ToolsetConfigurationSection; Assert.Equal("c:\\foo", msbuildToolsetSection.MSBuildOverrideTasksPath); } /// <summary> /// Tests if ToolsetConfigurationReaderTests is successfully initialized from the config file and that msbuildOVerrideTasksPath /// is correctly read in when the value is empty. /// </summary> [Fact] public void MSBuildToolsetsTest_Basic3() { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0"" msbuildOverrideTasksPath=""""> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ConfigurationSection section = config.GetSection(s_msbuildToolsets); ToolsetConfigurationSection msbuildToolsetSection = section as ToolsetConfigurationSection; Assert.Null(msbuildToolsetSection.MSBuildOverrideTasksPath); } /// <summary> /// tests if ToolsetConfigurationReaderTests is successfully initialized from the config file /// </summary> [Fact] public void MSBuildToolsetsTest_BasicWithOtherConfigEntries() { // NOTE: for some reason, <configSections> MUST be the first element under <configuration> // for the API to read it. The docs don't make this clear. ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <startup> <supportedRuntime imageVersion=""v2.0.60510"" version=""v2.0.x86chk""/> <requiredRuntime imageVersion=""v2.0.60510"" version=""v2.0.x86chk"" safemode=""true""/> </startup> <msbuildToolsets default=""2.0""> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> </toolset> </msbuildToolsets> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <dependentAssembly> <assemblyIdentity name=""Microsoft.Build.Framework"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral""/> <bindingRedirect oldVersion=""0.0.0.0-99.9.9.9"" newVersion=""2.0.0.0""/> </dependentAssembly> </assemblyBinding> </runtime> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection; Assert.Equal("2.0", msbuildToolsetSection.Default); Assert.Single(msbuildToolsetSection.Toolsets); Assert.Equal("2.0", msbuildToolsetSection.Toolsets.GetElement(0).toolsVersion); Assert.Single(msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements); Assert.Equal( @"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\", msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value); Assert.Empty(msbuildToolsetSection.Toolsets.GetElement(0).AllProjectImportSearchPaths); } #endregion #region "toolsVersion element tests" #region "Invalid cases (exception is expected to be thrown)" /// <summary> /// name attribute is missing from toolset element /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ToolsVersionTest_NameNotSpecified() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0""> <toolset> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> </toolset> <toolset toolsVersion=""4.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } /// <summary> /// More than 1 toolset element with the same name /// </summary> [Fact] public void ToolsVersionTest_MultipleElementsWithSameName() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0""> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> </toolset> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } /// <summary> /// empty toolset element /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ToolsVersionTest_EmptyElement() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0""> <toolset /> <toolset toolsVersion=""4.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } #endregion #region "Valid cases (No exception expected)" /// <summary> /// only 1 toolset is specified /// </summary> [Fact] public void ToolsVersionTest_SingleElement() { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""4.0""> <toolset toolsVersion=""4.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection; Assert.Equal("4.0", msbuildToolsetSection.Default); Assert.Single(msbuildToolsetSection.Toolsets); Assert.Equal("4.0", msbuildToolsetSection.Toolsets.GetElement(0).toolsVersion); Assert.Single(msbuildToolsetSection.Toolsets.GetElement("4.0").PropertyElements); Assert.Equal( @"D:\windows\Microsoft.NET\Framework\v3.5.x86ret\", msbuildToolsetSection.Toolsets.GetElement("4.0").PropertyElements.GetElement("MSBuildBinPath").Value); } #endregion #endregion #region "Property" #region "Invalid cases (exception is expected to be thrown)" /// <summary> /// name attribute is missing /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void PropertyTest_NameNotSpecified() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""4.0""> <toolset toolsVersion=""4.0""> <property value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } /// <summary> /// value attribute is missing /// </summary> [Fact] public void PropertyTest_ValueNotSpecified() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""4.0""> <toolset name=""4.0""> <property name=""MSBuildBinPath"" /> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } /// <summary> /// more than 1 property element with the same name /// </summary> [Fact] public void PropertyTest_MultipleElementsWithSameName() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""4.0""> <toolset ToolsVersion=""msbuilddefaulttoolsversion""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } /// <summary> /// property element is an empty element /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void PropertyTest_EmptyElement() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""4.0""> <toolset toolsVersion=""4.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> <property /> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } #endregion #region "Valid cases" /// <summary> /// more than 1 property element specified /// </summary> [Fact] public void PropertyTest_MultipleElement() { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0""> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> <property name=""SomeOtherPropertyName"" value=""SomeOtherPropertyValue""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection; Assert.Equal("2.0", msbuildToolsetSection.Default); Assert.Single(msbuildToolsetSection.Toolsets); Assert.Equal(2, msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.Count); Assert.Equal( @"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\", msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value); Assert.Equal( @"SomeOtherPropertyValue", msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("SomeOtherPropertyName").Value); } /// <summary> /// tests GetElement(string name) function in propertycollection class /// </summary> [Fact] public void PropertyTest_GetValueByName() { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0""> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> <property name=""SomeOtherPropertyName"" value=""SomeOtherPropertyValue""/> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection; // Verifications Assert.Equal("2.0", msbuildToolsetSection.Default); Assert.Single(msbuildToolsetSection.Toolsets); Assert.Equal(2, msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.Count); Assert.Equal(@"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\", msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value); Assert.Equal(@"SomeOtherPropertyValue", msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("SomeOtherPropertyName").Value); } #endregion #endregion #region Extensions Paths /// <summary> /// Tests multiple extensions paths from the config file, specified for multiple OSes /// </summary> [Fact] public void ExtensionPathsTest_Basic1() { // NOTE: for some reason, <configSections> MUST be the first element under <configuration> // for the API to read it. The docs don't make this clear. ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""2.0""> <toolset toolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> <property name=""MSBuildToolsPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/> <projectImportSearchPaths> <searchPaths os=""windows""> <property name=""MSBuildExtensionsPath"" value=""c:\foo""/> <property name=""MSBuildExtensionsPath64"" value=""c:\foo64;c:\bar64""/> </searchPaths> <searchPaths os=""osx""> <property name=""MSBuildExtensionsPath"" value=""/tmp/foo""/> <property name=""MSBuildExtensionsPath32"" value=""/tmp/foo32;/tmp/bar32""/> </searchPaths> <searchPaths os=""unix""> <property name=""MSBuildExtensionsPath"" value=""/tmp/bar""/> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection; Assert.Equal("2.0", msbuildToolsetSection.Default); Assert.Single(msbuildToolsetSection.Toolsets); Assert.Equal("2.0", msbuildToolsetSection.Toolsets.GetElement(0).toolsVersion); Assert.Equal(2, msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.Count); Assert.Equal( @"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\", msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value); Assert.Equal(3, msbuildToolsetSection.Toolsets.GetElement(0).AllProjectImportSearchPaths.Count); var allPaths = msbuildToolsetSection.Toolsets.GetElement(0).AllProjectImportSearchPaths; Assert.Equal("windows", allPaths.GetElement(0).OS); Assert.Equal(2, allPaths.GetElement(0).PropertyElements.Count); Assert.Equal(@"c:\foo", allPaths.GetElement(0).PropertyElements.GetElement("MSBuildExtensionsPath").Value); Assert.Equal(@"c:\foo64;c:\bar64", allPaths.GetElement(0).PropertyElements.GetElement("MSBuildExtensionsPath64").Value); Assert.Equal("osx", allPaths.GetElement(1).OS); Assert.Equal(2, allPaths.GetElement(1).PropertyElements.Count); Assert.Equal(@"/tmp/foo", allPaths.GetElement(1).PropertyElements.GetElement("MSBuildExtensionsPath").Value); Assert.Equal(@"/tmp/foo32;/tmp/bar32", allPaths.GetElement(1).PropertyElements.GetElement("MSBuildExtensionsPath32").Value); Assert.Equal("unix", allPaths.GetElement(2).OS); Assert.Single(allPaths.GetElement(2).PropertyElements); Assert.Equal( @"/tmp/bar", allPaths.GetElement(2).PropertyElements.GetElement("MSBuildExtensionsPath").Value); var reader = GetStandardConfigurationReader(); Dictionary<string, Toolset> toolsets = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); reader.ReadToolsets(toolsets, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), true, out string msbuildOverrideTasksPath, out string defaultOverrideToolsVersion); Dictionary<string, ProjectImportPathMatch> pathsTable = toolsets["2.0"].ImportPropertySearchPathsTable; if (NativeMethodsShared.IsWindows) { CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"c:\\foo"}); CheckPathsTable(pathsTable, "MSBuildExtensionsPath64", new string[] {"c:\\foo64", "c:\\bar64"}); } else if (NativeMethodsShared.IsOSX) { CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"/tmp/foo"}); CheckPathsTable(pathsTable, "MSBuildExtensionsPath32", new string[] {"/tmp/foo32", "/tmp/bar32"}); } else { CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"/tmp/bar"}); } } private void CheckPathsTable(Dictionary<string, ProjectImportPathMatch> pathsTable, string kind, string[] expectedPaths) { Assert.True(pathsTable.ContainsKey(kind)); var paths = pathsTable[kind]; Assert.Equal(paths.SearchPaths.Count, expectedPaths.Length); for (int i = 0; i < paths.SearchPaths.Count; i ++) { Assert.Equal(paths.SearchPaths[i], expectedPaths[i]); } } /// <summary> /// more than 1 searchPaths elements with the same OS /// </summary> [Fact] public void ExtensionsPathsTest_MultipleElementsWithSameOS() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""4.0""> <toolset ToolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/> <projectImportSearchPaths> <searchPaths os=""windows""> <property name=""MSBuildExtensionsPath"" value=""c:\foo""/> </searchPaths> <searchPaths os=""windows""> <property name=""MSBuildExtensionsPath"" value=""c:\bar""/> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } /// <summary> /// more than value is element found for a the same extensions path property name+os /// </summary> [Fact] public void ExtensionsPathsTest_MultipleElementsWithSamePropertyNameForSameOS() { Assert.Throws<ConfigurationErrorsException>(() => { ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""4.0""> <toolset ToolsVersion=""2.0""> <property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/> <projectImportSearchPaths> <searchPaths os=""windows""> <property name=""MSBuildExtensionsPath"" value=""c:\foo""/> <property name=""MSBuildExtensionsPath"" value=""c:\bar""/> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>")); Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); } ); } private ToolsetConfigurationReader GetStandardConfigurationReader() { return new ToolsetConfigurationReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary<ProjectPropertyInstance>(), ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest); } #endregion } } #endif
using System.Runtime.CompilerServices; using Svelto.DataStructures; using Svelto.DataStructures.Native; using Svelto.ECS.Internal; namespace Svelto.ECS { public readonly ref struct EntityCollection<T> where T : struct, IEntityComponent { static readonly bool IsUnmanaged = TypeSafeDictionary<T>.isUnmanaged; public EntityCollection(IBuffer<T> buffer, uint count) : this() { DBC.ECS.Check.Require(count == 0 || buffer.isValid, "Buffer is found in impossible state"); if (IsUnmanaged) _nativedBuffer = (NB<T>) buffer; else _managedBuffer = (MB<T>) buffer; _count = count; } public uint count => _count; internal readonly MB<T> _managedBuffer; internal readonly NB<T> _nativedBuffer; readonly uint _count; } public readonly ref struct EntityCollection<T1, T2> where T1 : struct, IEntityComponent where T2 : struct, IEntityComponent { internal EntityCollection(in EntityCollection<T1> array1, in EntityCollection<T2> array2) { _array1 = array1; _array2 = array2; } public uint count => _array1.count; internal EntityCollection<T2> buffer2 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array2; } internal EntityCollection<T1> buffer1 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array1; } readonly EntityCollection<T1> _array1; readonly EntityCollection<T2> _array2; } public readonly ref struct EntityCollection<T1, T2, T3> where T3 : struct, IEntityComponent where T2 : struct, IEntityComponent where T1 : struct, IEntityComponent { internal EntityCollection (in EntityCollection<T1> array1, in EntityCollection<T2> array2, in EntityCollection<T3> array3) { _array1 = array1; _array2 = array2; _array3 = array3; } internal EntityCollection<T1> buffer1 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array1; } internal EntityCollection<T2> buffer2 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array2; } internal EntityCollection<T3> buffer3 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array3; } internal uint count => buffer1.count; readonly EntityCollection<T1> _array1; readonly EntityCollection<T2> _array2; readonly EntityCollection<T3> _array3; } public readonly ref struct EntityCollection<T1, T2, T3, T4> where T1 : struct, IEntityComponent where T2 : struct, IEntityComponent where T3 : struct, IEntityComponent where T4 : struct, IEntityComponent { internal EntityCollection (in EntityCollection<T1> array1, in EntityCollection<T2> array2, in EntityCollection<T3> array3 , in EntityCollection<T4> array4) { _array1 = array1; _array2 = array2; _array3 = array3; _array4 = array4; } internal EntityCollection<T1> buffer1 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array1; } internal EntityCollection<T2> buffer2 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array2; } internal EntityCollection<T3> buffer3 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array3; } internal EntityCollection<T4> buffer4 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array4; } internal uint count => _array1.count; readonly EntityCollection<T1> _array1; readonly EntityCollection<T2> _array2; readonly EntityCollection<T3> _array3; readonly EntityCollection<T4> _array4; } public readonly struct BT<BufferT1, BufferT2, BufferT3, BufferT4> { public readonly BufferT1 buffer1; public readonly BufferT2 buffer2; public readonly BufferT3 buffer3; public readonly BufferT4 buffer4; public readonly int count; public BT(BufferT1 bufferT1, BufferT2 bufferT2, BufferT3 bufferT3, BufferT4 bufferT4, uint count) : this() { this.buffer1 = bufferT1; this.buffer2 = bufferT2; this.buffer3 = bufferT3; this.buffer4 = bufferT4; this.count = (int) count; } } public readonly struct BT<BufferT1, BufferT2, BufferT3> { public readonly BufferT1 buffer1; public readonly BufferT2 buffer2; public readonly BufferT3 buffer3; public readonly int count; public BT(BufferT1 bufferT1, BufferT2 bufferT2, BufferT3 bufferT3, uint count) : this() { this.buffer1 = bufferT1; this.buffer2 = bufferT2; this.buffer3 = bufferT3; this.count = (int) count; } public void Deconstruct(out BufferT1 bufferT1, out BufferT2 bufferT2, out BufferT3 bufferT3, out int count) { bufferT1 = buffer1; bufferT2 = buffer2; bufferT3 = buffer3; count = this.count; } } public readonly struct BT<BufferT1> { public readonly BufferT1 buffer; public readonly int count; public BT(BufferT1 bufferT1, uint count) : this() { this.buffer = bufferT1; this.count = (int) count; } public void Deconstruct(out BufferT1 bufferT1, out int count) { bufferT1 = buffer; count = this.count; } public static implicit operator BufferT1(BT<BufferT1> t) => t.buffer; } public readonly struct BT<BufferT1, BufferT2> { public readonly BufferT1 buffer1; public readonly BufferT2 buffer2; public readonly int count; public BT(BufferT1 bufferT1, BufferT2 bufferT2, uint count) : this() { this.buffer1 = bufferT1; this.buffer2 = bufferT2; this.count = (int) count; } public void Deconstruct(out BufferT1 bufferT1, out BufferT2 bufferT2, out int count) { bufferT1 = buffer1; bufferT2 = buffer2; count = this.count; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents an expression that applies a delegate or lambda expression to a list of argument expressions. /// </summary> [DebuggerTypeProxy(typeof(InvocationExpressionProxy))] public class InvocationExpression : Expression, IArgumentProvider { internal InvocationExpression(Expression expression, Type returnType) { Expression = expression; Type = returnType; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get; } /// <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 => ExpressionType.Invoke; /// <summary> /// Gets the delegate or lambda expression to be applied. /// </summary> public Expression Expression { get; } /// <summary> /// Gets the arguments that the delegate or lambda expression is applied to. /// </summary> public ReadOnlyCollection<Expression> Arguments => GetOrMakeArguments(); /// <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> /// <param name="arguments">The <see cref="Arguments"/> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public InvocationExpression Update(Expression expression, IEnumerable<Expression> arguments) { if (expression == Expression & arguments != null) { if (ExpressionUtils.SameElements(ref arguments, Arguments)) { return this; } } return Invoke(expression, arguments); } [ExcludeFromCodeCoverage] // Unreachable internal virtual ReadOnlyCollection<Expression> GetOrMakeArguments() { throw ContractUtils.Unreachable; } /// <summary> /// Gets the argument expression with the specified <paramref name="index"/>. /// </summary> /// <param name="index">The index of the argument expression to get.</param> /// <returns>The expression representing the argument at the specified <paramref name="index"/>.</returns> [ExcludeFromCodeCoverage] // Unreachable public virtual Expression GetArgument(int index) { throw ContractUtils.Unreachable; } /// <summary> /// Gets the number of argument expressions of the node. /// </summary> [ExcludeFromCodeCoverage] // Unreachable public virtual int ArgumentCount { get { throw ContractUtils.Unreachable; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitInvocation(this); } [ExcludeFromCodeCoverage] // Unreachable internal virtual InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { throw ContractUtils.Unreachable; } internal LambdaExpression LambdaOperand { get { return (Expression.NodeType == ExpressionType.Quote) ? (LambdaExpression)((UnaryExpression)Expression).Operand : (Expression as LambdaExpression); } } } #region Specialized Subclasses internal sealed class InvocationExpressionN : InvocationExpression { private IReadOnlyList<Expression> _arguments; public InvocationExpressionN(Expression lambda, IReadOnlyList<Expression> arguments, Type returnType) : base(lambda, returnType) { _arguments = arguments; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ExpressionUtils.ReturnReadOnly(ref _arguments); } public override Expression GetArgument(int index) => _arguments[index]; public override int ArgumentCount => _arguments.Count; internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == _arguments.Count); return Expression.Invoke(lambda, arguments ?? _arguments); } } internal sealed class InvocationExpression0 : InvocationExpression { public InvocationExpression0(Expression lambda, Type returnType) : base(lambda, returnType) { } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return EmptyReadOnlyCollection<Expression>.Instance; } public override Expression GetArgument(int index) { throw new ArgumentOutOfRangeException(nameof(index)); } public override int ArgumentCount => 0; internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 0); return Expression.Invoke(lambda); } } internal sealed class InvocationExpression1 : InvocationExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider public InvocationExpression1(Expression lambda, Type returnType, Expression arg0) : base(lambda, returnType) { _arg0 = arg0; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ExpressionUtils.ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), _ => throw new ArgumentOutOfRangeException(nameof(index)), }; public override int ArgumentCount => 1; internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 1); if (arguments != null) { return Expression.Invoke(lambda, arguments[0]); } return Expression.Invoke(lambda, ExpressionUtils.ReturnObject<Expression>(_arg0)); } } internal sealed class InvocationExpression2 : InvocationExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd argument public InvocationExpression2(Expression lambda, Type returnType, Expression arg0, Expression arg1) : base(lambda, returnType) { _arg0 = arg0; _arg1 = arg1; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ExpressionUtils.ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), 1 => _arg1, _ => throw new ArgumentOutOfRangeException(nameof(index)), }; public override int ArgumentCount => 2; internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 2); if (arguments != null) { return Expression.Invoke(lambda, arguments[0], arguments[1]); } return Expression.Invoke(lambda, ExpressionUtils.ReturnObject<Expression>(_arg0), _arg1); } } internal sealed class InvocationExpression3 : InvocationExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd argument private readonly Expression _arg2; // storage for the 3rd argument public InvocationExpression3(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2) : base(lambda, returnType) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ExpressionUtils.ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), 1 => _arg1, 2 => _arg2, _ => throw new ArgumentOutOfRangeException(nameof(index)), }; public override int ArgumentCount => 3; internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 3); if (arguments != null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2]); } return Expression.Invoke(lambda, ExpressionUtils.ReturnObject<Expression>(_arg0), _arg1, _arg2); } } internal sealed class InvocationExpression4 : InvocationExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd argument private readonly Expression _arg2; // storage for the 3rd argument private readonly Expression _arg3; // storage for the 4th argument public InvocationExpression4(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3) : base(lambda, returnType) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ExpressionUtils.ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), 1 => _arg1, 2 => _arg2, 3 => _arg3, _ => throw new ArgumentOutOfRangeException(nameof(index)), }; public override int ArgumentCount => 4; internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 4); if (arguments != null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3]); } return Expression.Invoke(lambda, ExpressionUtils.ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3); } } internal sealed class InvocationExpression5 : InvocationExpression { private object _arg0; // storage for the 1st argument or a read-only collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd argument private readonly Expression _arg2; // storage for the 3rd argument private readonly Expression _arg3; // storage for the 4th argument private readonly Expression _arg4; // storage for the 5th argument public InvocationExpression5(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) : base(lambda, returnType) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ExpressionUtils.ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) => index switch { 0 => ExpressionUtils.ReturnObject<Expression>(_arg0), 1 => _arg1, 2 => _arg2, 3 => _arg3, 4 => _arg4, _ => throw new ArgumentOutOfRangeException(nameof(index)), }; public override int ArgumentCount => 5; internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 5); if (arguments != null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]); } return Expression.Invoke(lambda, ExpressionUtils.ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3, _arg4); } } #endregion public partial class Expression { /// <summary> /// Creates an <see cref="InvocationExpression"/> that /// applies a delegate or lambda expression with no arguments. /// </summary> /// <returns> /// An <see cref="InvocationExpression"/> that /// applies the specified delegate or lambda expression. /// </returns> /// <param name="expression"> /// An <see cref="Expression"/> that represents the delegate /// or lambda expression to be applied. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="expression"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="expression"/>.Type does not represent a delegate type or an <see cref="Expression{TDelegate}"/>.</exception> /// <exception cref="InvalidOperationException"> /// The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression"/>.</exception> internal static InvocationExpression Invoke(Expression expression) { // COMPAT: This method is marked as non-public to avoid a gap between a 0-ary and 2-ary overload (see remark for the unary case below). ExpressionUtils.RequiresCanRead(expression, nameof(expression)); MethodInfo method = GetInvokeMethod(expression); ParameterInfo[] pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 0, pis); return new InvocationExpression0(expression, method.ReturnType); } /// <summary> /// Creates an <see cref="InvocationExpression"/> that /// applies a delegate or lambda expression to one argument expression. /// </summary> /// <returns> /// An <see cref="InvocationExpression"/> that /// applies the specified delegate or lambda expression to the provided arguments. /// </returns> /// <param name="expression"> /// An <see cref="Expression"/> that represents the delegate /// or lambda expression to be applied. /// </param> /// <param name="arg0"> /// The <see cref="Expression"/> that represents the first argument. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="expression"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="expression"/>.Type does not represent a delegate type or an <see cref="Expression{TDelegate}"/>.-or-The <see cref="Expression.Type"/> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression"/>.</exception> /// <exception cref="InvalidOperationException"> /// The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression"/>.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0) { // COMPAT: This method is marked as non-public to ensure compile-time compatibility for Expression.Invoke(e, null). ExpressionUtils.RequiresCanRead(expression, nameof(expression)); MethodInfo method = GetInvokeMethod(expression); ParameterInfo[] pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 1, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0], nameof(expression), nameof(arg0)); return new InvocationExpression1(expression, method.ReturnType, arg0); } /// <summary> /// Creates an <see cref="InvocationExpression"/> that /// applies a delegate or lambda expression to two argument expressions. /// </summary> /// <returns> /// An <see cref="InvocationExpression"/> that /// applies the specified delegate or lambda expression to the provided arguments. /// </returns> /// <param name="expression"> /// An <see cref="Expression"/> that represents the delegate /// or lambda expression to be applied. /// </param> /// <param name="arg0"> /// The <see cref="Expression"/> that represents the first argument. /// </param> /// <param name="arg1"> /// The <see cref="Expression"/> that represents the second argument. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="expression"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="expression"/>.Type does not represent a delegate type or an <see cref="Expression{TDelegate}"/>.-or-The <see cref="Expression.Type"/> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression"/>.</exception> /// <exception cref="InvalidOperationException"> /// The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression"/>.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1) { // NB: This method is marked as non-public to avoid public API additions at this point. ExpressionUtils.RequiresCanRead(expression, nameof(expression)); MethodInfo method = GetInvokeMethod(expression); ParameterInfo[] pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 2, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0], nameof(expression), nameof(arg0)); arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1], nameof(expression), nameof(arg1)); return new InvocationExpression2(expression, method.ReturnType, arg0, arg1); } /// <summary> /// Creates an <see cref="InvocationExpression"/> that /// applies a delegate or lambda expression to three argument expressions. /// </summary> /// <returns> /// An <see cref="InvocationExpression"/> that /// applies the specified delegate or lambda expression to the provided arguments. /// </returns> /// <param name="expression"> /// An <see cref="Expression"/> that represents the delegate /// or lambda expression to be applied. /// </param> /// <param name="arg0"> /// The <see cref="Expression"/> that represents the first argument. /// </param> /// <param name="arg1"> /// The <see cref="Expression"/> that represents the second argument. /// </param> /// <param name="arg2"> /// The <see cref="Expression"/> that represents the third argument. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="expression"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="expression"/>.Type does not represent a delegate type or an <see cref="Expression{TDelegate}"/>.-or-The <see cref="Expression.Type"/> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression"/>.</exception> /// <exception cref="InvalidOperationException"> /// The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression"/>.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2) { // NB: This method is marked as non-public to avoid public API additions at this point. ExpressionUtils.RequiresCanRead(expression, nameof(expression)); MethodInfo method = GetInvokeMethod(expression); ParameterInfo[] pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 3, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0], nameof(expression), nameof(arg0)); arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1], nameof(expression), nameof(arg1)); arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2], nameof(expression), nameof(arg2)); return new InvocationExpression3(expression, method.ReturnType, arg0, arg1, arg2); } /// <summary> /// Creates an <see cref="InvocationExpression"/> that /// applies a delegate or lambda expression to four argument expressions. /// </summary> /// <returns> /// An <see cref="InvocationExpression"/> that /// applies the specified delegate or lambda expression to the provided arguments. /// </returns> /// <param name="expression"> /// An <see cref="Expression"/> that represents the delegate /// or lambda expression to be applied. /// </param> /// <param name="arg0"> /// The <see cref="Expression"/> that represents the first argument. /// </param> /// <param name="arg1"> /// The <see cref="Expression"/> that represents the second argument. /// </param> /// <param name="arg2"> /// The <see cref="Expression"/> that represents the third argument. /// </param> /// <param name="arg3"> /// The <see cref="Expression"/> that represents the fourth argument. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="expression"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="expression"/>.Type does not represent a delegate type or an <see cref="Expression{TDelegate}"/>.-or-The <see cref="Expression.Type"/> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression"/>.</exception> /// <exception cref="InvalidOperationException"> /// The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression"/>.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2, Expression arg3) { // NB: This method is marked as non-public to avoid public API additions at this point. ExpressionUtils.RequiresCanRead(expression, nameof(expression)); MethodInfo method = GetInvokeMethod(expression); ParameterInfo[] pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 4, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0], nameof(expression), nameof(arg0)); arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1], nameof(expression), nameof(arg1)); arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2], nameof(expression), nameof(arg2)); arg3 = ValidateOneArgument(method, ExpressionType.Invoke, arg3, pis[3], nameof(expression), nameof(arg3)); return new InvocationExpression4(expression, method.ReturnType, arg0, arg1, arg2, arg3); } /// <summary> /// Creates an <see cref="InvocationExpression"/> that /// applies a delegate or lambda expression to five argument expressions. /// </summary> /// <returns> /// An <see cref="InvocationExpression"/> that /// applies the specified delegate or lambda expression to the provided arguments. /// </returns> /// <param name="expression"> /// An <see cref="Expression"/> that represents the delegate /// or lambda expression to be applied. /// </param> /// <param name="arg0"> /// The <see cref="Expression"/> that represents the first argument. /// </param> /// <param name="arg1"> /// The <see cref="Expression"/> that represents the second argument. /// </param> /// <param name="arg2"> /// The <see cref="Expression"/> that represents the third argument. /// </param> /// <param name="arg3"> /// The <see cref="Expression"/> that represents the fourth argument. /// </param> /// <param name="arg4"> /// The <see cref="Expression"/> that represents the fifth argument. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="expression"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="expression"/>.Type does not represent a delegate type or an <see cref="Expression{TDelegate}"/>.-or-The <see cref="Expression.Type"/> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression"/>.</exception> /// <exception cref="InvalidOperationException"> /// The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression"/>.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { // NB: This method is marked as non-public to avoid public API additions at this point. ExpressionUtils.RequiresCanRead(expression, nameof(expression)); MethodInfo method = GetInvokeMethod(expression); ParameterInfo[] pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 5, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0], nameof(expression), nameof(arg0)); arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1], nameof(expression), nameof(arg1)); arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2], nameof(expression), nameof(arg2)); arg3 = ValidateOneArgument(method, ExpressionType.Invoke, arg3, pis[3], nameof(expression), nameof(arg3)); arg4 = ValidateOneArgument(method, ExpressionType.Invoke, arg4, pis[4], nameof(expression), nameof(arg4)); return new InvocationExpression5(expression, method.ReturnType, arg0, arg1, arg2, arg3, arg4); } /// <summary> /// Creates an <see cref="InvocationExpression"/> that /// applies a delegate or lambda expression to a list of argument expressions. /// </summary> /// <returns> /// An <see cref="InvocationExpression"/> that /// applies the specified delegate or lambda expression to the provided arguments. /// </returns> /// <param name="expression"> /// An <see cref="Expression"/> that represents the delegate /// or lambda expression to be applied. /// </param> /// <param name="arguments"> /// An array of <see cref="Expression"/> objects /// that represent the arguments that the delegate or lambda expression is applied to. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="expression"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="expression"/>.Type does not represent a delegate type or an <see cref="Expression{TDelegate}"/>.-or-The <see cref="Expression.Type"/> property of an element of <paramref name="arguments"/> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression"/>.</exception> /// <exception cref="InvalidOperationException"> /// <paramref name="arguments"/> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression"/>.</exception> public static InvocationExpression Invoke(Expression expression, params Expression[] arguments) { return Invoke(expression, (IEnumerable<Expression>)arguments); } /// <summary> /// Creates an <see cref="InvocationExpression"/> that /// applies a delegate or lambda expression to a list of argument expressions. /// </summary> /// <returns> /// An <see cref="InvocationExpression"/> that /// applies the specified delegate or lambda expression to the provided arguments. /// </returns> /// <param name="expression"> /// An <see cref="Expression"/> that represents the delegate /// or lambda expression to be applied. /// </param> /// <param name="arguments"> /// An <see cref="Collections.Generic.IEnumerable{TDelegate}"/> of <see cref="Expression"/> objects /// that represent the arguments that the delegate or lambda expression is applied to. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="expression"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="expression"/>.Type does not represent a delegate type or an <see cref="Expression{TDelegate}"/>.-or-The <see cref="Expression.Type"/> property of an element of <paramref name="arguments"/> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression"/>.</exception> /// <exception cref="InvalidOperationException"> /// <paramref name="arguments"/> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression"/>.</exception> public static InvocationExpression Invoke(Expression expression, IEnumerable<Expression> arguments) { IReadOnlyList<Expression> argumentList = arguments as IReadOnlyList<Expression> ?? arguments.ToReadOnly(); switch (argumentList.Count) { case 0: return Invoke(expression); case 1: return Invoke(expression, argumentList[0]); case 2: return Invoke(expression, argumentList[0], argumentList[1]); case 3: return Invoke(expression, argumentList[0], argumentList[1], argumentList[2]); case 4: return Invoke(expression, argumentList[0], argumentList[1], argumentList[2], argumentList[3]); case 5: return Invoke(expression, argumentList[0], argumentList[1], argumentList[2], argumentList[3], argumentList[4]); } ExpressionUtils.RequiresCanRead(expression, nameof(expression)); ReadOnlyCollection<Expression> args = argumentList.ToReadOnly(); // Ensure is TrueReadOnlyCollection when count > 5. Returns fast if it already is. MethodInfo mi = GetInvokeMethod(expression); ValidateArgumentTypes(mi, ExpressionType.Invoke, ref args, nameof(expression)); return new InvocationExpressionN(expression, args, mi.ReturnType); } /// <summary> /// Gets the delegate's Invoke method; used by InvocationExpression. /// </summary> /// <param name="expression">The expression to be invoked.</param> internal static MethodInfo GetInvokeMethod(Expression expression) { Type delegateType = expression.Type; if (!expression.Type.IsSubclassOf(typeof(MulticastDelegate))) { Type exprType = TypeUtils.FindGenericType(typeof(Expression<>), expression.Type); if (exprType == null) { throw Error.ExpressionTypeNotInvocable(expression.Type, nameof(expression)); } delegateType = exprType.GetGenericArguments()[0]; } return delegateType.GetInvokeMethod(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Xml.Serialization; namespace NPOI.OpenXmlFormats.Spreadsheet { [Serializable] [DebuggerStepThrough] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_QueryTable { private CT_QueryTableRefresh queryTableRefreshField; private CT_ExtensionList extLstField; private string nameField; private bool headersField; private bool rowNumbersField; private bool disableRefreshField; private bool backgroundRefreshField; private bool firstBackgroundRefreshField; private bool refreshOnLoadField; private ST_GrowShrinkType growShrinkTypeField; private bool fillFormulasField; private bool removeDataOnSaveField; private bool disableEditField; private bool preserveFormattingField; private bool adjustColumnWidthField; private bool intermediateField; private uint connectionIdField; private uint autoFormatIdField; private bool autoFormatIdFieldSpecified; private bool applyNumberFormatsField; private bool applyNumberFormatsFieldSpecified; private bool applyBorderFormatsField; private bool applyBorderFormatsFieldSpecified; private bool applyFontFormatsField; private bool applyFontFormatsFieldSpecified; private bool applyPatternFormatsField; private bool applyPatternFormatsFieldSpecified; private bool applyAlignmentFormatsField; private bool applyAlignmentFormatsFieldSpecified; private bool applyWidthHeightFormatsField; private bool applyWidthHeightFormatsFieldSpecified; public CT_QueryTable() { this.headersField = true; this.rowNumbersField = false; this.disableRefreshField = false; this.backgroundRefreshField = true; this.firstBackgroundRefreshField = false; this.refreshOnLoadField = false; this.growShrinkTypeField = ST_GrowShrinkType.insertDelete; this.fillFormulasField = false; this.removeDataOnSaveField = false; this.disableEditField = false; this.preserveFormattingField = true; this.adjustColumnWidthField = true; this.intermediateField = false; } public CT_QueryTableRefresh queryTableRefresh { get { return this.queryTableRefreshField; } set { this.queryTableRefreshField = value; } } public CT_ExtensionList extLst { get { return this.extLstField; } set { this.extLstField = value; } } [XmlAttribute] public string name { get { return this.nameField; } set { this.nameField = value; } } [XmlAttribute] [DefaultValueAttribute(true)] public bool headers { get { return this.headersField; } set { this.headersField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool rowNumbers { get { return this.rowNumbersField; } set { this.rowNumbersField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool disableRefresh { get { return this.disableRefreshField; } set { this.disableRefreshField = value; } } [XmlAttribute] [DefaultValueAttribute(true)] public bool backgroundRefresh { get { return this.backgroundRefreshField; } set { this.backgroundRefreshField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool firstBackgroundRefresh { get { return this.firstBackgroundRefreshField; } set { this.firstBackgroundRefreshField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool refreshOnLoad { get { return this.refreshOnLoadField; } set { this.refreshOnLoadField = value; } } [XmlAttribute] [DefaultValueAttribute(ST_GrowShrinkType.insertDelete)] public ST_GrowShrinkType growShrinkType { get { return this.growShrinkTypeField; } set { this.growShrinkTypeField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool fillFormulas { get { return this.fillFormulasField; } set { this.fillFormulasField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool removeDataOnSave { get { return this.removeDataOnSaveField; } set { this.removeDataOnSaveField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool disableEdit { get { return this.disableEditField; } set { this.disableEditField = value; } } [XmlAttribute] [DefaultValueAttribute(true)] public bool preserveFormatting { get { return this.preserveFormattingField; } set { this.preserveFormattingField = value; } } [XmlAttribute] [DefaultValueAttribute(true)] public bool adjustColumnWidth { get { return this.adjustColumnWidthField; } set { this.adjustColumnWidthField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool intermediate { get { return this.intermediateField; } set { this.intermediateField = value; } } [XmlAttribute] public uint connectionId { get { return this.connectionIdField; } set { this.connectionIdField = value; } } [XmlAttribute] public uint autoFormatId { get { return this.autoFormatIdField; } set { this.autoFormatIdField = value; } } [XmlIgnore] public bool autoFormatIdSpecified { get { return this.autoFormatIdFieldSpecified; } set { this.autoFormatIdFieldSpecified = value; } } [XmlAttribute] public bool applyNumberFormats { get { return this.applyNumberFormatsField; } set { this.applyNumberFormatsField = value; } } [XmlIgnore] public bool applyNumberFormatsSpecified { get { return this.applyNumberFormatsFieldSpecified; } set { this.applyNumberFormatsFieldSpecified = value; } } [XmlAttribute] public bool applyBorderFormats { get { return this.applyBorderFormatsField; } set { this.applyBorderFormatsField = value; } } [XmlIgnore] public bool applyBorderFormatsSpecified { get { return this.applyBorderFormatsFieldSpecified; } set { this.applyBorderFormatsFieldSpecified = value; } } [XmlAttribute] public bool applyFontFormats { get { return this.applyFontFormatsField; } set { this.applyFontFormatsField = value; } } [XmlIgnore] public bool applyFontFormatsSpecified { get { return this.applyFontFormatsFieldSpecified; } set { this.applyFontFormatsFieldSpecified = value; } } [XmlAttribute] public bool applyPatternFormats { get { return this.applyPatternFormatsField; } set { this.applyPatternFormatsField = value; } } [XmlIgnore] public bool applyPatternFormatsSpecified { get { return this.applyPatternFormatsFieldSpecified; } set { this.applyPatternFormatsFieldSpecified = value; } } [XmlAttribute] public bool applyAlignmentFormats { get { return this.applyAlignmentFormatsField; } set { this.applyAlignmentFormatsField = value; } } [XmlIgnore] public bool applyAlignmentFormatsSpecified { get { return this.applyAlignmentFormatsFieldSpecified; } set { this.applyAlignmentFormatsFieldSpecified = value; } } [XmlAttribute] public bool applyWidthHeightFormats { get { return this.applyWidthHeightFormatsField; } set { this.applyWidthHeightFormatsField = value; } } [XmlIgnore] public bool applyWidthHeightFormatsSpecified { get { return this.applyWidthHeightFormatsFieldSpecified; } set { this.applyWidthHeightFormatsFieldSpecified = value; } } } [Serializable] [DebuggerStepThrough] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_QueryTableRefresh { private CT_QueryTableFields queryTableFieldsField; private CT_QueryTableDeletedFields queryTableDeletedFieldsField; private CT_SortState sortStateField; private CT_ExtensionList extLstField; private bool preserveSortFilterLayoutField; private bool fieldIdWrappedField; private bool headersInLastRefreshField; private byte minimumVersionField; private uint nextIdField; private uint unboundColumnsLeftField; private uint unboundColumnsRightField; public CT_QueryTableRefresh() { this.preserveSortFilterLayoutField = true; this.fieldIdWrappedField = false; this.headersInLastRefreshField = true; this.minimumVersionField = ((byte)(0)); this.nextIdField = ((uint)(1)); this.unboundColumnsLeftField = ((uint)(0)); this.unboundColumnsRightField = ((uint)(0)); } public CT_QueryTableFields queryTableFields { get { return this.queryTableFieldsField; } set { this.queryTableFieldsField = value; } } public CT_QueryTableDeletedFields queryTableDeletedFields { get { return this.queryTableDeletedFieldsField; } set { this.queryTableDeletedFieldsField = value; } } public CT_SortState sortState { get { return this.sortStateField; } set { this.sortStateField = value; } } public CT_ExtensionList extLst { get { return this.extLstField; } set { this.extLstField = value; } } [XmlAttribute] [DefaultValueAttribute(true)] public bool preserveSortFilterLayout { get { return this.preserveSortFilterLayoutField; } set { this.preserveSortFilterLayoutField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool fieldIdWrapped { get { return this.fieldIdWrappedField; } set { this.fieldIdWrappedField = value; } } [XmlAttribute] [DefaultValueAttribute(true)] public bool headersInLastRefresh { get { return this.headersInLastRefreshField; } set { this.headersInLastRefreshField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(byte), "0")] public byte minimumVersion { get { return this.minimumVersionField; } set { this.minimumVersionField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(uint), "1")] public uint nextId { get { return this.nextIdField; } set { this.nextIdField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(uint), "0")] public uint unboundColumnsLeft { get { return this.unboundColumnsLeftField; } set { this.unboundColumnsLeftField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(uint), "0")] public uint unboundColumnsRight { get { return this.unboundColumnsRightField; } set { this.unboundColumnsRightField = value; } } } [Serializable] [DebuggerStepThrough] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_QueryTableFields { private List<CT_QueryTableField> queryTableFieldField; private uint countField; public CT_QueryTableFields() { this.countField = ((uint)(0)); this.queryTableFieldField = new List<CT_QueryTableField>(); } [XmlElement("queryTableField")] public List<CT_QueryTableField> queryTableField { get { return this.queryTableFieldField; } set { this.queryTableFieldField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(uint), "0")] public uint count { get { return this.countField; } set { this.countField = value; } } } [Serializable] [DebuggerStepThrough] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_QueryTableField { private CT_ExtensionList extLstField; private uint idField; private string nameField; private bool dataBoundField; private bool rowNumbersField; private bool fillFormulasField; private bool clippedField; private uint tableColumnIdField; public CT_QueryTableField() { this.dataBoundField = true; this.rowNumbersField = false; this.fillFormulasField = false; this.clippedField = false; this.tableColumnIdField = ((uint)(0)); } public CT_ExtensionList extLst { get { return this.extLstField; } set { this.extLstField = value; } } [XmlAttribute] public uint id { get { return this.idField; } set { this.idField = value; } } [XmlAttribute] public string name { get { return this.nameField; } set { this.nameField = value; } } [XmlAttribute] [DefaultValueAttribute(true)] public bool dataBound { get { return this.dataBoundField; } set { this.dataBoundField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool rowNumbers { get { return this.rowNumbersField; } set { this.rowNumbersField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool fillFormulas { get { return this.fillFormulasField; } set { this.fillFormulasField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool clipped { get { return this.clippedField; } set { this.clippedField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(uint), "0")] public uint tableColumnId { get { return this.tableColumnIdField; } set { this.tableColumnIdField = value; } } } [Serializable] [DebuggerStepThrough] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_QueryTableDeletedFields { private CT_DeletedField[] deletedFieldField; private uint countField; private bool countFieldSpecified; [XmlElement("deletedField")] public CT_DeletedField[] deletedField { get { return this.deletedFieldField; } set { this.deletedFieldField = value; } } [XmlAttribute] public uint count { get { return this.countField; } set { this.countField = value; } } [XmlIgnore] public bool countSpecified { get { return this.countFieldSpecified; } set { this.countFieldSpecified = value; } } } [Serializable] [DebuggerStepThrough] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_DeletedField { private string nameField; [XmlAttribute] public string name { get { return this.nameField; } set { this.nameField = value; } } } [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=false)] public enum ST_GrowShrinkType { insertDelete, insertClear, overwriteClear, } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; using System.Text; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Update Distribution Request Marshaller /// </summary> public class UpdateDistributionRequestMarshaller : IMarshaller<IRequest, UpdateDistributionRequest> { public IRequest Marshall(UpdateDistributionRequest updateDistributionRequest) { IRequest request = new DefaultRequest(updateDistributionRequest, "AmazonCloudFront"); request.HttpMethod = "PUT"; if(updateDistributionRequest.IfMatch != null) request.Headers.Add("If-Match", updateDistributionRequest.IfMatch); string uriResourcePath = "2013-08-26/distribution/{Id}/config"; uriResourcePath = uriResourcePath.Replace("{Id}", updateDistributionRequest.Id ?? "" ); if (uriResourcePath.Contains("?")) { string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1); uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?")); foreach (string s in queryString.Split('&', ';')) { string[] nameValuePair = s.Split('='); if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0) { request.Parameters.Add(nameValuePair[0], nameValuePair[1]); } else { request.Parameters.Add(nameValuePair[0], null); } } } request.ResourcePath = uriResourcePath; StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); xmlWriter.Namespaces = true; if (updateDistributionRequest != null) { DistributionConfig distributionConfigDistributionConfig = updateDistributionRequest.DistributionConfig; if (distributionConfigDistributionConfig != null) { xmlWriter.WriteStartElement("DistributionConfig", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (distributionConfigDistributionConfig.IsSetCallerReference()) { xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.CallerReference.ToString()); } if (distributionConfigDistributionConfig != null) { Aliases aliasesAliases = distributionConfigDistributionConfig.Aliases; if (aliasesAliases != null) { xmlWriter.WriteStartElement("Aliases", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (aliasesAliases.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", aliasesAliases.Quantity.ToString()); } if (aliasesAliases != null) { List<string> aliasesAliasesitemsList = aliasesAliases.Items; if (aliasesAliasesitemsList != null && aliasesAliasesitemsList.Count > 0) { int aliasesAliasesitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); foreach (string aliasesAliasesitemsListValue in aliasesAliasesitemsList) { xmlWriter.WriteStartElement("CNAME", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); xmlWriter.WriteValue(aliasesAliasesitemsListValue); xmlWriter.WriteEndElement(); aliasesAliasesitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (distributionConfigDistributionConfig.IsSetDefaultRootObject()) { xmlWriter.WriteElementString("DefaultRootObject", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.DefaultRootObject.ToString()); } if (distributionConfigDistributionConfig != null) { Origins originsOrigins = distributionConfigDistributionConfig.Origins; if (originsOrigins != null) { xmlWriter.WriteStartElement("Origins", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (originsOrigins.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", originsOrigins.Quantity.ToString()); } if (originsOrigins != null) { List<Origin> originsOriginsitemsList = originsOrigins.Items; if (originsOriginsitemsList != null && originsOriginsitemsList.Count > 0) { int originsOriginsitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); foreach (Origin originsOriginsitemsListValue in originsOriginsitemsList) { xmlWriter.WriteStartElement("Origin", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (originsOriginsitemsListValue.IsSetId()) { xmlWriter.WriteElementString("Id", "http://cloudfront.amazonaws.com/doc/2013-08-26/", originsOriginsitemsListValue.Id.ToString()); } if (originsOriginsitemsListValue.IsSetDomainName()) { xmlWriter.WriteElementString("DomainName", "http://cloudfront.amazonaws.com/doc/2013-08-26/", originsOriginsitemsListValue.DomainName.ToString()); } if (originsOriginsitemsListValue != null) { S3OriginConfig s3OriginConfigS3OriginConfig = originsOriginsitemsListValue.S3OriginConfig; if (s3OriginConfigS3OriginConfig != null) { xmlWriter.WriteStartElement("S3OriginConfig", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (s3OriginConfigS3OriginConfig.IsSetOriginAccessIdentity()) { xmlWriter.WriteElementString("OriginAccessIdentity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", s3OriginConfigS3OriginConfig.OriginAccessIdentity.ToString()); } xmlWriter.WriteEndElement(); } } if (originsOriginsitemsListValue != null) { CustomOriginConfig customOriginConfigCustomOriginConfig = originsOriginsitemsListValue.CustomOriginConfig; if (customOriginConfigCustomOriginConfig != null) { xmlWriter.WriteStartElement("CustomOriginConfig", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (customOriginConfigCustomOriginConfig.IsSetHTTPPort()) { xmlWriter.WriteElementString("HTTPPort", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customOriginConfigCustomOriginConfig.HTTPPort.ToString()); } if (customOriginConfigCustomOriginConfig.IsSetHTTPSPort()) { xmlWriter.WriteElementString("HTTPSPort", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customOriginConfigCustomOriginConfig.HTTPSPort.ToString()); } if (customOriginConfigCustomOriginConfig.IsSetOriginProtocolPolicy()) { xmlWriter.WriteElementString("OriginProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customOriginConfigCustomOriginConfig.OriginProtocolPolicy.ToString()); } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); originsOriginsitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (distributionConfigDistributionConfig != null) { DefaultCacheBehavior defaultCacheBehaviorDefaultCacheBehavior = distributionConfigDistributionConfig.DefaultCacheBehavior; if (defaultCacheBehaviorDefaultCacheBehavior != null) { xmlWriter.WriteStartElement("DefaultCacheBehavior", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (defaultCacheBehaviorDefaultCacheBehavior.IsSetTargetOriginId()) { xmlWriter.WriteElementString("TargetOriginId", "http://cloudfront.amazonaws.com/doc/2013-08-26/", defaultCacheBehaviorDefaultCacheBehavior.TargetOriginId.ToString()); } if (defaultCacheBehaviorDefaultCacheBehavior != null) { ForwardedValues forwardedValuesForwardedValues = defaultCacheBehaviorDefaultCacheBehavior.ForwardedValues; if (forwardedValuesForwardedValues != null) { xmlWriter.WriteStartElement("ForwardedValues", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (forwardedValuesForwardedValues.IsSetQueryString()) { xmlWriter.WriteElementString("QueryString", "http://cloudfront.amazonaws.com/doc/2013-08-26/", forwardedValuesForwardedValues.QueryString.ToString().ToLower()); } if (forwardedValuesForwardedValues != null) { CookiePreference cookiePreferenceCookies = forwardedValuesForwardedValues.Cookies; if (cookiePreferenceCookies != null) { xmlWriter.WriteStartElement("Cookies", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (cookiePreferenceCookies.IsSetForward()) { xmlWriter.WriteElementString("Forward", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cookiePreferenceCookies.Forward.ToString()); } if (cookiePreferenceCookies != null) { CookieNames cookieNamesWhitelistedNames = cookiePreferenceCookies.WhitelistedNames; if (cookieNamesWhitelistedNames != null) { xmlWriter.WriteStartElement("WhitelistedNames", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (cookieNamesWhitelistedNames.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cookieNamesWhitelistedNames.Quantity.ToString()); } if (cookieNamesWhitelistedNames != null) { List<string> cookieNamesWhitelistedNamesitemsList = cookieNamesWhitelistedNames.Items; if (cookieNamesWhitelistedNamesitemsList != null && cookieNamesWhitelistedNamesitemsList.Count > 0) { int cookieNamesWhitelistedNamesitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); foreach (string cookieNamesWhitelistedNamesitemsListValue in cookieNamesWhitelistedNamesitemsList) { xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); xmlWriter.WriteValue(cookieNamesWhitelistedNamesitemsListValue); xmlWriter.WriteEndElement(); cookieNamesWhitelistedNamesitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (defaultCacheBehaviorDefaultCacheBehavior != null) { TrustedSigners trustedSignersTrustedSigners = defaultCacheBehaviorDefaultCacheBehavior.TrustedSigners; if (trustedSignersTrustedSigners != null) { xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (trustedSignersTrustedSigners.IsSetEnabled()) { xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Enabled.ToString().ToLower()); } if (trustedSignersTrustedSigners.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Quantity.ToString()); } if (trustedSignersTrustedSigners != null) { List<string> trustedSignersTrustedSignersitemsList = trustedSignersTrustedSigners.Items; if (trustedSignersTrustedSignersitemsList != null && trustedSignersTrustedSignersitemsList.Count > 0) { int trustedSignersTrustedSignersitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); foreach (string trustedSignersTrustedSignersitemsListValue in trustedSignersTrustedSignersitemsList) { xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); xmlWriter.WriteValue(trustedSignersTrustedSignersitemsListValue); xmlWriter.WriteEndElement(); trustedSignersTrustedSignersitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (defaultCacheBehaviorDefaultCacheBehavior.IsSetViewerProtocolPolicy()) { xmlWriter.WriteElementString("ViewerProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2013-08-26/", defaultCacheBehaviorDefaultCacheBehavior.ViewerProtocolPolicy.ToString()); } if (defaultCacheBehaviorDefaultCacheBehavior.IsSetMinTTL()) { xmlWriter.WriteElementString("MinTTL", "http://cloudfront.amazonaws.com/doc/2013-08-26/", defaultCacheBehaviorDefaultCacheBehavior.MinTTL.ToString()); } xmlWriter.WriteEndElement(); } } if (distributionConfigDistributionConfig != null) { CacheBehaviors cacheBehaviorsCacheBehaviors = distributionConfigDistributionConfig.CacheBehaviors; if (cacheBehaviorsCacheBehaviors != null) { xmlWriter.WriteStartElement("CacheBehaviors", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (cacheBehaviorsCacheBehaviors.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviors.Quantity.ToString()); } if (cacheBehaviorsCacheBehaviors != null) { List<CacheBehavior> cacheBehaviorsCacheBehaviorsitemsList = cacheBehaviorsCacheBehaviors.Items; if (cacheBehaviorsCacheBehaviorsitemsList != null && cacheBehaviorsCacheBehaviorsitemsList.Count > 0) { int cacheBehaviorsCacheBehaviorsitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); foreach (CacheBehavior cacheBehaviorsCacheBehaviorsitemsListValue in cacheBehaviorsCacheBehaviorsitemsList) { xmlWriter.WriteStartElement("CacheBehavior", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (cacheBehaviorsCacheBehaviorsitemsListValue.IsSetPathPattern()) { xmlWriter.WriteElementString("PathPattern", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviorsitemsListValue.PathPattern.ToString()); } if (cacheBehaviorsCacheBehaviorsitemsListValue.IsSetTargetOriginId()) { xmlWriter.WriteElementString("TargetOriginId", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviorsitemsListValue.TargetOriginId.ToString()); } if (cacheBehaviorsCacheBehaviorsitemsListValue != null) { ForwardedValues forwardedValuesForwardedValues = cacheBehaviorsCacheBehaviorsitemsListValue.ForwardedValues; if (forwardedValuesForwardedValues != null) { xmlWriter.WriteStartElement("ForwardedValues", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (forwardedValuesForwardedValues.IsSetQueryString()) { xmlWriter.WriteElementString("QueryString", "http://cloudfront.amazonaws.com/doc/2013-08-26/", forwardedValuesForwardedValues.QueryString.ToString().ToLower()); } if (forwardedValuesForwardedValues != null) { CookiePreference cookiePreferenceCookies = forwardedValuesForwardedValues.Cookies; if (cookiePreferenceCookies != null) { xmlWriter.WriteStartElement("Cookies", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (cookiePreferenceCookies.IsSetForward()) { xmlWriter.WriteElementString("Forward", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cookiePreferenceCookies.Forward.ToString()); } if (cookiePreferenceCookies != null) { CookieNames cookieNamesWhitelistedNames = cookiePreferenceCookies.WhitelistedNames; if (cookieNamesWhitelistedNames != null) { xmlWriter.WriteStartElement("WhitelistedNames", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (cookieNamesWhitelistedNames.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cookieNamesWhitelistedNames.Quantity.ToString()); } if (cookieNamesWhitelistedNames != null) { List<string> cookieNamesWhitelistedNamesitemsList = cookieNamesWhitelistedNames.Items; if (cookieNamesWhitelistedNamesitemsList != null && cookieNamesWhitelistedNamesitemsList.Count > 0) { int cookieNamesWhitelistedNamesitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); foreach (string cookieNamesWhitelistedNamesitemsListValue in cookieNamesWhitelistedNamesitemsList) { xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); xmlWriter.WriteValue(cookieNamesWhitelistedNamesitemsListValue); xmlWriter.WriteEndElement(); cookieNamesWhitelistedNamesitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (cacheBehaviorsCacheBehaviorsitemsListValue != null) { TrustedSigners trustedSignersTrustedSigners = cacheBehaviorsCacheBehaviorsitemsListValue.TrustedSigners; if (trustedSignersTrustedSigners != null) { xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (trustedSignersTrustedSigners.IsSetEnabled()) { xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Enabled.ToString().ToLower()); } if (trustedSignersTrustedSigners.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Quantity.ToString()); } if (trustedSignersTrustedSigners != null) { List<string> trustedSignersTrustedSignersitemsList = trustedSignersTrustedSigners.Items; if (trustedSignersTrustedSignersitemsList != null && trustedSignersTrustedSignersitemsList.Count > 0) { int trustedSignersTrustedSignersitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); foreach (string trustedSignersTrustedSignersitemsListValue in trustedSignersTrustedSignersitemsList) { xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); xmlWriter.WriteValue(trustedSignersTrustedSignersitemsListValue); xmlWriter.WriteEndElement(); trustedSignersTrustedSignersitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (cacheBehaviorsCacheBehaviorsitemsListValue.IsSetViewerProtocolPolicy()) { xmlWriter.WriteElementString("ViewerProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviorsitemsListValue.ViewerProtocolPolicy.ToString()); } if (cacheBehaviorsCacheBehaviorsitemsListValue.IsSetMinTTL()) { xmlWriter.WriteElementString("MinTTL", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviorsitemsListValue.MinTTL.ToString()); } xmlWriter.WriteEndElement(); cacheBehaviorsCacheBehaviorsitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (distributionConfigDistributionConfig != null) { CustomErrorResponses customErrorResponsesCustomErrorResponses = distributionConfigDistributionConfig.CustomErrorResponses; if (customErrorResponsesCustomErrorResponses != null) { xmlWriter.WriteStartElement("CustomErrorResponses", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (customErrorResponsesCustomErrorResponses.IsSetQuantity()) { xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponses.Quantity.ToString()); } if (customErrorResponsesCustomErrorResponses != null) { List<CustomErrorResponse> customErrorResponsesCustomErrorResponsesitemsList = customErrorResponsesCustomErrorResponses.Items; if (customErrorResponsesCustomErrorResponsesitemsList != null && customErrorResponsesCustomErrorResponsesitemsList.Count > 0) { int customErrorResponsesCustomErrorResponsesitemsListIndex = 1; xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); foreach (CustomErrorResponse customErrorResponsesCustomErrorResponsesitemsListValue in customErrorResponsesCustomErrorResponsesitemsList) { xmlWriter.WriteStartElement("CustomErrorResponse", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (customErrorResponsesCustomErrorResponsesitemsListValue.IsSetErrorCode()) { xmlWriter.WriteElementString("ErrorCode", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponsesitemsListValue.ErrorCode.ToString()); } if (customErrorResponsesCustomErrorResponsesitemsListValue.IsSetResponsePagePath()) { xmlWriter.WriteElementString("ResponsePagePath", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponsesitemsListValue.ResponsePagePath.ToString()); } if (customErrorResponsesCustomErrorResponsesitemsListValue.IsSetResponseCode()) { xmlWriter.WriteElementString("ResponseCode", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponsesitemsListValue.ResponseCode.ToString()); } if (customErrorResponsesCustomErrorResponsesitemsListValue.IsSetErrorCachingMinTTL()) { xmlWriter.WriteElementString("ErrorCachingMinTTL", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponsesitemsListValue.ErrorCachingMinTTL.ToString()); } xmlWriter.WriteEndElement(); customErrorResponsesCustomErrorResponsesitemsListIndex++; } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } if (distributionConfigDistributionConfig.IsSetComment()) { xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.Comment.ToString()); } if (distributionConfigDistributionConfig != null) { LoggingConfig loggingConfigLogging = distributionConfigDistributionConfig.Logging; if (loggingConfigLogging != null) { xmlWriter.WriteStartElement("Logging", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (loggingConfigLogging.IsSetEnabled()) { xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", loggingConfigLogging.Enabled.ToString().ToLower()); } if (loggingConfigLogging.IsSetIncludeCookies()) { xmlWriter.WriteElementString("IncludeCookies", "http://cloudfront.amazonaws.com/doc/2013-08-26/", loggingConfigLogging.IncludeCookies.ToString().ToLower()); } if (loggingConfigLogging.IsSetBucket()) { xmlWriter.WriteElementString("Bucket", "http://cloudfront.amazonaws.com/doc/2013-08-26/", loggingConfigLogging.Bucket.ToString()); } if (loggingConfigLogging.IsSetPrefix()) { xmlWriter.WriteElementString("Prefix", "http://cloudfront.amazonaws.com/doc/2013-08-26/", loggingConfigLogging.Prefix.ToString()); } xmlWriter.WriteEndElement(); } } if (distributionConfigDistributionConfig.IsSetPriceClass()) { xmlWriter.WriteElementString("PriceClass", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.PriceClass.ToString()); } if (distributionConfigDistributionConfig.IsSetEnabled()) { xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.Enabled.ToString().ToLower()); } if (distributionConfigDistributionConfig != null) { ViewerCertificate viewerCertificateViewerCertificate = distributionConfigDistributionConfig.ViewerCertificate; if (viewerCertificateViewerCertificate != null) { xmlWriter.WriteStartElement("ViewerCertificate", "http://cloudfront.amazonaws.com/doc/2013-08-26/"); if (viewerCertificateViewerCertificate.IsSetIAMCertificateId()) { xmlWriter.WriteElementString("IAMCertificateId", "http://cloudfront.amazonaws.com/doc/2013-08-26/", viewerCertificateViewerCertificate.IAMCertificateId.ToString()); } if (viewerCertificateViewerCertificate.IsSetCloudFrontDefaultCertificate()) { xmlWriter.WriteElementString("CloudFrontDefaultCertificate", "http://cloudfront.amazonaws.com/doc/2013-08-26/", viewerCertificateViewerCertificate.CloudFrontDefaultCertificate.ToString().ToLower()); } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } try { request.Content = System.Text.Encoding.UTF8.GetBytes(stringWriter.ToString()); request.Headers.Add("Content-Type", "application/xml"); } catch (EncoderFallbackException e) { throw new AmazonServiceException("Unable to marshall request to XML", e); } return request; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.LdapMessageQueue.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using RfcLdapMessage = Novell.Directory.Ldap.Rfc2251.RfcLdapMessage; using ExtResponseFactory = Novell.Directory.Ldap.Utilclass.ExtResponseFactory; using IntermediateResponseFactory = Novell.Directory.Ldap.Utilclass.IntermediateResponseFactory; namespace Novell.Directory.Ldap { /// <summary> Represents a queue of incoming asynchronous messages from the server. /// It is the common interface for {@link LdapResponseQueue} and /// {@link LdapSearchQueue}. /// </summary> public abstract class LdapMessageQueue { /// <summary> Returns the name used for debug /// /// </summary> /// <returns> name of object instance used for debug /// </returns> virtual internal System.String DebugName { /* package */ get { return name; } } /// <summary> Returns the internal client message agent /// /// </summary> /// <returns> The internal client message agent /// </returns> virtual internal MessageAgent MessageAgent { /* package */ get { return agent; } } /// <summary> Returns the message IDs for all outstanding requests. These are requests /// for which a response has not been received from the server or which /// still have messages to be retrieved with getResponse. /// /// The last ID in the array is the messageID of the last submitted /// request. /// /// </summary> /// <returns> The message IDs for all outstanding requests. /// </returns> virtual public int[] MessageIDs { get { return agent.MessageIDs; } } /// <summary> The message agent object associated with this queue</summary> /* package */ internal MessageAgent agent; // Queue name used only for debug /* package */ internal System.String name = ""; // nameLock used to protect queueNum during increment /* package */ internal static System.Object nameLock; // Queue number used only for debug /* package */ internal static int queueNum = 0; /// <summary> Constructs a response queue using the specified message agent /// /// </summary> /// <param name="agent">The message agent to associate with this conneciton /// </param> /* package */ internal LdapMessageQueue(System.String myname, MessageAgent agent) { // Get a unique connection name for debug this.agent = agent; return ; } /// <summary> Returns the response from an Ldap request. /// /// The getResponse method blocks until a response is available, or until /// all operations associated with the object have completed or been /// canceled, and then returns the response. /// /// The application is responsible to determine the type of message /// returned. /// /// </summary> /// <returns> The response. /// /// </returns> /// <seealso cref="LdapResponse"> /// </seealso> /// <seealso cref="LdapSearchResult"> /// </seealso> /// <seealso cref="LdapSearchResultReference"> /// /// </seealso> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> public virtual LdapMessage getResponse() { return getResponse(null); } /// <summary> Returns the response from an Ldap request for a particular message ID. /// /// The getResponse method blocks until a response is available /// for a particular message ID, or until all operations associated /// with the object have completed or been canceled, and /// then returns the response. If there is no outstanding operation for /// the message ID (or if it is zero or a negative number), /// IllegalArgumentException is thrown. /// /// The application is responsible to determine the type of message /// returned. /// /// </summary> /// <param name="msgid">query for responses for a specific message request /// /// </param> /// <returns> The response from the server. /// /// </returns> /// <seealso cref="LdapResponse"> /// </seealso> /// <seealso cref="LdapSearchResult"> /// </seealso> /// <seealso cref="LdapSearchResultReference"> /// /// </seealso> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> public virtual LdapMessage getResponse(System.Int32 msgid) { return getResponse(new Integer32(msgid)); } /// <summary> Private implementation of getResponse. /// Has an Integer object as a parameter so we can distinguish /// the null and the message number case /// </summary> // private LdapMessage getResponse(System.Int32 msgid) private LdapMessage getResponse(Integer32 msgid) { System.Object resp; RfcLdapMessage message; LdapMessage response; if ((resp = agent.getLdapMessage(msgid)) == null) { // blocks return null; // no messages from this agent } // Local error occurred, contains a LocalException if (resp is LdapResponse) { return (LdapMessage) resp; } // Normal message handling message = (RfcLdapMessage) resp; switch (message.Type) { case LdapMessage.SEARCH_RESPONSE: response = new LdapSearchResult(message); break; case LdapMessage.SEARCH_RESULT_REFERENCE: response = new LdapSearchResultReference(message); break; case LdapMessage.EXTENDED_RESPONSE: ExtResponseFactory fac = new ExtResponseFactory(); response = ExtResponseFactory.convertToExtendedResponse(message); break; case LdapMessage.INTERMEDIATE_RESPONSE : response = IntermediateResponseFactory.convertToIntermediateResponse(message); break; default: response = new LdapResponse(message); break; } return response; } /// <summary> Reports true if any response has been received from the server and not /// yet retrieved with getResponse. If getResponse has been used to /// retrieve all messages received to this point, then isResponseReceived /// returns false. /// /// </summary> /// <returns> true if a response is available to be retrieved via getResponse, /// otherwise false. /// /// </returns> public virtual bool isResponseReceived() { return agent.isResponseReceived(); } /// <summary> Reports true if a response has been received from the server for /// a particular message ID but not yet retrieved with getResponse. If /// there is no outstanding operation for the message ID (or if it is /// zero or a negative number), IllegalArgumentException is thrown. /// /// </summary> /// <param name="msgid"> A particular message ID to query for available responses. /// /// </param> /// <returns> true if a response is available to be retrieved via getResponse /// for the specified message ID, otherwise false. /// /// </returns> public virtual bool isResponseReceived(int msgid) { return agent.isResponseReceived(msgid); } /// <summary> Reports true if all results have been received for a particular /// message id. /// /// If the search result done has been received from the server for the /// message id, it reports true. There may still be messages waiting to be /// retrieved by the applcation with getResponse. /// /// @throws IllegalArgumentException if there is no outstanding operation /// for the message ID, /// </summary> public virtual bool isComplete(int msgid) { return agent.isComplete(msgid); } static LdapMessageQueue() { nameLock = new System.Object(); } } }
using System; using System.Collections; using System.Collections.Generic; namespace TagLib.Mpeg4 { public class AppleTag : TagLib.Tag, IEnumerable { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private AppleItemListBox ilst_box; private File file; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public AppleTag (AppleItemListBox box, File file) : base () { // Hold onto the ilst_box and file. If the box doesn't exist, create // one. ilst_box = (box == null) ? new AppleItemListBox () : box; this.file = file; } public AppleTag (File file) : this (null, file) { } public IEnumerator GetEnumerator() { return ilst_box.Children.GetEnumerator(); } // Get all the data boxes with the provided types. public AppleDataBox [] DataBoxes (ByteVectorList list) { List<AppleDataBox> l = new List<AppleDataBox> (); // Check each box to see if the match any of the provided types. // If a match is found, loop through the children and add any data box. foreach (Box box in ilst_box.Children) foreach (ByteVector v in list) if (FixId (v) == box.BoxType) foreach (Box data_box in box.Children) if (data_box.GetType () == typeof (AppleDataBox)) l.Add ((AppleDataBox)data_box); // Return the results as an array. return (AppleDataBox []) l.ToArray (); } // Get all the data boxes with a given type. public AppleDataBox [] DataBoxes (ByteVector v) { return DataBoxes (new ByteVectorList (FixId (v))); } // Find all the data boxes with a given mean and name. public AppleDataBox [] DataBoxes (string mean, string name) { List<AppleDataBox> l = new List<AppleDataBox> (); // These children will have a box type of "----" foreach (Box box in ilst_box.Children) if (box.BoxType == "----") { // Get the mean and name boxes, make sure they're legit, and make // sure that they match what we want. Then loop through and add // all the data box children to our output. AppleAdditionalInfoBox mean_box = (AppleAdditionalInfoBox) box.FindChild ("meta"); AppleAdditionalInfoBox name_box = (AppleAdditionalInfoBox) box.FindChild ("name"); if (mean_box != null && name_box != null && mean_box.Text == mean && name_box.Text == name) foreach (Box data_box in box.Children) if (data_box.GetType () == typeof (AppleDataBox)) l.Add ((AppleDataBox)data_box); } // Return the results as an array. return (AppleDataBox []) l.ToArray (); } // Get all the text data boxes from a given box type. public string [] GetText (ByteVector type) { StringList l = new StringList (); foreach (AppleDataBox box in DataBoxes (type)) if (box.Text != null) l.Add (box.Text); return l.ToArray (); } // Set the data with the given box type, data, and flags. public void SetData (ByteVector type, AppleDataBox [] boxes) { // Fix the type. type = FixId (type); bool first = true; // Loop through the children and find all with the type. foreach (Box box in ilst_box.Children) if (type == box.BoxType) { // If this is our first child... if (first) { // clear its children and add our data boxes. box.ClearChildren (); foreach (AppleDataBox b in boxes) box.AddChild (b); first = false; } // Otherwise, it is dead to us. else box.RemoveFromParent (); } // If we didn't find the box.. if (first == true) { // Add the box and try again. Box box = new AppleAnnotationBox (type); ilst_box.AddChild (box); SetData (type, boxes); } } public void SetData (ByteVector type, ByteVectorList data, uint flags) { if (data == null || data.Count == 0) { ClearData (type); return; } AppleDataBox [] boxes = new AppleDataBox [data.Count]; for (int i = 0; i < data.Count; i ++) boxes [i] = new AppleDataBox (data [i], flags); SetData (type, boxes); } // Set the data with the given box type, data, and flags. public void SetData (ByteVector type, ByteVector data, uint flags) { if (data == null || data.Count == 0) ClearData (type); else SetData (type, new ByteVectorList (data), flags); } // Set the data with the given box type, strings, and flags. public void SetText (ByteVector type, string [] text) { // Remove empty data and return. if (text == null) { ilst_box.RemoveChildren (FixId (type)); return; } // Create a list... ByteVectorList l = new ByteVectorList (); // and populate it with the ByteVectorized strings. foreach (string value in text) l.Add (ByteVector.FromString (value, StringType.UTF8)); // Send our final byte vectors to SetData SetData (type, l, (uint) AppleDataBox.FlagTypes.ContainsText); } // Set the data with the given box type, string, and flags. public void SetText (ByteVector type, string text) { // Remove empty data and return. if (text == null || text == "") { ilst_box.RemoveChildren (FixId (type)); return; } SetText (type, new string [] {text}); } // Clear all data associated with a box type. public void ClearData (ByteVector type) { ilst_box.RemoveChildren (FixId (type)); } // Save the file. public void Save () { if (ilst_box == null) { throw new NullReferenceException(); } // Try to get into write mode. file.Mode = File.AccessMode.Write; // Make a file box. FileBox file_box = new FileBox (file); // Get the MovieBox. IsoMovieBox moov_box = (IsoMovieBox) file_box.FindChildDeep ("moov"); // If we have a movie box... if (moov_box != null) { // Set up how much, where, and what to replace, and who to tell // about it. ulong original_size = 0; long position = -1; ByteVector data = null; Box parent = null; // Get the old ItemList (the one we're replacing. AppleItemListBox old_ilst_box = (AppleItemListBox) moov_box.FindChildDeep ("ilst"); // If it exists. if (old_ilst_box != null) { // We stick ourself in the meta box and slate to overwrite it. parent = old_ilst_box.Parent; original_size = parent.BoxSize; position = parent.NextBoxPosition - (long) original_size; parent.ReplaceChild (old_ilst_box, ilst_box); data = parent.Render (); parent = parent.Parent; } else { // There is not old ItemList. See if we can get a MetaBox. IsoMetaBox meta_box = (IsoMetaBox) moov_box.FindChildDeep ("meta"); //If we can... if (meta_box != null) { // Stick the child in here and slate to overwrite... meta_box.AddChild (ilst_box); original_size = meta_box.BoxSize; position = meta_box.NextBoxPosition - (long) original_size; data = meta_box.Render (); parent = meta_box.Parent; } else { // There's no MetaBox. Create one and add the ItemList. meta_box = new IsoMetaBox ("hdlr", null); meta_box.AddChild (ilst_box); // See if we can get a UserDataBox. IsoUserDataBox udta_box = (IsoUserDataBox) moov_box.FindChildDeep ("udta"); // If we can... if (udta_box != null) { // We'll stick the MetaBox at the end and overwrite it. original_size = 0; position = udta_box.NextBoxPosition; data = meta_box.Render (); parent = udta_box; } else { // If not even the UserDataBox exists, create it and add // our MetaBox. udta_box = new IsoUserDataBox (); udta_box.AddChild (meta_box); // Since UserDataBox is a child of MovieBox, we'll just // insert it at the end. original_size = 0; position = moov_box.NextBoxPosition; data = udta_box.Render (); parent = moov_box; } } } // If we have data and somewhere to put it.. if (data != null && position >= 0) { // Figure out the size difference. long size_difference = (long) data.Count - (long) original_size; // Insert the new data. file.Insert (data, position, (long) (original_size)); // If there is a size difference, resize all parent headers. if (size_difference != 0) { while (parent != null) { parent.OverwriteHeader (size_difference); parent = parent.Parent; } // ALSO, VERY IMPORTANTLY, YOU MUST UPDATE EVERY 'stco'. foreach (Box box in moov_box.Children) if (box.BoxType == "trak") { IsoChunkLargeOffsetBox co64_box = (IsoChunkLargeOffsetBox) box.FindChildDeep ("co64"); if (co64_box != null) co64_box.UpdateOffset (size_difference, position); IsoChunkOffsetBox stco_box = (IsoChunkOffsetBox) box.FindChildDeep ("stco"); if (stco_box != null) stco_box.UpdateOffset ((int) size_difference, position); } } // Be nice and close the stream. file.Mode = File.AccessMode.Closed; return; } } else throw new ApplicationException("stream does not have MOOV tag"); // We're at the end. Close the stream and admit defeat. file.Mode = File.AccessMode.Closed; throw new ApplicationException("Could not complete AppleTag save"); } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// public override string Title { get { string [] text = GetText (FixId ("nam")); return text.Length == 0 ? null : text [0]; } set {SetText (FixId ("nam"), value);} } public override string [] AlbumArtists { get {return IsCompilation ? new string [] {"Various Artists"} : Performers;} set { if (value.Length == 1 && value [0].ToLower () == "various artists") IsCompilation = true; else { IsCompilation = false; Performers = value; } } } public bool IsCompilation { get { AppleDataBox [] boxes = DataBoxes ("cpil"); return boxes.Length != 0 && boxes [0].Data.ToUInt () != 0; } set { SetData ("cpil", ByteVector.FromUInt ((uint)(value ? 1 : 0)), (uint)AppleDataBox.FlagTypes.ForTempo); } } public override string [] Performers { get {return GetText (FixId ("ART"));} set {SetText (FixId ("ART"), value);} } public override string [] Composers { get {return GetText (FixId ("wrt"));} set {SetText (FixId ("wrt"), value);} } public override string Album { get { string [] text = GetText (FixId ("alb")); return text.Length == 0 ? null : text [0]; } set {SetText (FixId ("alb"), value);} } public override string Comment { get { AppleDataBox [] boxes = DataBoxes (FixId ("cmt")); return boxes.Length == 0 ? null : boxes [0].Text; } set { SetText (FixId ("cmt"), value); } } public override string [] Genres { get { StringList l = new StringList (); ByteVectorList names = new ByteVectorList (); names.Add (FixId ("gen")); names.Add (FixId ("gnre")); foreach (AppleDataBox box in DataBoxes (names)) if (box.Text != null) l.Add (box.Text); else if (box.Flags == (int) AppleDataBox.FlagTypes.ContainsData) { // iTunes stores genre's in the GNRE box as (ID3# + 1). string genre = Id3v1.GenreList.Genre ((byte) (box.Data.ToShort (true) - 1)); if (genre != null) l.Add (genre); } return l.ToArray (); } set { ClearData (FixId ("gnre")); SetText (FixId ("gen"), value); } } public override uint Year { get { AppleDataBox [] boxes = DataBoxes (FixId ("day")); try { return boxes.Length == 0 || boxes [0].Text == null ? 0 : System.UInt32.Parse (boxes [0].Text.Substring (0, boxes [0].Text.Length < 4 ? boxes [0].Text.Length : 4)); } catch {return 0;} } set { SetText (FixId ("day"), value.ToString ()); } } public override uint Track { get { AppleDataBox [] boxes = DataBoxes (FixId ("trkn")); if (boxes.Length != 0 && boxes [0].Flags == (int) AppleDataBox.FlagTypes.ContainsData && boxes [0].Data.Count >=4) return (uint) boxes [0].Data.Mid (2, 2).ToShort (); return 0; } set { ByteVector v = ByteVector.FromShort (0); v.Add (ByteVector.FromShort ((short) value)); v.Add (ByteVector.FromShort ((short) TrackCount)); v.Add (ByteVector.FromShort (0)); SetData (FixId ("trkn"), v, (int) AppleDataBox.FlagTypes.ContainsData); } } public override uint TrackCount { get { AppleDataBox [] boxes = DataBoxes (FixId ("trkn")); if (boxes.Length != 0 && boxes [0].Flags == (int) AppleDataBox.FlagTypes.ContainsData && boxes [0].Data.Count >=6) return (uint) boxes [0].Data.Mid (4, 2).ToShort (); return 0; } set { ByteVector v = new ByteVector (); v += ByteVector.FromShort (0); v += ByteVector.FromShort ((short) Track); v += ByteVector.FromShort ((short) value); v += ByteVector.FromShort (0); SetData (FixId ("trkn"), v, (int) AppleDataBox.FlagTypes.ContainsData); } } public override uint Disc { get { AppleDataBox [] boxes = DataBoxes (FixId ("disk")); if (boxes.Length != 0 && boxes [0].Flags == (int) AppleDataBox.FlagTypes.ContainsData && boxes [0].Data.Count >=4) return (uint) boxes [0].Data.Mid (2, 2).ToShort (); return 0; } set { ByteVector v = new ByteVector (); v += ByteVector.FromShort (0); v += ByteVector.FromShort ((short) value); v += ByteVector.FromShort ((short) DiscCount); v += ByteVector.FromShort (0); SetData (FixId ("disk"), v, (int) AppleDataBox.FlagTypes.ContainsData); } } public override uint DiscCount { get { AppleDataBox [] boxes = DataBoxes (FixId ("disk")); if (boxes.Length != 0 && boxes [0].Flags == (int) AppleDataBox.FlagTypes.ContainsData && boxes [0].Data.Count >=6) return (uint) boxes [0].Data.Mid (4, 2).ToShort (); return 0; } set { ByteVector v = new ByteVector (); v += ByteVector.FromShort (0); v += ByteVector.FromShort ((short) Disc); v += ByteVector.FromShort ((short) value); v += ByteVector.FromShort (0); SetData (FixId ("disk"), v, (int) AppleDataBox.FlagTypes.ContainsData); } } public override IPicture [] Pictures { get { List<Picture> l = new List<Picture> (); foreach (AppleDataBox box in DataBoxes(FixId("covr"))) { string type = null; string desc = null; if (box.Flags == (int) AppleDataBox.FlagTypes.ContainsJpegData) { type = "image/jpeg"; desc = "cover.jpg"; } else if (box.Flags == (int) AppleDataBox.FlagTypes.ContainsPngData) { type = "image/png"; desc = "cover.png"; } else continue; Picture p = new Picture (); p.Type = PictureType.FrontCover; p.Data = box.Data; p.MimeType = type; p.Description = desc; l.Add (p); } return (Picture []) l.ToArray (); } set { if (value == null || value.Length == 0) { ClearData ("covr"); return; } AppleDataBox [] boxes = new AppleDataBox [value.Length]; for (int i = 0; i < value.Length; i ++) { uint type = (uint) AppleDataBox.FlagTypes.ContainsData; if (value [i].MimeType == "image/jpeg") type = (uint) AppleDataBox.FlagTypes.ContainsJpegData; else if (value [i].MimeType == "image/png") type = (uint) AppleDataBox.FlagTypes.ContainsPngData; boxes [i] = new AppleDataBox (value [i].Data, type); } SetData("covr", boxes); } } ////////////////////////////////////////////////////////////////////////// // private methods ////////////////////////////////////////////////////////////////////////// private ByteVector FixId (ByteVector v) { // IF we have a three byte type (like "wrt"), add the extra byte. if (v.Count == 3) v.Insert (0, 0xa9); return v; } } }
namespace Mapbox.Utils { using System; using System.Runtime.CompilerServices; public struct Mathd { public const double PI = 3.141593d; public const double Infinity = double.PositiveInfinity; public const double NegativeInfinity = double.NegativeInfinity; public const double Deg2Rad = 0.01745329d; public const double Rad2Deg = 57.29578d; public const double Epsilon = 1.401298E-45d; public static double Sin(double d) { return Math.Sin(d); } public static double Cos(double d) { return Math.Cos(d); } public static double Tan(double d) { return Math.Tan(d); } public static double Asin(double d) { return Math.Asin(d); } public static double Acos(double d) { return Math.Acos(d); } public static double Atan(double d) { return Math.Atan(d); } public static double Atan2(double y, double x) { return Math.Atan2(y, x); } public static double Sqrt(double d) { return Math.Sqrt(d); } public static double Abs(double d) { return Math.Abs(d); } public static int Abs(int value) { return Math.Abs(value); } public static double Min(double a, double b) { if (a < b) return a; else return b; } public static double Min(params double[] values) { int length = values.Length; if (length == 0) return 0.0d; double num = values[0]; for (int index = 1; index < length; ++index) { if (values[index] < num) num = values[index]; } return num; } public static int Min(int a, int b) { if (a < b) return a; else return b; } public static int Min(params int[] values) { int length = values.Length; if (length == 0) return 0; int num = values[0]; for (int index = 1; index < length; ++index) { if (values[index] < num) num = values[index]; } return num; } public static double Max(double a, double b) { if (a > b) return a; else return b; } public static double Max(params double[] values) { int length = values.Length; if (length == 0) return 0d; double num = values[0]; for (int index = 1; index < length; ++index) { if ((double)values[index] > (double)num) num = values[index]; } return num; } public static int Max(int a, int b) { if (a > b) return a; else return b; } public static int Max(params int[] values) { int length = values.Length; if (length == 0) return 0; int num = values[0]; for (int index = 1; index < length; ++index) { if (values[index] > num) num = values[index]; } return num; } public static double Pow(double d, double p) { return Math.Pow(d, p); } public static double Exp(double power) { return Math.Exp(power); } public static double Log(double d, double p) { return Math.Log(d, p); } public static double Log(double d) { return Math.Log(d); } public static double Log10(double d) { return Math.Log10(d); } public static double Ceil(double d) { return Math.Ceiling(d); } public static double Floor(double d) { return Math.Floor(d); } public static double Round(double d) { return Math.Round(d); } public static int CeilToInt(double d) { return (int)Math.Ceiling(d); } public static int FloorToInt(double d) { return (int)Math.Floor(d); } public static int RoundToInt(double d) { return (int)Math.Round(d); } public static double Sign(double d) { return d >= 0.0 ? 1d : -1d; } public static double Clamp(double value, double min, double max) { if (value < min) value = min; else if (value > max) value = max; return value; } public static int Clamp(int value, int min, int max) { if (value < min) value = min; else if (value > max) value = max; return value; } public static double Clamp01(double value) { if (value < 0.0) return 0.0d; if (value > 1.0) return 1d; else return value; } public static double Lerp(double from, double to, double t) { return from + (to - from) * Mathd.Clamp01(t); } public static double LerpAngle(double a, double b, double t) { double num = Mathd.Repeat(b - a, 360d); if (num > 180.0d) num -= 360d; return a + num * Mathd.Clamp01(t); } public static double MoveTowards(double current, double target, double maxDelta) { if (Mathd.Abs(target - current) <= maxDelta) return target; else return current + Mathd.Sign(target - current) * maxDelta; } public static double MoveTowardsAngle(double current, double target, double maxDelta) { target = current + Mathd.DeltaAngle(current, target); return Mathd.MoveTowards(current, target, maxDelta); } public static double SmoothStep(double from, double to, double t) { t = Mathd.Clamp01(t); t = (-2.0 * t * t * t + 3.0 * t * t); return to * t + from * (1.0 - t); } public static double Gamma(double value, double absmax, double gamma) { bool flag = false; if (value < 0.0) flag = true; double num1 = Mathd.Abs(value); if (num1 > absmax) { if (flag) return -num1; else return num1; } else { double num2 = Mathd.Pow(num1 / absmax, gamma) * absmax; if (flag) return -num2; else return num2; } } public static bool Approximately(double a, double b) { return Mathd.Abs(b - a) < Mathd.Max(1E-06d * Mathd.Max(Mathd.Abs(a), Mathd.Abs(b)), 1.121039E-44d); } public static double SmoothDamp(double current, double target, ref double currentVelocity, double smoothTime, double maxSpeed, double deltaTime) { smoothTime = Mathd.Max(0.0001d, smoothTime); double num1 = 2d / smoothTime; double num2 = num1 * deltaTime; double num3 = (1.0d / (1.0d + num2 + 0.479999989271164d * num2 * num2 + 0.234999999403954d * num2 * num2 * num2)); double num4 = current - target; double num5 = target; double max = maxSpeed * smoothTime; double num6 = Mathd.Clamp(num4, -max, max); target = current - num6; double num7 = (currentVelocity + num1 * num6) * deltaTime; currentVelocity = (currentVelocity - num1 * num7) * num3; double num8 = target + (num6 + num7) * num3; if (num5 - current > 0.0 == num8 > num5) { num8 = num5; currentVelocity = (num8 - num5) / deltaTime; } return num8; } public static double SmoothDampAngle(double current, double target, ref double currentVelocity, double smoothTime, double maxSpeed, double deltaTime) { target = current + Mathd.DeltaAngle(current, target); return Mathd.SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } public static double Repeat(double t, double length) { return t - Mathd.Floor(t / length) * length; } public static double PingPong(double t, double length) { t = Mathd.Repeat(t, length * 2d); return length - Mathd.Abs(t - length); } public static double InverseLerp(double from, double to, double value) { if (from < to) { if (value < from) return 0d; if (value > to) return 1d; value -= from; value /= to - from; return value; } else { if (from <= to) return 0d; if (value < to) return 1d; if (value > from) return 0d; else return (1.0d - (value - to) / (from - to)); } } public static double DeltaAngle(double current, double target) { double num = Mathd.Repeat(target - current, 360d); if (num > 180.0d) num -= 360d; return num; } internal static bool LineIntersection(Vector2d p1, Vector2d p2, Vector2d p3, Vector2d p4, ref Vector2d result) { double num1 = p2.x - p1.x; double num2 = p2.y - p1.y; double num3 = p4.x - p3.x; double num4 = p4.y - p3.y; double num5 = num1 * num4 - num2 * num3; if (num5 == 0.0d) return false; double num6 = p3.x - p1.x; double num7 = p3.y - p1.y; double num8 = (num6 * num4 - num7 * num3) / num5; result = new Vector2d(p1.x + num8 * num1, p1.y + num8 * num2); return true; } internal static bool LineSegmentIntersection(Vector2d p1, Vector2d p2, Vector2d p3, Vector2d p4, ref Vector2d result) { double num1 = p2.x - p1.x; double num2 = p2.y - p1.y; double num3 = p4.x - p3.x; double num4 = p4.y - p3.y; double num5 = (num1 * num4 - num2 * num3); if (num5 == 0.0d) return false; double num6 = p3.x - p1.x; double num7 = p3.y - p1.y; double num8 = (num6 * num4 - num7 * num3) / num5; if (num8 < 0.0d || num8 > 1.0d) return false; double num9 = (num6 * num2 - num7 * num1) / num5; if (num9 < 0.0d || num9 > 1.0d) return false; result = new Vector2d(p1.x + num8 * num1, p1.y + num8 * num2); return true; } } }
// 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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.Spellcheck; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.SpellCheck { public class SpellCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>(null, new CSharpSpellCheckCodeFixProvider()); } protected override IList<CodeAction> MassageActions(IList<CodeAction> actions) => FlattenActions(actions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestNoSpellcheckForIfOnly2Characters() { var text = @"class Foo { void Bar() { var a = new [|Fo|] } }"; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestAfterNewExpression() { var text = @"class Foo { void Bar() { void a = new [|Fooa|].ToString(); } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Fooa", "Foo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInLocalType() { var text = @"class Foo { void Bar() { [|Foa|] a; } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Foa", "Foo"), String.Format(FeaturesResources.Change_0_to_1, "Foa", "for") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInFunc() { var text = @" using System; class Foo { void Bar(Func<[|Foa|]> f) { } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Foa", "Foo") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInExpression() { var text = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + [|zza|]; } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "zza", "zzz") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInTypeOfIsExpression() { var text = @"using System; public class Class1 { void F() { if (x is [|Boolea|]) {} } }"; await TestExactActionSetOfferedAsync(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Boolea", "Boolean"), String.Format(FeaturesResources.Change_0_to_1, "Boolea", "bool") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestInvokeCorrectIdentifier() { var text = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + [|zza|]; } }"; var expected = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + zzz; } }"; await TestAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestAfterDot() { var text = @"class Program { static void Main(string[] args) { Program.[|Mair|] } }"; var expected = @"class Program { static void Main(string[] args) { Program.Main } }"; await TestAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestNotInaccessibleProperty() { var text = @"class Program { void Main(string[] args) { var z = new c().[|membr|] } } class c { protected int member { get; } }"; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestGenericName1() { var text = @"class Foo<T> { private [|Foo2|]<T> x; }"; var expected = @"class Foo<T> { private Foo<T> x; }"; await TestAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestGenericName2() { var text = @"class Foo<T> { private [|Foo2|] x; }"; var expected = @"class Foo<T> { private Foo x; }"; await TestAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestQualifiedName1() { var text = @"class Program { private object x = new [|Foo2|].Bar } class Foo { class Bar { } }"; var expected = @"class Program { private object x = new Foo.Bar } class Foo { class Bar { } }"; await TestAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestQualifiedName2() { var text = @"class Program { private object x = new Foo.[|Ba2|] } class Foo { public class Bar { } }"; var expected = @"class Program { private object x = new Foo.Bar } class Foo { public class Bar { } }"; await TestAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestMiddleOfDottedExpression() { var text = @"class Program { void Main(string[] args) { var z = new c().[|membr|].ToString(); } } class c { public int member { get; } }"; var expected = @"class Program { void Main(string[] args) { var z = new c().member.ToString(); } } class c { public int member { get; } }"; await TestAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestNotForOverloadResolutionFailure() { var text = @"class Program { void Main(string[] args) { } void Foo() { [|Method|](); } int Method(int argument) { } }"; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestHandlePredefinedTypeKeywordCorrectly() { var text = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { [|Int3|] i; } }"; var expected = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { int i; } }"; await TestAsync(text, expected, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestHandlePredefinedTypeKeywordCorrectly1() { var text = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { [|Int3|] i; } }"; var expected = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { Int32 i; } }"; await TestAsync(text, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestOnGeneric() { var text = @" interface Enumerable<T> { } class C { void Main(string[] args) { [|IEnumerable|]<int> x; } }"; var expected = @" interface Enumerable<T> { } class C { void Main(string[] args) { Enumerable<int> x; } }"; await TestAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestTestObjectConstruction() { await TestAsync( @"class AwesomeClass { void M() { var foo = new [|AwesomeClas()|]; } }", @"class AwesomeClass { void M() { var foo = new AwesomeClass(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] public async Task TestTestMissingName() { await TestMissingAsync( @"[assembly: Microsoft.CodeAnalysis.[||]]"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] [WorkItem(12990, "https://github.com/dotnet/roslyn/issues/12990")] public async Task TestTrivia1() { var text = @" using System.Text; class C { void M() { /*leading*/ [|stringbuilder|] /*trailing*/ sb = null; } }"; var expected = @" using System.Text; class C { void M() { /*leading*/ StringBuilder /*trailing*/ sb = null; } }"; await TestAsync(text, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] [WorkItem(13345, "https://github.com/dotnet/roslyn/issues/13345")] public async Task TestNotMissingOnKeywordWhichIsAlsoASnippet() { await TestAsync( @"class C { void M() { // here 'for' is a keyword and snippet, so we should offer to spell check to it. [|foo|]; } }", @"class C { void M() { // here 'for' is a keyword and snippet, so we should offer to spell check to it. for; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSpellcheck)] [WorkItem(13345, "https://github.com/dotnet/roslyn/issues/13345")] public async Task TestMissingOnKeywordWhichIsOnlyASnippet() { await TestMissingAsync( @"class C { void M() { // here 'for' is *only* a snippet, and we should not offer to spell check to it. var v = [|foo|]; } }"); } } }
// 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: Holds state about A/G/R permissionsets in a callstack or appdomain ** (Replacement for PermissionListSet) ** =============================================================================*/ namespace System.Security { using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] sealed internal class PermissionListSet { // Only internal (public) methods are creation methods and demand evaluation methods. // Scroll down to the end to see them. private PermissionSetTriple m_firstPermSetTriple; private ArrayList m_permSetTriples; internal PermissionListSet() {} private void EnsureTriplesListCreated() { if (m_permSetTriples == null) { m_permSetTriples = new ArrayList(); if (m_firstPermSetTriple != null) { m_permSetTriples.Add(m_firstPermSetTriple); m_firstPermSetTriple = null; } } } private void Terminate(PermissionSetTriple currentTriple) { UpdateTripleListAndCreateNewTriple(currentTriple, null); } private void Terminate(PermissionSetTriple currentTriple, PermissionListSet pls) { this.UpdatePermissions(currentTriple, pls); this.UpdateTripleListAndCreateNewTriple(currentTriple, null); } private bool Update(PermissionSetTriple currentTriple, PermissionListSet pls) { return this.UpdatePermissions(currentTriple, pls); } private bool Update(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd) { // check imperative bool fHalt = Update2(currentTriple, fsd, false); if (!fHalt) { // then declarative fHalt = Update2(currentTriple, fsd, true); } return fHalt; } private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative) { // Deny PermissionSet deniedPset = fsd.GetDenials(fDeclarative); if (deniedPset != null) { currentTriple.UpdateRefused(deniedPset); } // permit only PermissionSet permitOnlyPset = fsd.GetPermitOnly(fDeclarative); if (permitOnlyPset != null) { currentTriple.UpdateGrant(permitOnlyPset); } // Assert all possible if (fsd.GetAssertAllPossible()) { // If we have no grant set, it means that the only assembly we've seen on the stack so // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the // compressed stack is also FullTrust. if (currentTriple.GrantSet == null) currentTriple.GrantSet = PermissionSet.s_fullTrust; UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples); currentTriple.GrantSet = PermissionSet.s_fullTrust; currentTriple.UpdateAssert(fsd.GetAssertions(fDeclarative)); return true; } // Assert PermissionSet assertPset = fsd.GetAssertions(fDeclarative); if (assertPset != null) { if (assertPset.IsUnrestricted()) { // If we have no grant set, it means that the only assembly we've seen on the stack so // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the // compressed stack is also FullTrust. if (currentTriple.GrantSet == null) currentTriple.GrantSet = PermissionSet.s_fullTrust; UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples); currentTriple.GrantSet = PermissionSet.s_fullTrust; currentTriple.UpdateAssert(assertPset); return true; } PermissionSetTriple retTriple = currentTriple.UpdateAssert(assertPset); if (retTriple != null) { EnsureTriplesListCreated(); m_permSetTriples.Add(retTriple); } } return false; } private void Update(PermissionSetTriple currentTriple, PermissionSet in_g, PermissionSet in_r) { currentTriple.UpdateGrant(in_g); currentTriple.UpdateRefused(in_r); } // Called from the VM for HG CS construction private void Update(PermissionSet in_g) { if (m_firstPermSetTriple == null) m_firstPermSetTriple = new PermissionSetTriple(); Update(m_firstPermSetTriple, in_g, null); } private bool UpdatePermissions(PermissionSetTriple currentTriple, PermissionListSet pls) { if (pls != null) { if (pls.m_permSetTriples != null) { // DCS has an AGR List. So we need to add the AGR List UpdateTripleListAndCreateNewTriple(currentTriple,pls.m_permSetTriples); } else { // Common case: One AGR set PermissionSetTriple tmp_psTriple = pls.m_firstPermSetTriple; PermissionSetTriple retTriple; // First try and update currentTriple. Return value indicates if we can stop construction if (currentTriple.Update(tmp_psTriple, out retTriple)) return true; // If we got a non-null retTriple, what it means is that compression failed, // and we now have 2 triples to deal with: retTriple and currentTriple. // retTriple has to be appended first. then currentTriple. if (retTriple != null) { EnsureTriplesListCreated(); // we just created a new triple...add the previous one (returned) to the list m_permSetTriples.Add(retTriple); } } } else { // pls can be null only outside the loop in CreateCompressedState UpdateTripleListAndCreateNewTriple(currentTriple, null); } return false; } private void UpdateTripleListAndCreateNewTriple(PermissionSetTriple currentTriple, ArrayList tripleList) { if (!currentTriple.IsEmpty()) { if (m_firstPermSetTriple == null && m_permSetTriples == null) { m_firstPermSetTriple = new PermissionSetTriple(currentTriple); } else { EnsureTriplesListCreated(); m_permSetTriples.Add(new PermissionSetTriple(currentTriple)); } currentTriple.Reset(); } if (tripleList != null) { EnsureTriplesListCreated(); m_permSetTriples.AddRange(tripleList); } } private static void UpdateArrayList(ArrayList current, ArrayList newList) { if (newList == null) return; for(int i=0;i < newList.Count; i++) { if (!current.Contains(newList[i])) current.Add(newList[i]); } } // Private Demand evaluation functions - only called from the VM internal bool CheckDemandNoThrow(CodeAccessPermission demand) { // AppDomain permissions - no asserts. So there should only be one triple to work with Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); PermissionToken permToken = null; if (demand != null) permToken = PermissionToken.GetToken(demand); return m_firstPermSetTriple.CheckDemandNoThrow(demand, permToken); } internal bool CheckSetDemandNoThrow(PermissionSet pSet) { // AppDomain permissions - no asserts. So there should only be one triple to work with Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet); } // Demand evauation functions internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) { bool bRet = SecurityRuntime.StackContinue; if (m_permSetTriples != null) { for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++) { PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i]; bRet = psTriple.CheckDemand(demand, permToken, rmh); } } else if (m_firstPermSetTriple != null) { bRet = m_firstPermSetTriple.CheckDemand(demand, permToken, rmh); } return bRet; } internal bool CheckSetDemand(PermissionSet pset , RuntimeMethodHandleInternal rmh) { PermissionSet unused; CheckSetDemandWithModification(pset, out unused, rmh); return SecurityRuntime.StackHalt; // CS demand check always terminates the stackwalk } internal bool CheckSetDemandWithModification(PermissionSet pset, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh) { bool bRet = SecurityRuntime.StackContinue; PermissionSet demandSet = pset; alteredDemandSet = null; if (m_permSetTriples != null) { for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++) { PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i]; bRet = psTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh); if (alteredDemandSet != null) demandSet = alteredDemandSet; } } else if (m_firstPermSetTriple != null) { bRet = m_firstPermSetTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh); } return bRet; } /// <summary> /// Check to see if the PLS satisfies a demand for the special permissions encoded in flags /// </summary> /// <param name="flags">set of flags to check (See PermissionType)</param> private bool CheckFlags(int flags) { Debug.Assert(flags != 0, "Invalid permission flag demand"); bool check = true; if (m_permSetTriples != null) { for (int i = 0; i < m_permSetTriples.Count && check && flags != 0; i++) { check &= ((PermissionSetTriple)m_permSetTriples[i]).CheckFlags(ref flags); } } else if (m_firstPermSetTriple != null) { check = m_firstPermSetTriple.CheckFlags(ref flags); } return check; } /// <summary> /// Demand which succeeds if either a set of special permissions or a permission set is granted /// to the call stack /// </summary> /// <param name="flags">set of flags to check (See PermissionType)</param> /// <param name="grantSet">alternate permission set to check</param> internal void DemandFlagsOrGrantSet(int flags, PermissionSet grantSet) { if (CheckFlags(flags)) return; CheckSetDemand(grantSet, RuntimeMethodHandleInternal.EmptyHandle); } } }
using System; using System.Data; using System.Data.Common; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Core.Objects; using System.Linq; using System.Linq.Dynamic; using System.Linq.Expressions; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using EntityFramework.Extensions; using EntityFramework.Mapping; using EntityFramework.Reflection; namespace EntityFramework.Batch { /// <summary> /// A batch execution runner for SQL Server. /// </summary> public class SqlServerBatchRunner : IBatchRunner { /// <summary> /// Create and run a batch delete statement. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param> /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param> /// <param name="query">The query to create the where clause from.</param> /// <returns> /// The number of rows deleted. /// </returns> public int Delete<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query) where TEntity : class { #if NET45 return InternalDelete(objectContext, entityMap, query, false).Result; #else return InternalDelete(objectContext, entityMap, query); #endif } #if NET45 /// <summary> /// Create and run a batch delete statement asynchronously. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param> /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param> /// <param name="query">The query to create the where clause from.</param> /// <returns> /// The number of rows deleted. /// </returns> public Task<int> DeleteAsync<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query) where TEntity : class { return InternalDelete(objectContext, entityMap, query, true); } #endif #if NET45 private async Task<int> InternalDelete<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query, bool async = false) where TEntity : class #else private int InternalDelete<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query) where TEntity : class #endif { DbConnection deleteConnection = null; DbTransaction deleteTransaction = null; DbCommand deleteCommand = null; bool ownConnection = false; bool ownTransaction = false; try { // get store connection and transaction var store = GetStore(objectContext); deleteConnection = store.Item1; deleteTransaction = store.Item2; if (deleteConnection.State != ConnectionState.Open) { deleteConnection.Open(); ownConnection = true; } if (deleteTransaction == null) { deleteTransaction = deleteConnection.BeginTransaction(); ownTransaction = true; } deleteCommand = deleteConnection.CreateCommand(); deleteCommand.Transaction = deleteTransaction; if (objectContext.CommandTimeout.HasValue) deleteCommand.CommandTimeout = objectContext.CommandTimeout.Value; var innerSelect = GetSelectSql(query, entityMap, deleteCommand); var sqlBuilder = new StringBuilder(innerSelect.Length * 2); sqlBuilder.Append("DELETE "); sqlBuilder.Append(entityMap.TableName); sqlBuilder.AppendLine(); sqlBuilder.AppendFormat("FROM {0} AS j0 INNER JOIN (", entityMap.TableName); sqlBuilder.AppendLine(); sqlBuilder.AppendLine(innerSelect); sqlBuilder.Append(") AS j1 ON ("); bool wroteKey = false; foreach (var keyMap in entityMap.KeyMaps) { if (wroteKey) sqlBuilder.Append(" AND "); sqlBuilder.AppendFormat("j0.[{0}] = j1.[{0}]", keyMap.ColumnName); wroteKey = true; } sqlBuilder.Append(")"); deleteCommand.CommandText = sqlBuilder.ToString(); #if NET45 int result = async ? await deleteCommand.ExecuteNonQueryAsync().ConfigureAwait(false) : deleteCommand.ExecuteNonQuery(); #else int result = deleteCommand.ExecuteNonQuery(); #endif // only commit if created transaction if (ownTransaction) deleteTransaction.Commit(); return result; } finally { if (deleteCommand != null) deleteCommand.Dispose(); if (deleteTransaction != null && ownTransaction) deleteTransaction.Dispose(); if (deleteConnection != null && ownConnection) deleteConnection.Close(); } } /// <summary> /// Create and run a batch update statement. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param> /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param> /// <param name="query">The query to create the where clause from.</param> /// <param name="updateExpression">The update expression.</param> /// <returns> /// The number of rows updated. /// </returns> public int Update<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query, Expression<Func<TEntity, TEntity>> updateExpression) where TEntity : class { #if NET45 return InternalUpdate(objectContext, entityMap, query, updateExpression, false).Result; #else return InternalUpdate(objectContext, entityMap, query, updateExpression); #endif } #if NET45 /// <summary> /// Create and run a batch update statement asynchronously. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param> /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param> /// <param name="query">The query to create the where clause from.</param> /// <param name="updateExpression">The update expression.</param> /// <returns> /// The number of rows updated. /// </returns> public Task<int> UpdateAsync<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query, Expression<Func<TEntity, TEntity>> updateExpression) where TEntity : class { return InternalUpdate(objectContext, entityMap, query, updateExpression, true); } #endif #if NET45 private async Task<int> InternalUpdate<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query, Expression<Func<TEntity, TEntity>> updateExpression, bool async = false) where TEntity : class #else private int InternalUpdate<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query, Expression<Func<TEntity, TEntity>> updateExpression, bool async = false) where TEntity : class #endif { DbConnection updateConnection = null; DbTransaction updateTransaction = null; DbCommand updateCommand = null; bool ownConnection = false; bool ownTransaction = false; try { // get store connection and transaction var store = GetStore(objectContext); updateConnection = store.Item1; updateTransaction = store.Item2; if (updateConnection.State != ConnectionState.Open) { updateConnection.Open(); ownConnection = true; } // use existing transaction or create new if (updateTransaction == null) { updateTransaction = updateConnection.BeginTransaction(); ownTransaction = true; } updateCommand = updateConnection.CreateCommand(); updateCommand.Transaction = updateTransaction; if (objectContext.CommandTimeout.HasValue) updateCommand.CommandTimeout = objectContext.CommandTimeout.Value; var innerSelect = GetSelectSql(query, entityMap, updateCommand); var sqlBuilder = new StringBuilder(innerSelect.Length * 2); sqlBuilder.Append("UPDATE "); sqlBuilder.Append(entityMap.TableName); sqlBuilder.AppendLine(" SET "); var memberInitExpression = updateExpression.Body as MemberInitExpression; if (memberInitExpression == null) throw new ArgumentException("The update expression must be of type MemberInitExpression.", "updateExpression"); int nameCount = 0; bool wroteSet = false; foreach (MemberBinding binding in memberInitExpression.Bindings) { if (wroteSet) sqlBuilder.AppendLine(", "); string propertyName = binding.Member.Name; string columnName = entityMap.PropertyMaps .Where(p => p.PropertyName == propertyName) .Select(p => p.ColumnName) .FirstOrDefault(); var memberAssignment = binding as MemberAssignment; if (memberAssignment == null) throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression"); Expression memberExpression = memberAssignment.Expression; ParameterExpression parameterExpression = null; memberExpression.Visit((ParameterExpression p) => { if (p.Type == entityMap.EntityType) parameterExpression = p; return p; }); if (parameterExpression == null) { object value; if (memberExpression.NodeType == ExpressionType.Constant) { var constantExpression = memberExpression as ConstantExpression; if (constantExpression == null) throw new ArgumentException( "The MemberAssignment expression is not a ConstantExpression.", "updateExpression"); value = constantExpression.Value; } else { LambdaExpression lambda = Expression.Lambda(memberExpression, null); value = lambda.Compile().DynamicInvoke(); } if (value != null) { string parameterName = "p__update__" + nameCount++; var parameter = updateCommand.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = value; updateCommand.Parameters.Add(parameter); sqlBuilder.AppendFormat("[{0}] = @{1}", columnName, parameterName); } else { sqlBuilder.AppendFormat("[{0}] = NULL", columnName); } } else { // create clean objectset to build query from var objectSet = objectContext.CreateObjectSet<TEntity>(); Type[] typeArguments = new[] { entityMap.EntityType, memberExpression.Type }; ConstantExpression constantExpression = Expression.Constant(objectSet); LambdaExpression lambdaExpression = Expression.Lambda(memberExpression, parameterExpression); MethodCallExpression selectExpression = Expression.Call( typeof(Queryable), "Select", typeArguments, constantExpression, lambdaExpression); // create query from expression var selectQuery = objectSet.CreateQuery(selectExpression, entityMap.EntityType); string sql = selectQuery.ToTraceString(); // parse select part of sql to use as update string regex = @"SELECT\s*\r\n\s*(?<ColumnValue>.+)?\s*AS\s*(?<ColumnAlias>\[\w+\])\r\n\s*FROM\s*(?<TableName>\[\w+\]\.\[\w+\]|\[\w+\])\s*AS\s*(?<TableAlias>\[\w+\])"; Match match = Regex.Match(sql, regex); if (!match.Success) throw new ArgumentException("The MemberAssignment expression could not be processed.", "updateExpression"); string value = match.Groups["ColumnValue"].Value; string alias = match.Groups["TableAlias"].Value; value = value.Replace(alias + ".", ""); foreach (ObjectParameter objectParameter in selectQuery.Parameters) { string parameterName = "p__update__" + nameCount++; var parameter = updateCommand.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = objectParameter.Value ?? DBNull.Value; updateCommand.Parameters.Add(parameter); value = value.Replace(objectParameter.Name, parameterName); } sqlBuilder.AppendFormat("[{0}] = {1}", columnName, value); } wroteSet = true; } sqlBuilder.AppendLine(" "); sqlBuilder.AppendFormat("FROM {0} AS j0 INNER JOIN (", entityMap.TableName); sqlBuilder.AppendLine(); sqlBuilder.AppendLine(innerSelect); sqlBuilder.Append(") AS j1 ON ("); bool wroteKey = false; foreach (var keyMap in entityMap.KeyMaps) { if (wroteKey) sqlBuilder.Append(" AND "); sqlBuilder.AppendFormat("j0.[{0}] = j1.[{0}]", keyMap.ColumnName); wroteKey = true; } sqlBuilder.Append(")"); updateCommand.CommandText = sqlBuilder.ToString(); #if NET45 int result = async ? await updateCommand.ExecuteNonQueryAsync().ConfigureAwait(false) : updateCommand.ExecuteNonQuery(); #else int result = updateCommand.ExecuteNonQuery(); #endif // only commit if created transaction if (ownTransaction) updateTransaction.Commit(); return result; } finally { if (updateCommand != null) updateCommand.Dispose(); if (updateTransaction != null && ownTransaction) updateTransaction.Dispose(); if (updateConnection != null && ownConnection) updateConnection.Close(); } } private static Tuple<DbConnection, DbTransaction> GetStore(ObjectContext objectContext) { // TODO, re-eval if this is needed DbConnection dbConnection = objectContext.Connection; var entityConnection = dbConnection as EntityConnection; // by-pass entity connection if (entityConnection == null) return new Tuple<DbConnection, DbTransaction>(dbConnection, null); DbConnection connection = entityConnection.StoreConnection; // get internal transaction dynamic connectionProxy = new DynamicProxy(entityConnection); dynamic entityTransaction = connectionProxy.CurrentTransaction; if (entityTransaction == null) return new Tuple<DbConnection, DbTransaction>(connection, null); DbTransaction transaction = entityTransaction.StoreTransaction; return new Tuple<DbConnection, DbTransaction>(connection, transaction); } private static string GetSelectSql<TEntity>(ObjectQuery<TEntity> query, EntityMap entityMap, DbCommand command) where TEntity : class { // TODO change to esql? // changing query to only select keys var selector = new StringBuilder(50); selector.Append("new("); foreach (var propertyMap in entityMap.KeyMaps) { if (selector.Length > 4) selector.Append((", ")); selector.Append(propertyMap.PropertyName); } selector.Append(")"); var selectQuery = DynamicQueryable.Select(query, selector.ToString()); var objectQuery = selectQuery as ObjectQuery; if (objectQuery == null) throw new ArgumentException("The query must be of type ObjectQuery.", "query"); string innerJoinSql = objectQuery.ToTraceString(); // create parameters foreach (var objectParameter in objectQuery.Parameters) { var parameter = command.CreateParameter(); parameter.ParameterName = objectParameter.Name; parameter.Value = objectParameter.Value ?? DBNull.Value; command.Parameters.Add(parameter); } return innerJoinSql; } } }
// 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.ComponentModel.Composition.Hosting; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.CSharp.CallHierarchy; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy; using Microsoft.CodeAnalysis.Editor.Implementation.Notification; using Microsoft.CodeAnalysis.Editor.SymbolMapping; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.Language.CallHierarchy; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy { public class CallHierarchyTestState { private readonly CallHierarchyCommandHandler _commandHandler; private readonly MockCallHierarchyPresenter _presenter; internal TestWorkspace Workspace; private readonly ITextBuffer _subjectBuffer; private readonly IWpfTextView _textView; private class MockCallHierarchyPresenter : ICallHierarchyPresenter { public CallHierarchyItem PresentedRoot; public void PresentRoot(CallHierarchyItem root) { this.PresentedRoot = root; } } private class MockSearchCallback : ICallHierarchySearchCallback { private readonly Action<CallHierarchyItem> _verifyMemberItem; private readonly TaskCompletionSource<object> _completionSource = new TaskCompletionSource<object>(); private readonly Action<ICallHierarchyNameItem> _verifyNameItem; public MockSearchCallback(Action<CallHierarchyItem> verify) { _verifyMemberItem = verify; } public MockSearchCallback(Action<ICallHierarchyNameItem> verify) { _verifyNameItem = verify; } public void AddResult(ICallHierarchyNameItem item) { _verifyNameItem(item); } public void AddResult(ICallHierarchyMemberItem item) { _verifyMemberItem((CallHierarchyItem)item); } public void InvalidateResults() { } public void ReportProgress(int current, int maximum) { } public void SearchFailed(string message) { _completionSource.SetException(new Exception(message)); } public void SearchSucceeded() { _completionSource.SetResult(null); } internal void WaitForCompletion() { _completionSource.Task.Wait(); } } public static async Task<CallHierarchyTestState> CreateAsync(XElement markup, params Type[] additionalTypes) { var exportProvider = CreateExportProvider(additionalTypes); var workspace = await TestWorkspace.CreateAsync(markup, exportProvider: exportProvider); return new CallHierarchyTestState(workspace); } private CallHierarchyTestState(TestWorkspace workspace) { this.Workspace = workspace; var testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue); _textView = testDocument.GetTextView(); _subjectBuffer = testDocument.GetTextBuffer(); var provider = Workspace.GetService<CallHierarchyProvider>(); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; _presenter = new MockCallHierarchyPresenter(); _commandHandler = new CallHierarchyCommandHandler(new[] { _presenter }, provider, TestWaitIndicator.Default); } private static VisualStudio.Composition.ExportProvider CreateExportProvider(Type[] additionalTypes) { var catalog = TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic .WithPart(typeof(CallHierarchyProvider)) .WithPart(typeof(SymbolMappingServiceFactory)) .WithPart(typeof(EditorNotificationServiceFactory)) .WithParts(additionalTypes); return MinimalTestExportProvider.CreateExportProvider(catalog); } public static async Task<CallHierarchyTestState> CreateAsync(string markup, params Type[] additionalTypes) { var exportProvider = CreateExportProvider(additionalTypes); var workspace = await TestWorkspace.CreateCSharpAsync(markup, exportProvider: exportProvider); return new CallHierarchyTestState(markup, workspace); } private CallHierarchyTestState(string markup, TestWorkspace workspace) { this.Workspace = workspace; var testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue); _textView = testDocument.GetTextView(); _subjectBuffer = testDocument.GetTextBuffer(); var provider = Workspace.GetService<CallHierarchyProvider>(); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; _presenter = new MockCallHierarchyPresenter(); _commandHandler = new CallHierarchyCommandHandler(new[] { _presenter }, provider, TestWaitIndicator.Default); } internal string NotificationMessage { get; private set; } internal CallHierarchyItem GetRoot() { var args = new ViewCallHierarchyCommandArgs(_textView, _subjectBuffer); _commandHandler.ExecuteCommand(args, () => { }); return _presenter.PresentedRoot; } internal IImmutableSet<Document> GetDocuments(string[] documentNames) { var selectedDocuments = new List<Document>(); this.Workspace.CurrentSolution.Projects.Do(p => p.Documents.Where(d => documentNames.Contains(d.Name)).Do(d => selectedDocuments.Add(d))); return ImmutableHashSet.CreateRange<Document>(selectedDocuments); } internal void SearchRoot(CallHierarchyItem root, string displayName, Action<CallHierarchyItem> verify, CallHierarchySearchScope scope, IImmutableSet<Document> documents = null) { var callback = new MockSearchCallback(verify); var category = root.SupportedSearchCategories.First(c => c.DisplayName == displayName).Name; if (documents != null) { root.StartSearchWithDocuments(category, scope, callback, documents); } else { root.StartSearch(category, scope, callback); } callback.WaitForCompletion(); } internal void SearchRoot(CallHierarchyItem root, string displayName, Action<ICallHierarchyNameItem> verify, CallHierarchySearchScope scope, IImmutableSet<Document> documents = null) { var callback = new MockSearchCallback(verify); var category = root.SupportedSearchCategories.First(c => c.DisplayName == displayName).Name; if (documents != null) { root.StartSearchWithDocuments(category, scope, callback, documents); } else { root.StartSearch(category, scope, callback); } callback.WaitForCompletion(); } internal string ConvertToName(ICallHierarchyMemberItem root) { var name = root.MemberName; if (!string.IsNullOrEmpty(root.ContainingTypeName)) { name = root.ContainingTypeName + "." + name; } if (!string.IsNullOrEmpty(root.ContainingNamespaceName)) { name = root.ContainingNamespaceName + "." + name; } return name; } internal string ConvertToName(ICallHierarchyNameItem root) { return root.Name; } internal void VerifyRoot(CallHierarchyItem root, string name = "", string[] expectedCategories = null) { Assert.Equal(name, ConvertToName(root)); if (expectedCategories != null) { var categories = root.SupportedSearchCategories.Select(s => s.DisplayName); foreach (var category in expectedCategories) { Assert.Contains(category, categories); } } } internal void VerifyResultName(CallHierarchyItem root, string searchCategory, string[] expectedCallers, CallHierarchySearchScope scope = CallHierarchySearchScope.EntireSolution, IImmutableSet<Document> documents = null) { this.SearchRoot(root, searchCategory, (ICallHierarchyNameItem c) => { Assert.True(expectedCallers.Any()); Assert.True(expectedCallers.Contains(ConvertToName(c))); }, scope, documents); } internal void VerifyResult(CallHierarchyItem root, string searchCategory, string[] expectedCallers, CallHierarchySearchScope scope = CallHierarchySearchScope.EntireSolution, IImmutableSet<Document> documents = null) { this.SearchRoot(root, searchCategory, (CallHierarchyItem c) => { Assert.True(expectedCallers.Any()); Assert.True(expectedCallers.Contains(ConvertToName(c))); }, scope, documents); } internal void Navigate(CallHierarchyItem root, string searchCategory, string callSite, CallHierarchySearchScope scope = CallHierarchySearchScope.EntireSolution, IImmutableSet<Document> documents = null) { CallHierarchyItem item = null; this.SearchRoot(root, searchCategory, (CallHierarchyItem c) => item = c, scope, documents); if (callSite == ConvertToName(item)) { var detail = item.Details.FirstOrDefault(); if (detail != null) { detail.NavigateTo(); } else { item.NavigateTo(); } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gcbav = Google.Cloud.Bigtable.Admin.V2; using gcbcv = Google.Cloud.Bigtable.Common.V2; namespace Google.Cloud.Bigtable.Admin.V2 { public partial class RestoreTableRequest { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public InstanceName ParentAsInstanceName { get => string.IsNullOrEmpty(Parent) ? null : InstanceName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary><see cref="BackupName"/>-typed view over the <see cref="Backup"/> resource name property.</summary> public BackupName BackupAsBackupName { get => string.IsNullOrEmpty(Backup) ? null : BackupName.Parse(Backup, allowUnparsed: true); set => Backup = value?.ToString() ?? ""; } } public partial class CreateTableRequest { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public InstanceName ParentAsInstanceName { get => string.IsNullOrEmpty(Parent) ? null : InstanceName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class CreateTableFromSnapshotRequest { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public InstanceName ParentAsInstanceName { get => string.IsNullOrEmpty(Parent) ? null : InstanceName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="SnapshotName"/>-typed view over the <see cref="SourceSnapshot"/> resource name property. /// </summary> public SnapshotName SourceSnapshotAsSnapshotName { get => string.IsNullOrEmpty(SourceSnapshot) ? null : SnapshotName.Parse(SourceSnapshot, allowUnparsed: true); set => SourceSnapshot = value?.ToString() ?? ""; } } public partial class DropRowRangeRequest { /// <summary> /// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::TableName TableName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListTablesRequest { /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public InstanceName ParentAsInstanceName { get => string.IsNullOrEmpty(Parent) ? null : InstanceName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetTableRequest { /// <summary> /// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::TableName TableName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteTableRequest { /// <summary> /// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::TableName TableName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ModifyColumnFamiliesRequest { /// <summary> /// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::TableName TableName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GenerateConsistencyTokenRequest { /// <summary> /// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::TableName TableName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CheckConsistencyRequest { /// <summary> /// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::TableName TableName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class SnapshotTableRequest { /// <summary> /// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::TableName TableName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="ClusterName"/>-typed view over the <see cref="Cluster"/> resource name property. /// </summary> public ClusterName ClusterAsClusterName { get => string.IsNullOrEmpty(Cluster) ? null : ClusterName.Parse(Cluster, allowUnparsed: true); set => Cluster = value?.ToString() ?? ""; } } public partial class GetSnapshotRequest { /// <summary> /// <see cref="gcbav::SnapshotName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbav::SnapshotName SnapshotName { get => string.IsNullOrEmpty(Name) ? null : gcbav::SnapshotName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListSnapshotsRequest { /// <summary> /// <see cref="ClusterName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ClusterName ParentAsClusterName { get => string.IsNullOrEmpty(Parent) ? null : ClusterName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteSnapshotRequest { /// <summary> /// <see cref="gcbav::SnapshotName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbav::SnapshotName SnapshotName { get => string.IsNullOrEmpty(Name) ? null : gcbav::SnapshotName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateBackupRequest { /// <summary> /// <see cref="ClusterName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ClusterName ParentAsClusterName { get => string.IsNullOrEmpty(Parent) ? null : ClusterName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetBackupRequest { /// <summary> /// <see cref="gcbav::BackupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbav::BackupName BackupName { get => string.IsNullOrEmpty(Name) ? null : gcbav::BackupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteBackupRequest { /// <summary> /// <see cref="gcbav::BackupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbav::BackupName BackupName { get => string.IsNullOrEmpty(Name) ? null : gcbav::BackupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListBackupsRequest { /// <summary> /// <see cref="ClusterName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ClusterName ParentAsClusterName { get => string.IsNullOrEmpty(Parent) ? null : ClusterName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } }
// 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.Web.UI.ControlBuilder.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 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.Web.UI { public partial class ControlBuilder { #region Methods and constructors public virtual new bool AllowWhitespaceLiterals () { return default(bool); } public virtual new void AppendLiteralString (string s) { } public virtual new void AppendSubBuilder (ControlBuilder subBuilder) { Contract.Requires (subBuilder != null); } public virtual new Object BuildObject () { return default(Object); } public virtual new void CloseControl () { } public ControlBuilder () { } public static ControlBuilder CreateBuilderFromType (TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id, System.Collections.IDictionary attribs, int line, string sourceFileName) { Contract.Ensures (Contract.Result<System.Web.UI.ControlBuilder>() != null); return default(ControlBuilder); } public virtual new Type GetChildControlType (string tagName, System.Collections.IDictionary attribs) { return default(Type); } public ObjectPersistData GetObjectPersistData () { Contract.Ensures (Contract.Result<System.Web.UI.ObjectPersistData>() != null); return default(ObjectPersistData); } public string GetResourceKey () { return default(string); } public virtual new bool HasBody () { return default(bool); } public virtual new bool HtmlDecodeLiterals () { return default(bool); } public virtual new void Init (TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id, System.Collections.IDictionary attribs) { Contract.Requires (parser != null); } public virtual new bool NeedsTagInnerText () { return default(bool); } public virtual new void OnAppendToParentBuilder (ControlBuilder parentBuilder) { } public virtual new void ProcessGeneratedCode (System.CodeDom.CodeCompileUnit codeCompileUnit, System.CodeDom.CodeTypeDeclaration baseType, System.CodeDom.CodeTypeDeclaration derivedType, System.CodeDom.CodeMemberMethod buildMethod, System.CodeDom.CodeMemberMethod dataBindingMethod) { } public void SetResourceKey (string resourceKey) { } public void SetServiceProvider (IServiceProvider serviceProvider) { } public virtual new void SetTagInnerText (string text) { } #endregion #region Properties and indexers public virtual new Type BindingContainerType { get { return default(Type); } } public Type ControlType { get { return default(Type); } } public IFilterResolutionService CurrentFilterResolutionService { get { return default(IFilterResolutionService); } } public virtual new Type DeclareType { get { return default(Type); } } protected bool FChildrenAsProperties { get { return default(bool); } } protected bool FIsNonParserAccessor { get { return default(bool); } } #if NETFRAMEWORK_4_0 virtual #endif public new bool HasAspCode { get { return default(bool); } } public string ID { get { return default(string); } set { } } protected bool InDesigner { get { return default(bool); } } protected bool InPageTheme { get { return default(bool); } } public bool Localize { get { return default(bool); } } public Type NamingContainerType { get { return default(Type); } } internal protected TemplateParser Parser { get { return default(TemplateParser); } } public IServiceProvider ServiceProvider { get { return default(IServiceProvider); } } public string TagName { get { return default(string); } } public IThemeResolutionService ThemeResolutionService { get { return default(IThemeResolutionService); } } #endregion #region Fields public readonly static string DesignerFilter; #endregion } }
using System; using NTumbleBit.BouncyCastle.Crypto.Utilities; using NTumbleBit.BouncyCastle.Utilities; namespace NTumbleBit.BouncyCastle.Crypto.Digests { /** * Draft FIPS 180-2 implementation of SHA-256. <b>Note:</b> As this is * based on a draft this implementation is subject to change. * * <pre> * block word digest * SHA-1 512 32 160 * SHA-256 512 32 256 * SHA-384 1024 64 384 * SHA-512 1024 64 512 * </pre> */ internal class Sha256Digest : GeneralDigest { private const int DigestLength = 32; private uint H1, H2, H3, H4, H5, H6, H7, H8; private uint[] X = new uint[64]; private int xOff; public Sha256Digest() { initHs(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha256Digest(Sha256Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha256Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-256"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if(++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if(xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE((uint)H1, output, outOff); Pack.UInt32_To_BE((uint)H2, output, outOff + 4); Pack.UInt32_To_BE((uint)H3, output, outOff + 8); Pack.UInt32_To_BE((uint)H4, output, outOff + 12); Pack.UInt32_To_BE((uint)H5, output, outOff + 16); Pack.UInt32_To_BE((uint)H6, output, outOff + 20); Pack.UInt32_To_BE((uint)H7, output, outOff + 24); Pack.UInt32_To_BE((uint)H8, output, outOff + 28); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); initHs(); xOff = 0; Array.Clear(X, 0, X.Length); } private void initHs() { /* SHA-256 initial hash value * The first 32 bits of the fractional parts of the square roots * of the first eight prime numbers */ H1 = 0x6a09e667; H2 = 0xbb67ae85; H3 = 0x3c6ef372; H4 = 0xa54ff53a; H5 = 0x510e527f; H6 = 0x9b05688c; H7 = 0x1f83d9ab; H8 = 0x5be0cd19; } internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // for(int ti = 16; ti <= 63; ti++) { X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // // set up working variables. // uint a = H1; uint b = H2; uint c = H3; uint d = H4; uint e = H5; uint f = H6; uint g = H7; uint h = H8; int t = 0; for(int i = 0; i < 8; ++i) { // t = 8 * i h += Sum1Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; Array.Clear(X, 0, 16); } private static uint Sum1Ch( uint x, uint y, uint z) { // return Sum1(x) + Ch(x, y, z); return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))) + ((x & y) ^ ((~x) & z)); } private static uint Sum0Maj( uint x, uint y, uint z) { // return Sum0(x) + Maj(x, y, z); return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))) + ((x & y) ^ (x & z) ^ (y & z)); } // /* SHA-256 functions */ // private static uint Ch( // uint x, // uint y, // uint z) // { // return ((x & y) ^ ((~x) & z)); // } // // private static uint Maj( // uint x, // uint y, // uint z) // { // return ((x & y) ^ (x & z) ^ (y & z)); // } // // private static uint Sum0( // uint x) // { // return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); // } // // private static uint Sum1( // uint x) // { // return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); // } private static uint Theta0( uint x) { return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); } private static uint Theta1( uint x) { return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-256 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ private static readonly uint[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; public override IMemoable Copy() { return new Sha256Digest(this); } public override void Reset(IMemoable other) { Sha256Digest d = (Sha256Digest)other; CopyIn(d); } } }
using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Drawing; using System.Windows.Forms; namespace GuruComponents.Netrix.UserInterface.ColorPicker { internal class ColorWellHelper { private ColorWellHelper() { } /// <summary> /// Generate an array of ColorWellInfo from the supplied array of Color. /// </summary> /// <param name="customColors"></param> /// <param name="colorSortOrder"></param> /// <returns></returns> public static ColorWellInfo[] GetCustomColorWells(List<Color> customColors, ColorSortOrder colorSortOrder) { int nColors = customColors.Count; ColorWellInfo[] colorWells = new ColorWellInfo[nColors]; for (int i = 0; i < customColors.Count; i++) { colorWells[i] = new ColorWellInfo((Color)customColors[i], i); } SortColorWells(colorWells, colorSortOrder); return colorWells; } /// <summary> /// This method return an array of colorWells that belong to the desired ColorSet and /// that have been sorted in the desired ColorSortOrder. /// </summary> /// <param name="colorSet">The color palette to be generated.</param> /// <param name="colorSortOrder">The order the generated palette should be sorted.</param> /// <returns></returns> public static ColorWellInfo[] GetColorWells(ColorSet colorSet, ColorSortOrder colorSortOrder) { // get array of desired colorWells and sort // Could have sort order enum/property Array knownColors = Enum.GetValues(typeof(System.Drawing.KnownColor)); int nColors = 0; // How many colors are there? switch (colorSet) { case ColorSet.Web: case ColorSet.Continues: nColors = 216; break; case ColorSet.System: foreach (KnownColor k in knownColors) { Color c = Color.FromKnownColor(k); if (c.IsSystemColor && (c.A > 0)) { nColors++; } } break; } ColorWellInfo[] colorWells = new ColorWellInfo[nColors]; int index = 0; int r = 0, g = 0, b = 0, i = 0; // Get the colors switch (colorSet) { case ColorSet.Continues: int[] ContR = new int[] { 0xCC, 0x66, 0x00, 0xFF, 0x99, 0x33 }; int[] ContG = new int[] { 0xFF, 0xCC, 0x99, 0x66, 0x33, 0x00, 0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF }; int[] ContB = new int[] { 0xFF, 0xCC, 0x99, 0x66, 0x33, 0x00, 0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF, 0xFF, 0xCC, 0x99, 0x66, 0x33, 0x00 }; for (int y = 0; y < 12; y++) { g = ContG[y]; for (int x = 0; x < 18; x++) { r = ContR[(x / 6) + ((y < 6) ? 0 : 3)]; b = ContB[x]; colorWells[i++] = new ColorWellInfo(Color.FromArgb(r, g, b), i); } } break; case ColorSet.Web: int[] WebSafe = new int[] { 0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF }; for (int y = 0; y < 12; y++) { b = WebSafe[y % 6]; for (int x = 0; x < 18; x++) { g = WebSafe[x % 6]; r = (y < 6) ? WebSafe[x / 6] : WebSafe[(x / 6) + 3]; colorWells[i++] = new ColorWellInfo(Color.FromArgb(r, g, b), i); } } break; case ColorSet.System: foreach (KnownColor k in knownColors) { Color c = Color.FromKnownColor(k); if (c.IsSystemColor && (c.A > 0)) { colorWells[index] = new ColorWellInfo(c, index); index++; } } break; } SortColorWells(colorWells, colorSortOrder); return colorWells; } /// <summary> /// Sort the supplied colorWells according to the required sort order. /// </summary> /// <param name="colorWells"></param> /// <param name="colorSortOrder"></param> public static void SortColorWells(ColorWellInfo[] colorWells, ColorSortOrder colorSortOrder) { // Sort them switch (colorSortOrder) { case ColorSortOrder.Brightness: Array.Sort(colorWells, ColorComparer.CompareColorBrightness()); break; case ColorSortOrder.Distance: Array.Sort(colorWells, ColorComparer.CompareColorDistance()); break; case ColorSortOrder.Continues: Array.Sort(colorWells, ColorComparer.CompareUnsorted()); break; case ColorSortOrder.Name: Array.Sort(colorWells, ColorComparer.CompareColorName()); break; case ColorSortOrder.Saturation: Array.Sort(colorWells, ColorComparer.CompareColorSaturation()); break; case ColorSortOrder.Unsorted: Array.Sort(colorWells, ColorComparer.CompareUnsorted()); break; } } /// <summary> /// Draws the ColorWell on the Graphics surface. /// </summary> /// <remarks> /// This method draws the ColorWell as either enabled or disabled. /// It also indicates the currently selected color and the color /// that is ready to chosed (picked) by the mouse or keyboard. /// </remarks> /// <param name="g">Graphics object.</param> /// <param name="enabled">Enable appearance</param> /// <param name="selected">Selected appearance.</param> /// <param name="pickColor">Color used.</param> /// <param name="cwi">ColorWellInfo object.</param> public static void DrawColorWell(System.Drawing.Graphics g, bool enabled, bool selected, bool pickColor, ColorWellInfo cwi) { Rectangle r = cwi.ColorPosition; if (!enabled) { r.Inflate(-SystemInformation.BorderSize.Width, -SystemInformation.BorderSize.Height); ControlPaint.DrawBorder3D(g, r, Border3DStyle.Flat); r.Inflate(-SystemInformation.BorderSize.Width, -SystemInformation.BorderSize.Height); g.FillRectangle(SystemBrushes.Control, r); } else { SolidBrush br = new SolidBrush(cwi.Color); if (pickColor) { ControlPaint.DrawBorder3D(g, r, Border3DStyle.Sunken); r.Inflate(-SystemInformation.Border3DSize.Width, -SystemInformation.Border3DSize.Height); g.FillRectangle(br, r); } else { if (selected) { ControlPaint.DrawBorder3D(g, r, Border3DStyle.Raised); r.Inflate(-SystemInformation.Border3DSize.Width, -SystemInformation.Border3DSize.Height); g.FillRectangle(br, r); } else { g.FillRectangle(SystemBrushes.Control, r); r.Inflate(-SystemInformation.BorderSize.Width, -SystemInformation.BorderSize.Height); ControlPaint.DrawBorder3D(g, r, Border3DStyle.Flat); r.Inflate(-SystemInformation.BorderSize.Width, -SystemInformation.BorderSize.Height); g.FillRectangle(br, r); } } br.Dispose(); br = null; } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Text; using Orleans.Runtime; namespace Orleans.Metadata { /// <summary> /// Information about a logical grain type <see cref="GrainType"/>. /// </summary> [Serializable] [GenerateSerializer] public class GrainProperties { /// <summary> /// Creates a <see cref="GrainProperties"/> instance. /// </summary> public GrainProperties(ImmutableDictionary<string, string> values) { this.Properties = values; } /// <summary> /// Gets the properties. /// </summary> [Id(1)] public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Returns a detailed string representation of this instance. /// </summary> public string ToDetailedString() { if (this.Properties is null) return string.Empty; var result = new StringBuilder("["); bool first = true; foreach (var entry in this.Properties) { if (!first) { result.Append(", "); } result.Append($"\"{entry.Key}\": \"{entry.Value}\""); first = false; } result.Append("]"); return result.ToString(); } } /// <summary> /// Well-known grain properties. /// </summary> /// <seealso cref="GrainProperties"/> public static class WellKnownGrainTypeProperties { /// <summary> /// The name of the placement strategy for grains of this type. /// </summary> public const string PlacementStrategy = "placement-strategy"; /// <summary> /// The directory policy for grains of this type. /// </summary> public const string GrainDirectory = "directory-policy"; /// <summary> /// Whether or not messages to this grain are unordered. /// </summary> public const string Unordered = "unordered"; /// <summary> /// Prefix for keys which indicate <see cref="GrainInterfaceType"/> of interfaces which a grain class implements. /// </summary> public const string ImplementedInterfacePrefix = "interface."; /// <summary> /// The period after which an idle grain will be deactivated. /// </summary> public const string IdleDeactivationPeriod = "idle-duration"; /// <summary> /// The value for <see cref="IdleDeactivationPeriod"/> used to specify that the grain should not be deactivated due to idleness. /// </summary> public const string IndefiniteIdleDeactivationPeriodValue = "indefinite"; /// <summary> /// The name of the primary implementation type. Used for convention-based matching of primary interface implementations. /// </summary> public const string TypeName = "type-name"; /// <summary> /// The full name of the primary implementation type. Used for prefix-based matching of implementations. /// </summary> public const string FullTypeName = "full-type-name"; /// <summary> /// The prefix for binding declarations /// </summary> public const string BindingPrefix = "binding"; /// <summary> /// The key for defining a binding type. /// </summary> public const string BindingTypeKey = "type"; /// <summary> /// The binding type for Orleans streams. /// </summary> public const string StreamBindingTypeValue = "stream"; /// <summary> /// The key to specify a stream binding pattern. /// </summary> public const string StreamBindingPatternKey = "pattern"; /// <summary> /// The key to specify a stream id mapper /// </summary> public const string StreamIdMapperKey = "streamid-mapper"; /// <summary> /// Whether to include the namespace name in the grain id. /// </summary> public const string StreamBindingIncludeNamespaceKey = "include-namespace"; /// <summary> /// Key type of the grain, if it implement a legacy interface. Valid values are nameof(String), nameof(Int64) and nameof(Guid) /// </summary> public const string LegacyGrainKeyType = "legacy-grain-key-type"; /// <summary> /// Whether a grain is reentrant or not. /// </summary> public const string Reentrant = "reentrant"; /// <summary> /// Specifies the name of a method used to determine if a request can interleave other requests. /// </summary> public const string MayInterleavePredicate = "may-interleave-predicate"; } /// <summary> /// Provides grain properties. /// </summary> public interface IGrainPropertiesProvider { /// <summary> /// Adds grain properties to <paramref name="properties"/>. /// </summary> void Populate(Type grainClass, GrainType grainType, Dictionary<string, string> properties); } /// <summary> /// Interface for <see cref="Attribute"/> classes which provide information about a grain. /// </summary> public interface IGrainPropertiesProviderAttribute { /// <summary> /// Adds grain properties to <paramref name="properties"/>. /// </summary> void Populate(IServiceProvider services, Type grainClass, GrainType grainType, Dictionary<string, string> properties); } /// <summary> /// Provides grain interface properties from attributes implementing <see cref="IGrainPropertiesProviderAttribute"/>. /// </summary> public sealed class AttributeGrainPropertiesProvider : IGrainPropertiesProvider { private readonly IServiceProvider serviceProvider; /// <summary> /// Creates a <see cref="AttributeGrainPropertiesProvider"/> instance. /// </summary> public AttributeGrainPropertiesProvider(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } /// <inheritdoc /> public void Populate(Type grainClass, GrainType grainType, Dictionary<string, string> properties) { foreach (var attr in grainClass.GetCustomAttributes(inherit: true)) { if (attr is IGrainPropertiesProviderAttribute providerAttribute) { providerAttribute.Populate(this.serviceProvider, grainClass, grainType, properties); } } } } /// <summary> /// Interface for <see cref="Attribute"/> classes which provide information about a grain. /// </summary> public interface IGrainBindingsProviderAttribute { /// <summary> /// Gets bindings for the type this attribute is attached to. /// </summary> IEnumerable<Dictionary<string, string>> GetBindings(IServiceProvider services, Type grainClass, GrainType grainType); } /// <summary> /// Provides grain interface properties from attributes implementing <see cref="IGrainPropertiesProviderAttribute"/>. /// </summary> public sealed class AttributeGrainBindingsProvider : IGrainPropertiesProvider { /// <summary> /// A hopefully unique name to describe bindings added by this provider. /// Binding names are meaningless and are only used to group properties for a given binding together. /// </summary> private const string BindingPrefix = WellKnownGrainTypeProperties.BindingPrefix + ".attr-"; private readonly IServiceProvider serviceProvider; /// <summary> /// Creates a <see cref="AttributeGrainBindingsProvider"/> instance. /// </summary> public AttributeGrainBindingsProvider(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } /// <inheritdoc /> public void Populate(Type grainClass, GrainType grainType, Dictionary<string, string> properties) { var bindingIndex = 1; foreach (var attr in grainClass.GetCustomAttributes(inherit: true)) { if (!(attr is IGrainBindingsProviderAttribute providerAttribute)) { continue; } foreach (var binding in providerAttribute.GetBindings(this.serviceProvider, grainClass, grainType)) { foreach (var pair in binding) { properties[BindingPrefix + bindingIndex.ToString(CultureInfo.InvariantCulture) + '.' + pair.Key] = pair.Value; } ++bindingIndex; } } } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey 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 License using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; #if !UNITY3D using System.Xml; #endif #if NETFX_CORE using MarkerMetro.Unity.WinLegacy.Plugin.IO; using MarkerMetro.Unity.WinLegacy.Reflection; using System.Linq; #endif namespace Pathfinding.Serialization.JsonFx { /// <summary> /// Writer for producing JSON data /// </summary> public class JsonWriter : IDisposable { #region Constants public const string JsonMimeType = "application/json"; public const string JsonFileExtension = ".json"; private const string AnonymousTypePrefix = "<>f__AnonymousType"; private const string ErrorMaxDepth = "The maxiumum depth of {0} was exceeded. Check for cycles in object graph."; private const string ErrorIDictionaryEnumerator = "Types which implement Generic IDictionary<TKey, TValue> must have an IEnumerator which implements IDictionaryEnumerator. ({0})"; #endregion Constants #region Fields private readonly TextWriter Writer; private JsonWriterSettings settings; private int depth; private Dictionary<object,int> previouslySerializedObjects; #endregion Fields #region Init /// <summary> /// Ctor /// </summary> /// <param name="output">TextWriter for writing</param> public JsonWriter(TextWriter output) : this(output, new JsonWriterSettings()) { } /// <summary> /// Ctor /// </summary> /// <param name="output">TextWriter for writing</param> /// <param name="settings">JsonWriterSettings</param> public JsonWriter (TextWriter output, JsonWriterSettings settings) { if (output == null) { throw new ArgumentNullException ("output"); } if (settings == null) { throw new ArgumentNullException ("settings"); } this.Writer = output; this.settings = settings; this.Writer.NewLine = this.settings.NewLine; if (settings.HandleCyclicReferences) { this.previouslySerializedObjects = new Dictionary<object, int> (); } } /// <summary> /// Ctor /// </summary> /// <param name="output">Stream for writing</param> public JsonWriter(System.IO.Stream output) : this(output, new JsonWriterSettings()) { } /// <summary> /// Ctor /// </summary> /// <param name="output">Stream for writing</param> /// <param name="settings">JsonWriterSettings</param> public JsonWriter(System.IO.Stream output, JsonWriterSettings settings) { if (output == null) { throw new ArgumentNullException("output"); } if (settings == null) { throw new ArgumentNullException("settings"); } this.Writer = new MarkerMetro.Unity.WinLegacy.Plugin.IO.StreamWriter(output, Encoding.UTF8); this.settings = settings; this.Writer.NewLine = this.settings.NewLine; } /// <summary> /// Ctor /// </summary> /// <param name="output">file name for writing</param> public JsonWriter(string outputFileName) : this(outputFileName, new JsonWriterSettings()) { } /// <summary> /// Ctor /// </summary> /// <param name="output">file name for writing</param> /// <param name="settings">JsonWriterSettings</param> public JsonWriter(string outputFileName, JsonWriterSettings settings) { if (outputFileName == null) { throw new ArgumentNullException("outputFileName"); } if (settings == null) { throw new ArgumentNullException("settings"); } Stream stream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read); this.Writer = new MarkerMetro.Unity.WinLegacy.Plugin.IO.StreamWriter(stream, Encoding.UTF8); this.settings = settings; this.Writer.NewLine = this.settings.NewLine; } /// <summary> /// Ctor /// </summary> /// <param name="output">StringBuilder for appending</param> public JsonWriter(StringBuilder output) : this(output, new JsonWriterSettings()) { } /// <summary> /// Ctor /// </summary> /// <param name="output">StringBuilder for appending</param> /// <param name="settings">JsonWriterSettings</param> public JsonWriter(StringBuilder output, JsonWriterSettings settings) { if (output == null) { throw new ArgumentNullException("output"); } if (settings == null) { throw new ArgumentNullException("settings"); } this.Writer = new StringWriter(output, System.Globalization.CultureInfo.InvariantCulture); this.settings = settings; this.Writer.NewLine = this.settings.NewLine; } #endregion Init #region Properties /// <summary> /// Gets and sets the property name used for type hinting /// </summary> [Obsolete("This has been deprecated in favor of JsonWriterSettings object")] public string TypeHintName { get { return this.settings.TypeHintName; } set { this.settings.TypeHintName = value; } } /// <summary> /// Gets and sets if JSON will be formatted for human reading /// </summary> [Obsolete("This has been deprecated in favor of JsonWriterSettings object")] public bool PrettyPrint { get { return this.settings.PrettyPrint; } set { this.settings.PrettyPrint = value; } } /// <summary> /// Gets and sets the string to use for indentation /// </summary> [Obsolete("This has been deprecated in favor of JsonWriterSettings object")] public string Tab { get { return this.settings.Tab; } set { this.settings.Tab = value; } } /// <summary> /// Gets and sets the line terminator string /// </summary> [Obsolete("This has been deprecated in favor of JsonWriterSettings object")] public string NewLine { get { return this.settings.NewLine; } set { this.Writer.NewLine = this.settings.NewLine = value; } } /// <summary> /// Gets the current nesting depth /// </summary> protected int Depth { get { return this.depth; } } /// <summary> /// Gets and sets the maximum depth to be serialized /// </summary> [Obsolete("This has been deprecated in favor of JsonWriterSettings object")] public int MaxDepth { get { return this.settings.MaxDepth; } set { this.settings.MaxDepth = value; } } /// <summary> /// Gets and sets if should use XmlSerialization Attributes /// </summary> /// <remarks> /// Respects XmlIgnoreAttribute, ... /// </remarks> [Obsolete("This has been deprecated in favor of JsonWriterSettings object")] public bool UseXmlSerializationAttributes { get { return this.settings.UseXmlSerializationAttributes; } set { this.settings.UseXmlSerializationAttributes = value; } } /// <summary> /// Gets and sets a proxy formatter to use for DateTime serialization /// </summary> [Obsolete("This has been deprecated in favor of JsonWriterSettings object")] public WriteDelegate<DateTime> DateTimeSerializer { get { return this.settings.DateTimeSerializer; } set { this.settings.DateTimeSerializer = value; } } /// <summary> /// Gets the underlying TextWriter /// </summary> public TextWriter TextWriter { get { return this.Writer; } } /// <summary> /// Gets and sets the JsonWriterSettings /// </summary> public JsonWriterSettings Settings { get { return this.settings; } set { if (value == null) { value = new JsonWriterSettings(); } this.settings = value; } } #endregion Properties #region Static Methods /// <summary> /// A helper method for serializing an object to JSON /// </summary> /// <param name="value"></param> /// <returns></returns> public static string Serialize(object value) { StringBuilder output = new StringBuilder(); using (JsonWriter writer = new JsonWriter(output)) { writer.Write(value); } return output.ToString(); } #endregion Static Methods #region Public Methods public void Write(object value) { this.Write(value, false); } protected virtual void Write(object value, bool isProperty) { if (isProperty && this.settings.PrettyPrint) { this.Writer.Write(' '); } if (value == null) { this.Writer.Write(JsonReader.LiteralNull); return; } if (value is IJsonSerializable) { try { if (isProperty) { this.depth++; if (this.depth > this.settings.MaxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth)); } this.WriteLine(); } ((IJsonSerializable)value).WriteJson(this); } finally { if (isProperty) { this.depth--; } } return; } // must test enumerations before value types if (value is Enum) { this.Write((Enum)value); return; } // Type.GetTypeCode() allows us to more efficiently switch type // plus cannot use 'is' for ValueTypes Type type = value.GetType(); JsonConverter converter = this.Settings.GetConverter (type); if (converter != null) { converter.Write (this, type,value); return; } #if NETFX_CORE switch (type.GetTypeCode()) #else switch (Type.GetTypeCode(type)) #endif { case TypeCode.Boolean: { this.Write((Boolean)value); return; } case TypeCode.Byte: { this.Write((Byte)value); return; } case TypeCode.Char: { this.Write((Char)value); return; } case TypeCode.DateTime: { this.Write((DateTime)value); return; } case TypeCode.DBNull: case TypeCode.Empty: { this.Writer.Write(JsonReader.LiteralNull); return; } case TypeCode.Decimal: { // From MSDN: // Conversions from Char, SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, and UInt64 // to Decimal are widening conversions that never lose information or throw exceptions. // Conversions from Single or Double to Decimal throw an OverflowException // if the result of the conversion is not representable as a Decimal. this.Write((Decimal)value); return; } case TypeCode.Double: { this.Write((Double)value); return; } case TypeCode.Int16: { this.Write((Int16)value); return; } case TypeCode.Int32: { this.Write((Int32)value); return; } case TypeCode.Int64: { this.Write((Int64)value); return; } case TypeCode.SByte: { this.Write((SByte)value); return; } case TypeCode.Single: { this.Write((Single)value); return; } case TypeCode.String: { this.Write((String)value); return; } case TypeCode.UInt16: { this.Write((UInt16)value); return; } case TypeCode.UInt32: { this.Write((UInt32)value); return; } case TypeCode.UInt64: { this.Write((UInt64)value); return; } default: case TypeCode.Object: { // all others must be explicitly tested break; } } if (value is Guid) { this.Write((Guid)value); return; } if (value is Uri) { this.Write((Uri)value); return; } if (value is TimeSpan) { this.Write((TimeSpan)value); return; } if (value is Version) { this.Write((Version)value); return; } // IDictionary test must happen BEFORE IEnumerable test // since IDictionary implements IEnumerable if (value is IDictionary) { try { if (isProperty) { this.depth++; if (this.depth > this.settings.MaxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth)); } this.WriteLine(); } this.WriteObject((IDictionary)value); } finally { if (isProperty) { this.depth--; } } return; } if (type.GetInterface(JsonReader.TypeGenericIDictionary, false) != null) { try { if (isProperty) { this.depth++; if (this.depth > this.settings.MaxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth)); } this.WriteLine(); } this.WriteDictionary((IEnumerable)value); } finally { if (isProperty) { this.depth--; } } return; } // IDictionary test must happen BEFORE IEnumerable test // since IDictionary implements IEnumerable if (value is IEnumerable) { #if !UNITY3D if (value is XmlNode) { this.Write((System.Xml.XmlNode)value); return; } #endif try { if (isProperty) { this.depth++; if (this.depth > this.settings.MaxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth)); } this.WriteLine(); } this.WriteArray((IEnumerable)value); } finally { if (isProperty) { this.depth--; } } return; } // structs and classes try { if (isProperty) { this.depth++; if (this.depth > this.settings.MaxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth)); } this.WriteLine(); } this.WriteObject(value, type); } finally { if (isProperty) { this.depth--; } } } public virtual void WriteBase64(byte[] value) { this.Write(Convert.ToBase64String(value)); } public virtual void WriteHexString(byte[] value) { if (value == null || value.Length == 0) { this.Write(String.Empty); return; } StringBuilder builder = new StringBuilder(); // Loop through each byte of the binary data // and format each one as a hexadecimal string for (int i=0; i<value.Length; i++) { builder.Append(value[i].ToString("x2")); } // the hexadecimal string this.Write(builder.ToString()); } public virtual void Write(DateTime value) { if (this.settings.DateTimeSerializer != null) { this.settings.DateTimeSerializer(this, value); return; } switch (value.Kind) { case DateTimeKind.Local: { value = value.ToUniversalTime(); goto case DateTimeKind.Utc; } case DateTimeKind.Utc: { // UTC DateTime in ISO-8601 this.Write(String.Format("{0:s}Z", value)); break; } default: { // DateTime in ISO-8601 this.Write(String.Format("{0:s}", value)); break; } } } public virtual void Write(Guid value) { this.Write(value.ToString("D")); } public virtual void Write(Enum value) { string enumName = null; Type type = value.GetType(); if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value)) { Enum[] flags = JsonWriter.GetFlagList(type, value); string[] flagNames = new string[flags.Length]; for (int i=0; i<flags.Length; i++) { flagNames[i] = JsonNameAttribute.GetJsonName(flags[i]); if (String.IsNullOrEmpty(flagNames[i])) { flagNames[i] = flags[i].ToString("f"); } } enumName = String.Join(", ", flagNames); } else { enumName = JsonNameAttribute.GetJsonName(value); if (String.IsNullOrEmpty(enumName)) { enumName = value.ToString("f"); } } this.Write(enumName); } public virtual void Write(string value) { if (value == null) { this.Writer.Write(JsonReader.LiteralNull); return; } int start = 0, length = value.Length; this.Writer.Write(JsonReader.OperatorStringDelim); for (int i=start; i<length; i++) { char ch = value[i]; if (ch <= '\u001F' || ch >= '\u007F' || ch == '<' || // improves compatibility within script blocks ch == JsonReader.OperatorStringDelim || ch == JsonReader.OperatorCharEscape) { if (i > start) { this.Writer.Write(value.Substring(start, i-start)); } start = i+1; switch (ch) { case JsonReader.OperatorStringDelim: case JsonReader.OperatorCharEscape: { this.Writer.Write(JsonReader.OperatorCharEscape); this.Writer.Write(ch); continue; } case '\b': { this.Writer.Write("\\b"); continue; } case '\f': { this.Writer.Write("\\f"); continue; } case '\n': { this.Writer.Write("\\n"); continue; } case '\r': { this.Writer.Write("\\r"); continue; } case '\t': { this.Writer.Write("\\t"); continue; } default: { this.Writer.Write("\\u"); this.Writer.Write(Char.ConvertToUtf32(value, i).ToString("X4")); continue; } } } } if (length > start) { this.Writer.Write(value.Substring(start, length-start)); } this.Writer.Write(JsonReader.OperatorStringDelim); } #endregion Public Methods #region Primative Writer Methods public virtual void Write(bool value) { this.Writer.Write(value ? JsonReader.LiteralTrue : JsonReader.LiteralFalse); } public virtual void Write(byte value) { this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(sbyte value) { this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(short value) { this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(ushort value) { this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(int value) { this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(uint value) { if (this.InvalidIeee754(value)) { // emit as string since Number cannot represent this.Write(value.ToString("g", CultureInfo.InvariantCulture)); return; } this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(long value) { if (this.InvalidIeee754(value)) { // emit as string since Number cannot represent this.Write(value.ToString("g", CultureInfo.InvariantCulture)); return; } this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(ulong value) { if (this.InvalidIeee754(value)) { // emit as string since Number cannot represent this.Write(value.ToString("g", CultureInfo.InvariantCulture)); return; } this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(float value) { if (Single.IsNaN(value) || Single.IsInfinity(value)) { this.Writer.Write(JsonReader.LiteralNull); } else { this.Writer.Write(value.ToString("r", CultureInfo.InvariantCulture)); } } public virtual void Write(double value) { if (Double.IsNaN(value) || Double.IsInfinity(value)) { this.Writer.Write(JsonReader.LiteralNull); } else { this.Writer.Write(value.ToString("r", CultureInfo.InvariantCulture)); } } public virtual void Write(decimal value) { if (this.InvalidIeee754(value)) { // emit as string since Number cannot represent this.Write(value.ToString("g", CultureInfo.InvariantCulture)); return; } this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture)); } public virtual void Write(char value) { this.Write(new String(value, 1)); } public virtual void Write(TimeSpan value) { this.Write(value.Ticks); } public virtual void Write(Uri value) { this.Write(value.ToString()); } public virtual void Write(Version value) { this.Write(value.ToString()); } #if !UNITY3D public virtual void Write(XmlNode value) { // TODO: auto-translate XML to JsonML this.Write(value.OuterXml); } #endif #endregion Primative Writer Methods #region Writer Methods protected internal virtual void WriteArray(IEnumerable value) { bool appendDelim = false; this.Writer.Write(JsonReader.OperatorArrayStart); this.depth++; if (this.depth > this.settings.MaxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth)); } try { foreach (object item in value) { if (appendDelim) { this.WriteArrayItemDelim(); } else { appendDelim = true; } this.WriteLine(); this.WriteArrayItem(item); } } finally { this.depth--; } if (appendDelim) { this.WriteLine(); } this.Writer.Write(JsonReader.OperatorArrayEnd); } protected virtual void WriteArrayItem(object item) { this.Write(item, false); } protected virtual void WriteObject(IDictionary value) { this.WriteDictionary((IEnumerable)value); } protected virtual void WriteDictionary(IEnumerable value) { IDictionaryEnumerator enumerator = value.GetEnumerator() as IDictionaryEnumerator; if (enumerator == null) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorIDictionaryEnumerator, value.GetType())); } bool appendDelim = false; if (settings.HandleCyclicReferences) { int prevIndex = 0; if (this.previouslySerializedObjects.TryGetValue (value, out prevIndex)) { this.Writer.Write(JsonReader.OperatorObjectStart); this.WriteObjectProperty("@ref", prevIndex); this.WriteLine(); this.Writer.Write(JsonReader.OperatorObjectEnd); return; } else { this.previouslySerializedObjects.Add (value, this.previouslySerializedObjects.Count); } } this.Writer.Write(JsonReader.OperatorObjectStart); this.depth++; if (this.depth > this.settings.MaxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth)); } try { while (enumerator.MoveNext()) { if (appendDelim) { this.WriteObjectPropertyDelim(); } else { appendDelim = true; } this.WriteObjectProperty(Convert.ToString(enumerator.Entry.Key), enumerator.Entry.Value); } } finally { this.depth--; } if (appendDelim) { this.WriteLine(); } this.Writer.Write(JsonReader.OperatorObjectEnd); } private void WriteObjectProperty(string key, object value) { this.WriteLine(); this.WriteObjectPropertyName(key); this.Writer.Write(JsonReader.OperatorNameDelim); this.WriteObjectPropertyValue(value); } protected virtual void WriteObjectPropertyName(string name) { this.Write(name); } protected virtual void WriteObjectPropertyValue(object value) { this.Write(value, true); } protected virtual void WriteObject(object value, Type type) { bool appendDelim = false; #if NETFX_CORE if (settings.HandleCyclicReferences && !type.IsValueType()) #else if (settings.HandleCyclicReferences && !type.IsValueType) #endif { int prevIndex = 0; if (this.previouslySerializedObjects.TryGetValue (value, out prevIndex)) { this.Writer.Write(JsonReader.OperatorObjectStart); this.WriteObjectProperty("@ref", prevIndex); this.WriteLine(); this.Writer.Write(JsonReader.OperatorObjectEnd); return; } else { this.previouslySerializedObjects.Add (value, this.previouslySerializedObjects.Count); } } this.Writer.Write(JsonReader.OperatorObjectStart); this.depth++; if (this.depth > this.settings.MaxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth)); } try { if (!String.IsNullOrEmpty(this.settings.TypeHintName)) { if (appendDelim) { this.WriteObjectPropertyDelim(); } else { appendDelim = true; } #if NETFX_CORE this.WriteObjectProperty(this.settings.TypeHintName, type.FullName + ", " + type.GetAssembly().GetName().Name); #else this.WriteObjectProperty(this.settings.TypeHintName, type.FullName+", "+type.Assembly.GetName().Name); #endif } #if NETFX_CORE bool anonymousType = type.IsGenericType() && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix); #else bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix); #endif // serialize public properties PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { if (!property.CanRead) { #if !NETFX_CORE if (Settings.DebugMode) Console.WriteLine ("Cannot serialize "+property.Name+" : cannot read"); #endif continue; } if (!property.CanWrite && !anonymousType) { #if !NETFX_CORE if (Settings.DebugMode) Console.WriteLine ("Cannot serialize "+property.Name+" : cannot write"); #endif continue; } if (this.IsIgnored(type, property, value)) { #if !NETFX_CORE if (Settings.DebugMode) Console.WriteLine ("Cannot serialize "+property.Name+" : is ignored by settings"); #endif continue; } if (property.GetIndexParameters ().Length != 0) { #if !NETFX_CORE if (Settings.DebugMode) Console.WriteLine ("Cannot serialize "+property.Name+" : is indexed"); #endif continue; } object propertyValue = property.GetValue(value, null); if (this.IsDefaultValue(property, propertyValue)) { #if !NETFX_CORE if (Settings.DebugMode) Console.WriteLine ("Cannot serialize "+property.Name+" : is default value"); #endif continue; } if (appendDelim) this.WriteObjectPropertyDelim(); else appendDelim = true; // use Attributes here to control naming string propertyName = JsonNameAttribute.GetJsonName(property); if (String.IsNullOrEmpty(propertyName)) propertyName = property.Name; this.WriteObjectProperty(propertyName, propertyValue); } // serialize public fields FieldInfo[] fields = type.GetFields(); foreach (FieldInfo field in fields) { if (!field.IsPublic || field.IsStatic) { #if !NETFX_CORE if (Settings.DebugMode) Console.WriteLine ("Cannot serialize "+field.Name+" : not public or is static"); #endif continue; } if (this.IsIgnored(type, field, value)) { #if !NETFX_CORE if (Settings.DebugMode) Console.WriteLine ("Cannot serialize "+field.Name+" : ignored by settings"); #endif continue; } object fieldValue = field.GetValue(value); if (this.IsDefaultValue(field, fieldValue)) { #if !NETFX_CORE if (Settings.DebugMode) Console.WriteLine ("Cannot serialize "+field.Name+" : is default value"); #endif continue; } if (appendDelim) { this.WriteObjectPropertyDelim(); this.WriteLine(); } else { appendDelim = true; } // use Attributes here to control naming string fieldName = JsonNameAttribute.GetJsonName(field); if (String.IsNullOrEmpty(fieldName)) fieldName = field.Name; this.WriteObjectProperty(fieldName, fieldValue); } } finally { this.depth--; } if (appendDelim) this.WriteLine(); this.Writer.Write(JsonReader.OperatorObjectEnd); } protected virtual void WriteArrayItemDelim() { this.Writer.Write(JsonReader.OperatorValueDelim); } protected virtual void WriteObjectPropertyDelim() { this.Writer.Write(JsonReader.OperatorValueDelim); } protected virtual void WriteLine() { if (!this.settings.PrettyPrint) { return; } this.Writer.WriteLine(); for (int i=0; i<this.depth; i++) { this.Writer.Write(this.settings.Tab); } } #endregion Writer Methods #region Private Methods /// <summary> /// Determines if the property or field should not be serialized. /// </summary> /// <param name="objType"></param> /// <param name="member"></param> /// <param name="value"></param> /// <returns></returns> /// <remarks> /// Checks these in order, if any returns true then this is true: /// - is flagged with the JsonIgnoreAttribute property /// - has a JsonSpecifiedProperty which returns false /// </remarks> private bool IsIgnored(Type objType, MemberInfo member, object obj) { if (JsonIgnoreAttribute.IsJsonIgnore(member)) { return true; } string specifiedProperty = JsonSpecifiedPropertyAttribute.GetJsonSpecifiedProperty(member); if (!String.IsNullOrEmpty(specifiedProperty)) { PropertyInfo specProp = objType.GetProperty(specifiedProperty); if (specProp != null) { object isSpecified = specProp.GetValue(obj, null); if (isSpecified is Boolean && !Convert.ToBoolean(isSpecified)) { return true; } } } //If the class is specified as opt-in serialization only, members must have the JsonMember attribute if (objType.GetCustomAttributes (typeof(JsonOptInAttribute),true).Length != 0) { #if NETFX_CORE var customAttrs = member.GetCustomAttributes(typeof(JsonMemberAttribute), true); System.Attribute[] customAttrsArr = customAttrs == null ? null : customAttrs.ToArray(); if (customAttrs == null ||customAttrsArr == null || customAttrsArr.Length == 0) { #else if (member.GetCustomAttributes(typeof(JsonMemberAttribute),true).Length == 0) { #endif return true; } } if (this.settings.UseXmlSerializationAttributes) { if (JsonIgnoreAttribute.IsXmlIgnore(member)) { return true; } PropertyInfo specProp = objType.GetProperty(member.Name+"Specified"); if (specProp != null) { object isSpecified = specProp.GetValue(obj, null); if (isSpecified is Boolean && !Convert.ToBoolean(isSpecified)) { return true; } } } return false; } /// <summary> /// Determines if the member value matches the DefaultValue attribute /// </summary> /// <returns>if has a value equivalent to the DefaultValueAttribute</returns> private bool IsDefaultValue(MemberInfo member, object value) { #if NETFX_CORE var attribute = member.GetCustomAttribute<DefaultValueAttribute>(true); #else DefaultValueAttribute attribute = Attribute.GetCustomAttribute(member, typeof(DefaultValueAttribute)) as DefaultValueAttribute; #endif if (attribute == null) { return false; } if (attribute.Value == null) { return (value == null); } return (attribute.Value.Equals(value)); } #endregion Private Methods #region Utility Methods /// <summary> /// Splits a bitwise-OR'd set of enums into a list. /// </summary> /// <param name="enumType">the enum type</param> /// <param name="value">the combined value</param> /// <returns>list of flag enums</returns> /// <remarks> /// from PseudoCode.EnumHelper /// </remarks> private static Enum[] GetFlagList(Type enumType, object value) { ulong longVal = Convert.ToUInt64(value); Array enumValues = Enum.GetValues(enumType); List<Enum> enums = new List<Enum>(enumValues.Length); // check for empty if (longVal == 0L) { // Return the value of empty, or zero if none exists enums.Add((Enum)Convert.ChangeType(value, enumType)); return enums.ToArray(); } for (int i = enumValues.Length-1; i >= 0; i--) { ulong enumValue = Convert.ToUInt64(enumValues.GetValue(i)); if ((i == 0) && (enumValue == 0L)) { continue; } // matches a value in enumeration if ((longVal & enumValue) == enumValue) { // remove from val longVal -= enumValue; // add enum to list enums.Add(enumValues.GetValue(i) as Enum); } } if (longVal != 0x0L) { enums.Add(Enum.ToObject(enumType, longVal) as Enum); } return enums.ToArray(); } /// <summary> /// Determines if a numberic value cannot be represented as IEEE-754. /// </summary> /// <param name="value"></param> /// <returns></returns> protected virtual bool InvalidIeee754(decimal value) { // http://stackoverflow.com/questions/1601646 try { return (decimal)((double)value) != value; } catch { return true; } } #endregion Utility Methods #region IDisposable Members void IDisposable.Dispose() { if (this.Writer != null) { this.Writer.Dispose(); } } #endregion IDisposable Members } }
using UnityEditor; using UnityEngine; using System.Collections.Generic; using System.Linq; namespace Pathfinding { /** Helper for creating editors */ [CustomEditor(typeof(VersionedMonoBehaviour), true)] [CanEditMultipleObjects] public class EditorBase : Editor { static System.Collections.Generic.Dictionary<string, string> cachedTooltips; static System.Collections.Generic.Dictionary<string, string> cachedURLs; Dictionary<string, SerializedProperty> props = new Dictionary<string, SerializedProperty>(); Dictionary<string, string> localTooltips = new Dictionary<string, string>(); static GUIContent content = new GUIContent(); static GUIContent showInDocContent = new GUIContent("Show in online documentation", ""); static GUILayoutOption[] noOptions = new GUILayoutOption[0]; static void LoadMeta () { if (cachedTooltips == null) { var filePath = EditorResourceHelper.editorAssets + "/tooltips.tsv"; try { cachedURLs = System.IO.File.ReadAllLines(filePath).Select(l => l.Split('\t')).Where(l => l.Length == 2).ToDictionary(l => l[0], l => l[1]); cachedTooltips = new System.Collections.Generic.Dictionary<string, string>(); } catch { cachedURLs = new System.Collections.Generic.Dictionary<string, string>(); cachedTooltips = new System.Collections.Generic.Dictionary<string, string>(); } } } static string FindURL (System.Type type, string path) { // Find the correct type if the path was not an immediate member of #type while (true) { var index = path.IndexOf('.'); if (index == -1) break; var fieldName = path.Substring(0, index); var remaining = path.Substring(index + 1); var field = type.GetField(fieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); if (field != null) { type = field.FieldType; path = remaining; } else { // Could not find the correct field return null; } } // Find a documentation entry for the field, fall back to parent classes if necessary while (type != null) { var url = FindURL(type.FullName + "." + path); if (url != null) return url; type = type.BaseType; } return null; } static string FindURL (string path) { LoadMeta(); string url; cachedURLs.TryGetValue(path, out url); return url; } static string FindTooltip (string path) { LoadMeta(); string tooltip; cachedTooltips.TryGetValue(path, out tooltip); return tooltip; } string FindLocalTooltip (string path) { string result; if (!localTooltips.TryGetValue(path, out result)) { var fullPath = target.GetType().Name + "." + path; result = localTooltips[path] = FindTooltip(fullPath); } return result; } protected virtual void OnEnable () { foreach (var target in targets) if (target != null) (target as IVersionedMonoBehaviourInternal).OnUpgradeSerializedData(int.MaxValue, true); } public sealed override void OnInspectorGUI () { EditorGUI.indentLevel = 0; serializedObject.Update(); Inspector(); serializedObject.ApplyModifiedProperties(); if (targets.Length == 1 && (target as MonoBehaviour).enabled) { var attr = target.GetType().GetCustomAttributes(typeof(UniqueComponentAttribute), true); for (int i = 0; i < attr.Length; i++) { string tag = (attr[i] as UniqueComponentAttribute).tag; foreach (var other in (target as MonoBehaviour).GetComponents<MonoBehaviour>()) { if (!other.enabled || other == target) continue; if (other.GetType().GetCustomAttributes(typeof(UniqueComponentAttribute), true).Select(c => (c as UniqueComponentAttribute).tag == tag).Any()) { EditorGUILayout.HelpBox("This component and " + other.GetType().Name + " cannot be used at the same time", MessageType.Warning); } } } } } protected virtual void Inspector () { // Basically the same as DrawDefaultInspector, but with tooltips bool enterChildren = true; for (var prop = serializedObject.GetIterator(); prop.NextVisible(enterChildren); enterChildren = false) { PropertyField(prop.propertyPath); } } protected SerializedProperty FindProperty (string name) { SerializedProperty res; if (!props.TryGetValue(name, out res)) res = props[name] = serializedObject.FindProperty(name); if (res == null) throw new System.ArgumentException(name); return res; } protected bool PropertyField (string propertyPath, string label = null, string tooltip = null) { return PropertyField(FindProperty(propertyPath), label, tooltip, propertyPath); } protected bool PropertyField (SerializedProperty prop, string label = null, string tooltip = null) { return PropertyField(prop, label, tooltip, prop.propertyPath); } bool PropertyField (SerializedProperty prop, string label, string tooltip, string propertyPath) { content.text = label ?? prop.displayName; content.tooltip = tooltip ?? FindTooltip(propertyPath); var contextClick = IsContextClick(); EditorGUILayout.PropertyField(prop, content, true, noOptions); // Disable context clicking on arrays (as Unity has its own very useful context menu for the array elements) if (contextClick && !prop.isArray && Event.current.type == EventType.Used) CaptureContextClick(propertyPath); return prop.propertyType == SerializedPropertyType.Boolean ? !prop.hasMultipleDifferentValues && prop.boolValue : true; } bool IsContextClick () { return Event.current.type == EventType.ContextClick; } void CaptureContextClick (string propertyPath) { var url = FindURL(target.GetType(), propertyPath); if (url != null) { Event.current.Use(); var menu = new GenericMenu(); menu.AddItem(showInDocContent, false, () => Application.OpenURL(AstarUpdateChecker.GetURL("documentation") + url)); menu.ShowAsContext(); } } protected void Popup (string propertyPath, GUIContent[] options, string label = null) { var prop = FindProperty(propertyPath); content.text = label ?? prop.displayName; content.tooltip = FindTooltip(propertyPath); var contextClick = IsContextClick(); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = prop.hasMultipleDifferentValues; int newVal = EditorGUILayout.Popup(content, prop.propertyType == SerializedPropertyType.Enum ? prop.enumValueIndex : prop.intValue, options); if (EditorGUI.EndChangeCheck()) { if (prop.propertyType == SerializedPropertyType.Enum) prop.enumValueIndex = newVal; else prop.intValue = newVal; } EditorGUI.showMixedValue = false; if (contextClick && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) CaptureContextClick(propertyPath); } protected void Mask (string propertyPath, string[] options, string label = null) { var prop = FindProperty(propertyPath); content.text = label ?? prop.displayName; content.tooltip = FindTooltip(propertyPath); var contextClick = IsContextClick(); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = prop.hasMultipleDifferentValues; int newVal = EditorGUILayout.MaskField(content, prop.intValue, options); if (EditorGUI.EndChangeCheck()) { prop.intValue = newVal; } EditorGUI.showMixedValue = false; if (contextClick && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) CaptureContextClick(propertyPath); } protected void IntSlider (string propertyPath, int left, int right) { var contextClick = IsContextClick(); var prop = FindProperty(propertyPath); content.text = prop.displayName; content.tooltip = FindTooltip(propertyPath); EditorGUILayout.IntSlider(prop, left, right, content, noOptions); if (contextClick && Event.current.type == EventType.Used) CaptureContextClick(propertyPath); } protected void Clamp (string name, float min, float max = float.PositiveInfinity) { var prop = FindProperty(name); if (!prop.hasMultipleDifferentValues) prop.floatValue = Mathf.Clamp(prop.floatValue, min, max); } protected void ClampInt (string name, int min, int max = int.MaxValue) { var prop = FindProperty(name); if (!prop.hasMultipleDifferentValues) prop.intValue = Mathf.Clamp(prop.intValue, min, max); } } }
/* * 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 Payload = Lucene.Net.Index.Payload; using ArrayUtil = Lucene.Net.Util.ArrayUtil; namespace Lucene.Net.Analysis { /// <summary>A Token is an occurence of a term from the text of a field. It consists of /// a term's text, the start and end offset of the term in the text of the field, /// and a type string. /// <p> /// The start and end offsets permit applications to re-associate a token with /// its source text, e.g., to display highlighted query terms in a document /// browser, or to show matching text fragments in a KWIC (KeyWord In Context) /// display, etc. /// <p> /// The type is a string, assigned by a lexical analyzer /// (a.k.a. tokenizer), naming the lexical or syntactic class that the token /// belongs to. For example an end of sentence marker token might be implemented /// with type "eos". The default token type is "word". /// <p> /// A Token can optionally have metadata (a.k.a. Payload) in the form of a variable /// length byte array. Use {@link TermPositions#GetPayloadLength()} and /// {@link TermPositions#GetPayload(byte[], int)} to retrieve the payloads from the index. /// </summary> /// <summary><br><br> /// <p><font color="#FF0000"> /// WARNING: The status of the <b>Payloads</b> feature is experimental. /// The APIs introduced here might change in the future and will not be /// supported anymore in such a case.</font> /// <br><br> /// <p><b>NOTE:</b> As of 2.3, Token stores the term text /// internally as a malleable char[] termBuffer instead of /// String termText. The indexing code and core tokenizers /// have been changed to re-use a single Token instance, changing /// its buffer and other fields in-place as the Token is /// processed. This provides substantially better indexing /// performance as it saves the GC cost of new'ing a Token and /// String for every term. The APIs that accept String /// termText are still available but a warning about the /// associated performance cost has been added (below). The /// {@link #TermText()} method has been deprecated.</p> /// <p>Tokenizers and filters should try to re-use a Token /// instance when possible for best performance, by /// implementing the {@link TokenStream#Next(Token)} API. /// Failing that, to create a new Token you should first use /// one of the constructors that starts with null text. To load /// the token from a char[] use {@link #setTermBuffer(char[], int, int)}. /// To load from a String use {@link #setTermBuffer(String)} or {@link #setTermBuffer(String, int, int)}. /// Alternatively you can get the Token's termBuffer by calling either {@link #termBuffer()}, /// if you know that your text is shorter than the capacity of the termBuffer /// or {@link #resizeTermBuffer(int)}, if there is any possibility /// that you may need to grow the buffer. Fill in the characters of your term into this /// buffer, with {@link String#getChars(int, int, char[], int)} if loading from a string, /// or with {@link System#arraycopy(object, int, object, int, int)}, and finally call {@link #setTermLength(int)} to /// set the length of the term text. See <a target="_top" /// href="https://issues.apache.org/jira/browse/LUCENE-969">LUCENE-969</a> /// for details.</p> /// <p>Typical reuse patterns: /// <ul> /// <li> Copying text from a string (type is reset to #DEFAULT_TYPE if not specified):<br/> /// <pre> /// return reusableToken.reinit(string, startOffset, endOffset[, type]); /// </pre> /// </li> /// <li> Copying some text from a string (type is reset to #DEFAULT_TYPE if not specified):<br/> /// <pre> /// return reusableToken.reinit(string, 0, string.length(), startOffset, endOffset[, type]); /// </pre> /// </li> /// </li> /// <li> Copying text from char[] buffer (type is reset to #DEFAULT_TYPE if not specified):<br/> /// <pre> /// return reusableToken.reinit(buffer, 0, buffer.length, startOffset, endOffset[, type]); /// </pre> /// </li> /// <li> Copying some text from a char[] buffer (type is reset to #DEFAULT_TYPE if not specified):<br/> /// <pre> /// return reusableToken.reinit(buffer, start, end - start, startOffset, endOffset[, type]); /// </pre> /// </li> /// <li> Copying from one one Token to another (type is reset to #DEFAULT_TYPE if not specified):<br/> /// <pre> /// return reusableToken.reinit(source.termBuffer(), 0, source.termLength(), source.startOffset(), source.endOffset()[, source.type()]); /// </pre> /// </li> /// </ul> /// A few things to note: /// <ul> /// <li>clear() initializes most of the fields to default values, but not startOffset, endOffset and type.</li> /// <li>Because <code>TokenStreams</code> can be chained, one cannot assume that the <code>Token's</code> current type is correct.</li> /// <li>The startOffset and endOffset represent the start and offset in the source text. So be careful in adjusting them.</li> /// <li>When caching a reusable token, clone it. When injecting a cached token into a stream that can be reset, clone it again.</li> /// </ul> /// </p> /// </summary> /// <seealso cref="Lucene.Net.Index.Payload"> /// </seealso> public class Token : System.ICloneable { public const System.String DEFAULT_TYPE = "word"; private static int MIN_BUFFER_SIZE = 10; /// <deprecated> /// We will remove this when we remove the deprecated APIs. /// </deprecated> private System.String termText; /// <summary> /// Characters for the term text. /// </summary> /// <deprecated> /// This will be made private. Instead, use: /// {@link #setTermBuffer(char[], int, int)}, /// {@link #setTermBuffer(String)}, or /// {@link #setTermBuffer(String, int, int)}, /// </deprecated> internal char[] termBuffer; /// <summary> /// Length of term text in the buffer. /// </summary> /// <deprecated> /// This will be made private. Instead, use: /// {@link termLength()} or {@link setTermLength(int)} /// </deprecated> internal int termLength; /// <summary> /// Start in source text. /// </summary> /// <deprecated> /// This will be made private. Instead, use: /// {@link startOffset()} or {@link setStartOffset(int)} /// </deprecated> internal int startOffset; /// <summary> /// End in source text. /// </summary> /// <deprecated> /// This will be made private. Instead, use: /// {@link endOffset()} or {@link setEndOffset(int)} /// </deprecated> internal int endOffset; /// <summary> /// The lexical type of the token. /// </summary> /// <deprecated> /// This will be made private. Instead, use: /// {@link type()} or {@link setType(String)} /// </deprecated> internal System.String type = DEFAULT_TYPE; private int flags; /// <deprecated> /// This will be made private. Instead, use: /// {@link getPayload()} or {@link setPayload(Payload)}. /// </deprecated> internal Payload payload; /// <deprecated> /// This will be made private. Instead, use: /// {@link getPositionIncrement()} or {@link setPositionIncrement(String)}. /// </deprecated> internal int positionIncrement = 1; /// <summary>Constructs a Token will null text. </summary> public Token() { } /// <summary> /// Constructs a Token with null text and start & endoffsets. /// </summary> /// <param name="start">start offset in the source text</param> /// <param name="end">end offset in the source text</param> public Token(int start, int end) { startOffset = start; endOffset = end; } /// <summary> /// Constructs a Token with null text and start & endoffsets plus the Token type. /// </summary> /// <param name="start">start offset in the source text</param> /// <param name="end">end offset in the source text</param> /// <param name="typ">the lexical type of this Token</param> public Token(int start, int end, System.String typ) { startOffset = start; endOffset = end; type = typ; } /// <summary> /// Constructs a Token with null text and start & endoffsets plus flags. /// NOTE: flags is EXPERIMENTAL. /// </summary> /// <param name="start">start offset in the source text</param> /// <param name="end">end offset in the source text</param> /// <param name="flags">the bits to set for this Token</param> public Token(int start, int end, int flags) { startOffset = start; endOffset = end; this.flags = flags; } /// <summary> /// Constructs a Token with the given term text, and start /// and end offsets. The type defaults to "word." /// <b>NOTE:</b> for better indexing speed you should /// instead use the char[] termBuffer methods to set the /// term text. /// </summary> /// <param name="text">term text</param> /// <param name="start">start offset</param> /// <param name="end">end offset</param> /// <deprecated></deprecated> public Token(System.String text, int start, int end) { termText = text; startOffset = start; endOffset = end; } /// <summary> /// Constructs a Token with the given term text, start /// and end offsets, and type. /// <b>NOTE:</b> for better indexing speed you should /// instead use the char[] termBuffer methods to set the /// term text. /// </summary> /// <param name="text">term text</param> /// <param name="start">start offset</param> /// <param name="end">end offset</param> /// <param name="typ">token type</param> /// <deprecated></deprecated> public Token(System.String text, int start, int end, System.String typ) { termText = text; startOffset = start; endOffset = end; type = typ; } /// <summary> /// Constructs a Token with the given term text, start /// and end offsets, and flags. /// <b>NOTE:</b> for better indexing speed you should /// instead use the char[] termBuffer methods to set the /// term text. /// </summary> /// <param name="text">term text</param> /// <param name="start">start offset</param> /// <param name="end">end offset</param> /// <param name="flags">the bits to set for this Token</param> /// <deprecated></deprecated> public Token(System.String text, int start, int end, int flags) { termText = text; startOffset = start; endOffset = end; this.flags = flags; } /// <summary> /// Constructs a Token with the given term buffer (offset and length), start and end offsets. /// </summary> /// <param name="startTermBuffer"></param> /// <param name="termBufferOffset"></param> /// <param name="termBufferLength"></param> /// <param name="start"></param> /// <param name="end"></param> public Token(char[] startTermBuffer, int termBufferOffset, int termBufferLength, int start, int end) { SetTermBuffer(startTermBuffer, termBufferOffset, termBufferLength); startOffset = start; endOffset = end; } /// <summary>Set the position increment. This determines the position of this token /// relative to the previous Token in a {@link TokenStream}, used in phrase /// searching. /// /// <p>The default value is one. /// /// <p>Some common uses for this are:<ul> /// /// <li>Set it to zero to put multiple terms in the same position. This is /// useful if, e.g., a word has multiple stems. Searches for phrases /// including either stem will match. In this case, all but the first stem's /// increment should be set to zero: the increment of the first instance /// should be one. Repeating a token with an increment of zero can also be /// used to boost the scores of matches on that token. /// /// <li>Set it to values greater than one to inhibit exact phrase matches. /// If, for example, one does not want phrases to match across removed stop /// words, then one could build a stop word filter that removes stop words and /// also sets the increment to the number of stop words removed before each /// non-stop word. Then exact phrase queries will only match when the terms /// occur with no intervening stop words. /// /// </ul> /// </summary> /// <param name="positionIncrement">the distance from the prior term</param> /// <seealso cref="Lucene.Net.Index.TermPositions"> /// </seealso> public virtual void SetPositionIncrement(int positionIncrement) { if (positionIncrement < 0) throw new System.ArgumentException("Increment must be zero or greater: " + positionIncrement); this.positionIncrement = positionIncrement; } /// <summary>Returns the position increment of this Token.</summary> /// <seealso cref="setPositionIncrement"> /// </seealso> public virtual int GetPositionIncrement() { return positionIncrement; } /// <summary>Sets the Token's term text. <b>NOTE:</b> for better /// indexing speed you should instead use the char[] /// termBuffer methods to set the term text. /// </summary> /// <deprecated> /// use {@link #setTermBuffer(char[], int, int)}, /// {@link #setTermBuffer(string)}, or /// {@link #setTermBuffer(string, int, int)}. /// </deprecated> public virtual void SetTermText(System.String text) { termText = text; termBuffer = null; } /// <summary> /// Returns the Token's term text. /// This method has a performance penalty because the text is stored /// internally in a char[]. If possible, use {@link #termBuffer()} /// and {@link #termLength()} directly instead. If you really need /// a string, use {@link #Term()}. /// </summary> /// <returns></returns> public System.String TermText() { if (termText == null && termBuffer != null) termText = new System.String(termBuffer, 0, termLength); return termText; } /// <summary> /// Returns the Token's term text. /// This method has a performance penalty because the text is stored /// internally in a char[]. If possible, use {@link #termBuffer()} /// and {@link #termLength()} directly instead. If you really need /// a string, use this method which is nothing more than a /// convenience cal to <b>new String(token.TermBuffer(), o, token.TermLength())</b>. /// </summary> /// <returns></returns> public string Term() { if (termText != null) return termText; InitTermBuffer(); return new String(termBuffer, 0, termLength); } /// <summary> /// Copies the contents of buffer, starting at offset for /// length characters, into the termBuffer array. /// </summary> /// <param name="buffer"/> /// <param name="offset"/> /// <param name="length"/> public void SetTermBuffer(char[] buffer, int offset, int length) { termText = null; char[] newCharBuffer = GrowTermBuffer(length); if (newCharBuffer != null) termBuffer = newCharBuffer; Array.Copy(buffer, offset, termBuffer, 0, length); termLength = length; } /// <summary> /// Copies the contents of buffer, starting at offset for /// length characters, into the termBuffer array. /// </summary> /// <param name="buffer"/> public void SetTermBuffer(string buffer) { termText = null; int length = buffer.Length; char[] newCharBuffer = GrowTermBuffer(length); if (newCharBuffer != null) termBuffer = newCharBuffer; buffer.CopyTo(0, termBuffer, 0, length); termLength = length; } /// <summary> /// Copies the contents of buffer, starting at offset for /// length characters, into the termBuffer array. /// </summary> /// <param name="buffer"/> /// <param name="offset"/> /// <param name="length"/> public void SetTermBuffer(string buffer, int offset, int length) { System.Diagnostics.Debug.Assert(offset <= buffer.Length); System.Diagnostics.Debug.Assert(offset + length <= buffer.Length); termText = null; char[] newCharBuffer = GrowTermBuffer(length); if (newCharBuffer != null) termBuffer = newCharBuffer; buffer.CopyTo(offset, termBuffer, 0, length); termLength = length; } /// <summary>Returns the internal termBuffer character array which /// you can then directly alter. If the array is too /// small for your token, use {@link /// #ResizeTermBuffer(int)} to increase it. After /// altering the buffer be sure to call {@link /// #setTermLength} to record the number of valid /// characters that were placed into the termBuffer. /// </summary> public char[] TermBuffer() { InitTermBuffer(); return termBuffer; } /// <summary> /// Grows the termBuffer to at least size newSize, preserving the /// existing content. Note: If the next operation is to change /// the contents of the term buffer use /// {@link #setTermBuffer(char[], int, int)}, /// {@link #setTermBuffer(String)}, or /// {@link #setTermBuffer(String, int, int)}, /// to optimally combine the resize with the setting of the termBuffer. /// </summary> /// <param name="newSize">minimum size of the new termBuffer</param> /// <returns> newly created termBuffer with length >= newSize</returns> public virtual char[] ResizeTermBuffer(int newSize) { InitTermBuffer(); if (newSize > termBuffer.Length) { int size = termBuffer.Length; while (size < newSize) size *= 2; char[] newBuffer = new char[size]; Array.Copy(termBuffer, 0, newBuffer, 0, termBuffer.Length); termBuffer = newBuffer; } return termBuffer; } /// <summary> /// Allocates a buffer char[] of at least newSize. /// </summary> /// <param name="newSize">minimum size of the buffer</param> /// <returns>newly created buffer with length >= newSize or null if the current termBuffer is big enough</returns> private char[] GrowTermBuffer(int newSize) { if (termBuffer != null) { if (termBuffer.Length >= newSize) // Already big enough return null; else // Not big enough; create a new array with slight // over-allocation return new char[ArrayUtil.GetNextSize(newSize)]; } else { // determine the best size // The buffer is always at least MIN_BUFFER_SIZE if (newSize < MIN_BUFFER_SIZE) newSize = MIN_BUFFER_SIZE; // If there is already a termText, then the size has to be at least that big if (termText != null) { int ttLengh = termText.Length; if (newSize < ttLengh) newSize = ttLengh; } return new char[newSize]; } } // TODO: once we remove the deprecated termText() method // and switch entirely to char[] termBuffer we don't need // to use this method anymore private void InitTermBuffer() { if (termBuffer == null) { if (termText == null) { termBuffer = new char[MIN_BUFFER_SIZE]; termLength = 0; } else { int length = termText.Length; if (length < MIN_BUFFER_SIZE) length = MIN_BUFFER_SIZE; termBuffer = new char[length]; termLength = termText.Length; int offset = 0; while (offset < termText.Length) { termBuffer[offset] = (char) termText[offset]; offset++; } termText = null; } } else if (termText != null) termText = null; } /// <summary>Return number of valid characters (length of the term) /// in the termBuffer array. /// </summary> public int TermLength() { InitTermBuffer(); return termLength; } /// <summary>Set number of valid characters (length of the term) in /// the termBuffer array. Use this to truncate the termBuffer /// or to synchronize with external manipulation of the termBuffer. /// Note: to grow the size of the array use {@link #resizeTermBuffer(int)} first. /// </summary> /// <param name="length">the truncated length</param> public void SetTermLength(int length) { InitTermBuffer(); if (length > termBuffer.Length) throw new ArgumentOutOfRangeException("length " + length + " exceeds the size of the termBuffer (" + termBuffer.Length + ")"); termLength = length; } /// <summary>Returns this Token's starting offset, the position of the first character /// corresponding to this token in the source text. /// Note that the difference between endOffset() and startOffset() may not be /// equal to termText.length(), as the term text may have been altered by a /// stemmer or some other filter. /// </summary> public int StartOffset() { return startOffset; } /// <summary>Set the starting offset.</summary> /// <seealso cref="StartOffset()"> /// </seealso> public virtual void SetStartOffset(int offset) { this.startOffset = offset; } /// <summary>Returns this Token's ending offset, one greater than the position of the /// last character corresponding to this token in the source text. The length of the /// token in the source text is (endOffset - startOffset). /// </summary> public int EndOffset() { return endOffset; } /// <summary>Set the ending offset.</summary> /// <seealso cref="EndOffset()"> /// </seealso> public virtual void SetEndOffset(int offset) { this.endOffset = offset; } /// <summary>Returns this Token's lexical type. Defaults to "word". </summary> public System.String Type() { return type; } /// <summary>Set the lexical type.</summary> /// <seealso cref="Type()"> /// </seealso> public void SetType(System.String type) { this.type = type; } /// /// <summary> /// EXPERIMENTAL: While we think this is here to stay, we may want to change it to be a long. /// Get the bitset for any bits that have been set. This is completely distinct from {@link #type()}, although they do share similar purposes. /// The flags can be used to encode information about the token for use by other {@link org.apache.lucene.analysis.TokenFilter}s. /// </summary> /// <returns>The bits</returns> public int GetFlags() { return flags; } /// /// <seealso cref="GetFlags()"/> /// public void SetFlags(int flags) { this.flags = flags; } /// <summary> Returns this Token's payload.</summary> public virtual Payload GetPayload() { return this.payload; } /// <summary> Sets this Token's payload.</summary> public virtual void SetPayload(Payload payload) { this.payload = payload; } public override System.String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append('('); InitTermBuffer(); if (termBuffer == null) sb.Append("null"); else sb.Append(termBuffer, 0, termLength); sb.Append(',').Append(startOffset).Append(',').Append(endOffset); if (!type.Equals("word")) sb.Append(",type=").Append(type); if (positionIncrement != 1) sb.Append(",posIncr=").Append(positionIncrement); sb.Append(')'); return sb.ToString(); } /// <summary>Resets the term text, payload, and positionIncrement to default. /// Other fields such as startOffset, endOffset and the token type are /// not reset since they are normally overwritten by the tokenizer. /// </summary> public virtual void Clear() { payload = null; // Leave termBuffer to allow re-use termLength = 0; termText = null; positionIncrement = 1; flags = 0; // startOffset = endOffset = 0; // type = DEFAULT_TYPE; } public virtual object Clone() { try { Token t = (Token) base.MemberwiseClone(); // Do a deep clone if (termBuffer != null) { t.termBuffer = (char[]) termBuffer.Clone(); } if (payload != null) { t.SetPayload((Payload) payload.Clone()); } return t; } catch (System.Exception e) { throw new System.SystemException("", e); // shouldn't happen } } /** Makes a clone, but replaces the term buffer & * start/end offset in the process. This is more * efficient than doing a full clone (and then calling * setTermBuffer) because it saves a wasted copy of the old * termBuffer. */ public Token Clone(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset) { Token t = new Token(newTermBuffer, newTermOffset, newTermLength, newStartOffset, newEndOffset); t.positionIncrement = positionIncrement; t.flags = flags; t.type = type; if (payload != null) t.payload = (Payload)payload.Clone(); return t; } public override bool Equals(object obj) { if (obj == this) return true; if (obj is Token) { Token other = (Token)obj; InitTermBuffer(); other.InitTermBuffer(); if (termLength == other.termLength && startOffset == other.startOffset && endOffset == other.endOffset && flags == other.flags && positionIncrement == other.positionIncrement && SubEqual(type, other.type) && SubEqual(payload, other.payload)) { for (int i = 0; i < termLength; i++) if (termBuffer[i] != other.termBuffer[i]) return false; return true; } else return false; } else return false; } private bool SubEqual(object o1, object o2) { if (o1 == null) return o2 == null; else return o1.Equals(o2); } public override int GetHashCode() { InitTermBuffer(); int code = termLength; code = code * 31 + startOffset; code = code * 31 + endOffset; code = code * 31 + flags; code = code * 31 + positionIncrement; code = code * 31 + type.GetHashCode(); code = (payload == null ? code : code * 31 + payload.GetHashCode()); code = code * 31 + ArrayUtil.HashCode(termBuffer, 0, termLength); return code; } // like clear() but doesn't clear termBuffer/text private void ClearNoTermBuffer() { payload = null; positionIncrement = 1; flags = 0; } /** Shorthand for calling {@link #clear}, * {@link #setTermBuffer(char[], int, int)}, * {@link #setStartOffset}, * {@link #setEndOffset}, * {@link #setType} * @return this Token instance */ public Token Reinit(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset, String newType) { ClearNoTermBuffer(); payload = null; positionIncrement = 1; SetTermBuffer(newTermBuffer, newTermOffset, newTermLength); startOffset = newStartOffset; endOffset = newEndOffset; type = newType; return this; } /** Shorthand for calling {@link #clear}, * {@link #SetTermBuffer(char[], int, int)}, * {@link #setStartOffset}, * {@link #setEndOffset} * {@link #setType} on Token.DEFAULT_TYPE * @return this Token instance */ public Token Reinit(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset) { ClearNoTermBuffer(); SetTermBuffer(newTermBuffer, newTermOffset, newTermLength); startOffset = newStartOffset; endOffset = newEndOffset; type = DEFAULT_TYPE; return this; } /** Shorthand for calling {@link #clear}, * {@link #SetTermBuffer(String)}, * {@link #setStartOffset}, * {@link #setEndOffset} * {@link #setType} * @return this Token instance */ public Token Reinit(String newTerm, int newStartOffset, int newEndOffset, String newType) { ClearNoTermBuffer(); SetTermBuffer(newTerm); startOffset = newStartOffset; endOffset = newEndOffset; type = newType; return this; } /** Shorthand for calling {@link #clear}, * {@link #SetTermBuffer(String, int, int)}, * {@link #setStartOffset}, * {@link #setEndOffset} * {@link #setType} * @return this Token instance */ public Token Reinit(String newTerm, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset, String newType) { ClearNoTermBuffer(); SetTermBuffer(newTerm, newTermOffset, newTermLength); startOffset = newStartOffset; endOffset = newEndOffset; type = newType; return this; } /** Shorthand for calling {@link #clear}, * {@link #SetTermBuffer(String)}, * {@link #setStartOffset}, * {@link #setEndOffset} * {@link #setType} on Token.DEFAULT_TYPE * @return this Token instance */ public Token Reinit(String newTerm, int newStartOffset, int newEndOffset) { ClearNoTermBuffer(); SetTermBuffer(newTerm); startOffset = newStartOffset; endOffset = newEndOffset; type = DEFAULT_TYPE; return this; } /** Shorthand for calling {@link #clear}, * {@link #SetTermBuffer(String, int, int)}, * {@link #setStartOffset}, * {@link #setEndOffset} * {@link #setType} on Token.DEFAULT_TYPE * @return this Token instance */ public Token Reinit(String newTerm, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset) { ClearNoTermBuffer(); SetTermBuffer(newTerm, newTermOffset, newTermLength); startOffset = newStartOffset; endOffset = newEndOffset; type = DEFAULT_TYPE; return this; } /** * Copy the prototype token's fields into this one. Note: Payloads are shared. * @param prototype */ public void Reinit(Token prototype) { prototype.InitTermBuffer(); SetTermBuffer(prototype.termBuffer, 0, prototype.termLength); positionIncrement = prototype.positionIncrement; flags = prototype.flags; startOffset = prototype.startOffset; endOffset = prototype.endOffset; type = prototype.type; payload = prototype.payload; } /** * Copy the prototype token's fields into this one, with a different term. Note: Payloads are shared. * @param prototype * @param newTerm */ public void Reinit(Token prototype, String newTerm) { SetTermBuffer(newTerm); positionIncrement = prototype.positionIncrement; flags = prototype.flags; startOffset = prototype.startOffset; endOffset = prototype.endOffset; type = prototype.type; payload = prototype.payload; } /** * Copy the prototype token's fields into this one, with a different term. Note: Payloads are shared. * @param prototype * @param newTermBuffer * @param offset * @param length */ public void Reinit(Token prototype, char[] newTermBuffer, int offset, int length) { SetTermBuffer(newTermBuffer, offset, length); positionIncrement = prototype.positionIncrement; flags = prototype.flags; startOffset = prototype.startOffset; endOffset = prototype.endOffset; type = prototype.type; payload = prototype.payload; } } }
/* M2Mqtt Project - MQTT Client Library for .Net and GnatMQ MQTT Broker for .NET Copyright (c) 2014, Paolo Patierno, All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. */ using System; // if NOT .Net Micro Framework #if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) using System.Collections.Generic; #endif using System.Collections; using System.Text; using uPLibrary.Networking.M2Mqtt.Exceptions; namespace uPLibrary.Networking.M2Mqtt.Messages { /// <summary> /// Class for SUBSCRIBE message from client to broker /// </summary> public class MqttMsgSubscribe : MqttMsgBase { #region Properties... /// <summary> /// List of topics to subscribe /// </summary> public string[] Topics { get { return this.topics; } set { this.topics = value; } } /// <summary> /// List of QOS Levels related to topics /// </summary> public byte[] QoSLevels { get { return this.qosLevels; } set { this.qosLevels = value; } } /// <summary> /// Message identifier /// </summary> public ushort MessageId { get { return this.messageId; } set { this.messageId = value; } } #endregion // topics to subscribe string[] topics; // QOS levels related to topics byte[] qosLevels; // message identifier ushort messageId; /// <summary> /// Constructor /// </summary> public MqttMsgSubscribe() { this.type = MQTT_MSG_SUBSCRIBE_TYPE; } /// <summary> /// Constructor /// </summary> /// <param name="topics">List of topics to subscribe</param> /// <param name="qosLevels">List of QOS Levels related to topics</param> public MqttMsgSubscribe(string[] topics, byte[] qosLevels) { this.type = MQTT_MSG_SUBSCRIBE_TYPE; this.topics = topics; this.qosLevels = qosLevels; // SUBSCRIBE message uses QoS Level 1 this.qosLevel = QOS_LEVEL_AT_LEAST_ONCE; } /// <summary> /// Parse bytes for a SUBSCRIBE message /// </summary> /// <param name="fixedHeaderFirstByte">First fixed header byte</param> /// <param name="channel">Channel connected to the broker</param> /// <returns>SUBSCRIBE message instance</returns> public static MqttMsgSubscribe Parse(byte fixedHeaderFirstByte, IMqttNetworkChannel channel) { byte[] buffer; int index = 0; byte[] topicUtf8; int topicUtf8Length; MqttMsgSubscribe msg = new MqttMsgSubscribe(); // get remaining length and allocate buffer int remainingLength = MqttMsgBase.decodeRemainingLength(channel); buffer = new byte[remainingLength]; // read bytes from socket... int received = channel.Receive(buffer); // read QoS level from fixed header msg.qosLevel = (byte)((fixedHeaderFirstByte & QOS_LEVEL_MASK) >> QOS_LEVEL_OFFSET); // read DUP flag from fixed header msg.dupFlag = (((fixedHeaderFirstByte & DUP_FLAG_MASK) >> DUP_FLAG_OFFSET) == 0x01); // retain flag not used msg.retain = false; // message id msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); msg.messageId |= (buffer[index++]); // payload contains topics and QoS levels // NOTE : before, I don't know how many topics will be in the payload (so use List) // if .Net Micro Framework #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) IList tmpTopics = new ArrayList(); IList tmpQosLevels = new ArrayList(); // else other frameworks (.Net, .Net Compact, Mono, Windows Phone) #else IList<String> tmpTopics = new List<String>(); IList<byte> tmpQosLevels = new List<byte>(); #endif do { // topic name topicUtf8Length = ((buffer[index++] << 8) & 0xFF00); topicUtf8Length |= buffer[index++]; topicUtf8 = new byte[topicUtf8Length]; Array.Copy(buffer, index, topicUtf8, 0, topicUtf8Length); index += topicUtf8Length; tmpTopics.Add(new String(Encoding.UTF8.GetChars(topicUtf8))); // QoS level tmpQosLevels.Add(buffer[index++]); } while (index < remainingLength); // copy from list to array msg.topics = new string[tmpTopics.Count]; msg.qosLevels = new byte[tmpQosLevels.Count]; for (int i = 0; i < tmpTopics.Count; i++) { msg.topics[i] = (string)tmpTopics[i]; msg.qosLevels[i] = (byte)tmpQosLevels[i]; } return msg; } public override byte[] GetBytes() { int fixedHeaderSize = 0; int varHeaderSize = 0; int payloadSize = 0; int remainingLength = 0; byte[] buffer; int index = 0; // topics list empty if ((this.topics == null) || (this.topics.Length == 0)) throw new MqttClientException(MqttClientErrorCode.TopicsEmpty); // qos levels list empty if ((this.qosLevels == null) || (this.qosLevels.Length == 0)) throw new MqttClientException(MqttClientErrorCode.QosLevelsEmpty); // topics and qos levels lists length don't match if (this.topics.Length != this.qosLevels.Length) throw new MqttClientException(MqttClientErrorCode.TopicsQosLevelsNotMatch); // message identifier varHeaderSize += MESSAGE_ID_SIZE; int topicIdx = 0; byte[][] topicsUtf8 = new byte[this.topics.Length][]; for (topicIdx = 0; topicIdx < this.topics.Length; topicIdx++) { // check topic length if ((this.topics[topicIdx].Length < MIN_TOPIC_LENGTH) || (this.topics[topicIdx].Length > MAX_TOPIC_LENGTH)) throw new MqttClientException(MqttClientErrorCode.TopicLength); topicsUtf8[topicIdx] = Encoding.UTF8.GetBytes(this.topics[topicIdx]); payloadSize += 2; // topic size (MSB, LSB) payloadSize += topicsUtf8[topicIdx].Length; payloadSize++; // byte for QoS } remainingLength += (varHeaderSize + payloadSize); // first byte of fixed header fixedHeaderSize = 1; int temp = remainingLength; // increase fixed header size based on remaining length // (each remaining length byte can encode until 128) do { fixedHeaderSize++; temp = temp / 128; } while (temp > 0); // allocate buffer for message buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; // first fixed header byte buffer[index] = (byte)((MQTT_MSG_SUBSCRIBE_TYPE << MSG_TYPE_OFFSET) | (this.qosLevel << QOS_LEVEL_OFFSET)); buffer[index] |= this.dupFlag ? (byte)(1 << DUP_FLAG_OFFSET) : (byte)0x00; index++; // encode remaining length index = this.encodeRemainingLength(remainingLength, buffer, index); // check message identifier assigned (SUBSCRIBE uses QoS Level 1, so message id is mandatory) if (this.messageId == 0) throw new MqttClientException(MqttClientErrorCode.WrongMessageId); buffer[index++] = (byte)((messageId >> 8) & 0x00FF); // MSB buffer[index++] = (byte)(messageId & 0x00FF); // LSB topicIdx = 0; for (topicIdx = 0; topicIdx < this.topics.Length; topicIdx++) { // topic name buffer[index++] = (byte)((topicsUtf8[topicIdx].Length >> 8) & 0x00FF); // MSB buffer[index++] = (byte)(topicsUtf8[topicIdx].Length & 0x00FF); // LSB Array.Copy(topicsUtf8[topicIdx], 0, buffer, index, topicsUtf8[topicIdx].Length); index += topicsUtf8[topicIdx].Length; // requested QoS buffer[index++] = this.qosLevels[topicIdx]; } return buffer; } public override string ToString() { #if DEBUG return this.GetDebugString( "SUBSCRIBE", new object[] { "messageId", "topics", "qosLevels" }, new object[] { this.messageId, this.topics, this.qosLevels }); #else return base.ToString(); #endif } } }
using System; using Axiom.Core; /* Axiom Game Engine Library Copyright (C) 2006 Multiverse Corporation The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Axiom.Media { ///<summary> /// Class for manipulating bit patterns. ///</summary> public class Bitwise { ///<summary> /// Returns the most significant bit set in a value. ///</summary> public static uint MostSignificantBitSet(uint value) { uint result = 0; while (value != 0) { ++result; value >>= 1; } return result-1; } ///<summary> /// Returns the closest power-of-two number greater or equal to value. ///</summary> ///<remarks> /// 0 and 1 are powers of two, so firstPO2From(0)==0 and firstPO2From(1)==1. ///</remarks> public static uint FirstPO2From(uint n) { --n; n |= n >> 16; n |= n >> 8; n |= n >> 4; n |= n >> 2; n |= n >> 1; ++n; return n; } ///<summary> /// Convert N bit colour channel value to P bits. It fills P bits with the /// bit pattern repeated. (this is /((1<<n)-1) in fixed point) ///</summary> public static uint FixedToFixed(uint value, int n, int p) { if(n > p) // Less bits required than available; this is easy value >>= n - p; else if(n < p) { // More bits required than are there, do the fill // Use old fashioned division, probably better than a loop if(value == 0) value = 0; else if(value == ((uint)(1)<<n) - 1) value = (1u<<p)-1; else value = value * (1u<<p) / ((1u<<n) - 1u); } return value; } ///<summary> /// Convert N bit colour channel value to 8 bits, and return as a byte. It /// fills P bits with thebit pattern repeated. (this is /((1<<n)-1) in fixed point) ///</summary> public static byte FixedToByteFixed(uint value, int p) { return (byte)FixedToFixed(value, 8, p); } ///<summary> /// Convert floating point colour channel value between 0.0 and 1.0 (otherwise clamped) /// to integer of a certain number of bits. Works for any value of bits between 0 and 31. ///</summary> public static uint FloatToFixed(float value, int bits) { if(value <= 0.0f) return 0; else if (value >= 1.0f) return (1u<<bits)-1; else return (uint)(value * (1u<<bits)); } ///<summary> /// Convert floating point colour channel value between 0.0 and 1.0 (otherwise clamped) /// to an 8-bit integer, and return as a byte. ///</summary> public static byte FloatToByteFixed(float value) { return (byte)FloatToFixed(value, 8); } ///<summary> /// Fixed point to float ///</summary> public static float FixedToFloat(uint value, int bits) { return (float)value/(float)((1u<<bits)-1); } /** * Write a n*8 bits integer value to memory in native endian. */ unsafe public static void IntWrite(byte *dest, int n, uint value) { switch(n) { case 1: ((byte*)dest)[0] = (byte)value; break; case 2: ((ushort*)dest)[0] = (ushort)value; break; case 3: #if BIG_ENDIAN ((byte*)dest)[0] = (byte)((value >> 16) & 0xFF); ((byte*)dest)[1] = (byte)((value >> 8) & 0xFF); ((byte*)dest)[2] = (byte)(value & 0xFF); #else ((byte*)dest)[2] = (byte)((value >> 16) & 0xFF); ((byte*)dest)[1] = (byte)((value >> 8) & 0xFF); ((byte*)dest)[0] = (byte)(value & 0xFF); #endif break; case 4: ((uint*)dest)[0] = (uint)value; break; } } ///<summary> /// Read a n*8 bits integer value to memory in native endian. ///</summary> unsafe public static uint IntRead(byte *src, int n) { switch(n) { case 1: return ((byte*)src)[0]; case 2: return ((ushort*)src)[0]; case 3: #if BIG_ENDIAN return ((uint)((byte*)src)[0]<<16)| ((uint)((byte*)src)[1]<<8)| ((uint)((byte*)src)[2]); #else return ((uint)((byte*)src)[0])| ((uint)((byte*)src)[1]<<8)| ((uint)((byte*)src)[2]<<16); #endif case 4: return ((uint*)src)[0]; } return 0; // ? } private static float [] floatConversionBuffer = new float[] { 0f }; private static uint[] uintConversionBuffer = new uint[] { 0 }; ///<summary> /// Convert a float32 to a float16 (NV_half_float) /// Courtesy of OpenEXR ///</summary> public static ushort FloatToHalf(float f) { uint i; floatConversionBuffer[0] = f; unsafe { fixed (float* pFloat = floatConversionBuffer) { i = *((uint *)pFloat); } } return FloatToHalfI(i); } ///<summary> /// Converts float in uint format to a a half in ushort format ///</summary> public static ushort FloatToHalfI(uint i) { int s = (int)(i >> 16) & 0x00008000; int e = (int)((i >> 23) & 0x000000ff) - (127 - 15); int m = (int)i & 0x007fffff; if (e <= 0) { if (e < -10) { return 0; } m = (m | 0x00800000) >> (1 - e); return (ushort)(s | (m >> 13)); } else if (e == 0xff - (127 - 15)) { if (m == 0) // Inf { return (ushort)(s | 0x7c00); } else // NAN { m >>= 13; return (ushort)(s | 0x7c00 | m | (m == 0 ? 0x0001 : 0x0000)); } } else { if (e > 30) // Overflow { return (ushort)(s | 0x7c00); } return (ushort)(s | (e << 10) | (m >> 13)); } } ///<summary> /// Convert a float16 (NV_half_float) to a float32 /// Courtesy of OpenEXR ///</summary> public static float HalfToFloat(ushort y) { uintConversionBuffer[0] = HalfToFloatI(y); unsafe { fixed (uint* pUint = uintConversionBuffer) { return *((float *)pUint); } } } ///<summary> /// Converts a half in ushort format to a float /// in uint format ///</summary> public static uint HalfToFloatI(ushort y) { uint yuint = (uint)y; uint s = (yuint >> 15) & 0x00000001; uint e = (yuint >> 10) & 0x0000001f; uint m = yuint & 0x000003ff; if (e == 0) { if (m == 0) // Plus or minus zero return (s << 31); else { // Denormalized number -- renormalize it while ((m & 0x00000400) == 0) { m <<= 1; e -= 1; } e += 1; m &= 0xFFFFFBFF; // ~0x00000400; } } else if (e == 31) { if (m == 0) // Inf return (s << 31) | 0x7f800000; else // NaN return (s << 31) | 0x7f800000 | (m << 13); } e = e + (127 - 15); m = m << 13; return (s << 31) | (e << 23) | m; } } }
// 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.Globalization; using System.IO; using System.Reflection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; namespace System.Security.Cryptography.Xml { /// <summary> /// Trace support for debugging issues signing and verifying XML signatures. /// </summary> internal static class SignedXmlDebugLog { // // In order to enable XML digital signature debug loggging, applications should setup their config // file to be similar to the following: // // <configuration> // <system.diagnostics> // <sources> // <source name="System.Security.Cryptography.Xml.SignedXml" // switchName="XmlDsigLogSwitch"> // <listeners> // <add name="logFile" /> // </listeners> // </source> // </sources> // <switches> // <add name="XmlDsigLogSwitch" value="Verbose" /> // </switches> // <sharedListeners> // <add name="logFile" // type="System.Diagnostics.TextWriterTraceListener" // initializeData="XmlDsigLog.txt"/> // </sharedListeners> // <trace autoflush="true"> // <listeners> // <add name="logFile" /> // </listeners> // </trace> // </system.diagnostics> // </configuration> // private const string NullString = "(null)"; private static TraceSource s_traceSource = new TraceSource("System.Security.Cryptography.Xml.SignedXml"); private static volatile bool s_haveVerboseLogging; private static volatile bool s_verboseLogging; private static volatile bool s_haveInformationLogging; private static volatile bool s_informationLogging; /// <summary> /// Types of events that are logged to the debug log /// </summary> internal enum SignedXmlDebugEvent { /// <summary> /// Canonicalization of input XML has begun /// </summary> BeginCanonicalization, /// <summary> /// Verification of the signature format itself is beginning /// </summary> BeginCheckSignatureFormat, /// <summary> /// Verification of a signed info is beginning /// </summary> BeginCheckSignedInfo, /// <summary> /// Signing is beginning /// </summary> BeginSignatureComputation, /// <summary> /// Signature verification is beginning /// </summary> BeginSignatureVerification, /// <summary> /// Input data has been transformed to its canonicalized form /// </summary> CanonicalizedData, /// <summary> /// The result of signature format validation /// </summary> FormatValidationResult, /// <summary> /// Namespaces are being propigated into the signature /// </summary> NamespacePropagation, /// <summary> /// Output from a Reference /// </summary> ReferenceData, /// <summary> /// The result of a signature verification /// </summary> SignatureVerificationResult, /// <summary> /// Calculating the final signature /// </summary> Signing, /// <summary> /// A reference is being hashed /// </summary> SigningReference, /// <summary> /// A signature has failed to verify /// </summary> VerificationFailure, /// <summary> /// Verify that a reference has the correct hash value /// </summary> VerifyReference, /// <summary> /// Verification is processing the SignedInfo section of the signature /// </summary> VerifySignedInfo, /// <summary> /// Verification status on the x.509 certificate in use /// </summary> X509Verification, /// <summary> /// The signature is being rejected by the signature format verifier due to having /// a canonicalization algorithm which is not on the known valid list. /// </summary> UnsafeCanonicalizationMethod, /// <summary> /// The signature is being rejected by the signature verifier due to having /// a transform algorithm which is not on the known valid list. /// </summary> UnsafeTransformMethod, } /// <summary> /// Check to see if logging should be done in this process /// </summary> private static bool InformationLoggingEnabled { get { if (!s_haveInformationLogging) { s_informationLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Information); s_haveInformationLogging = true; } return s_informationLogging; } } /// <summary> /// Check to see if verbose log messages should be generated /// </summary> private static bool VerboseLoggingEnabled { get { if (!s_haveVerboseLogging) { s_verboseLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Verbose); s_haveVerboseLogging = true; } return s_verboseLogging; } } /// <summary> /// Convert the byte array into a hex string /// </summary> private static string FormatBytes(byte[] bytes) { if (bytes == null) return NullString; StringBuilder builder = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) { builder.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return builder.ToString(); } /// <summary> /// Map a key to a string describing the key /// </summary> private static string GetKeyName(object key) { Debug.Assert(key != null, "key != null"); ICspAsymmetricAlgorithm cspKey = key as ICspAsymmetricAlgorithm; X509Certificate certificate = key as X509Certificate; X509Certificate2 certificate2 = key as X509Certificate2; // // Use the following sources for key names, if available: // // * CAPI key -> key container name // * X509Certificate2 -> subject simple name // * X509Certificate -> subject name // * All others -> hash code // string keyName = null; if (cspKey != null && cspKey.CspKeyContainerInfo.KeyContainerName != null) { keyName = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", cspKey.CspKeyContainerInfo.KeyContainerName); } else if (certificate2 != null) { keyName = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", certificate2.GetNameInfo(X509NameType.SimpleName, false)); } else if (certificate != null) { keyName = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", certificate.Subject); } else { keyName = key.GetHashCode().ToString("x8", CultureInfo.InvariantCulture); } return string.Format(CultureInfo.InvariantCulture, "{0}#{1}", key.GetType().Name, keyName); } /// <summary> /// Map an object to a string describing the object /// </summary> private static string GetObjectId(object o) { Debug.Assert(o != null, "o != null"); return string.Format(CultureInfo.InvariantCulture, "{0}#{1}", o.GetType().Name, o.GetHashCode().ToString("x8", CultureInfo.InvariantCulture)); } /// <summary> /// Map an OID to the friendliest name possible /// </summary> private static string GetOidName(Oid oid) { Debug.Assert(oid != null, "oid != null"); string friendlyName = oid.FriendlyName; if (string.IsNullOrEmpty(friendlyName)) friendlyName = oid.Value; return friendlyName; } /// <summary> /// Log that canonicalization has begun on input data /// </summary> /// <param name="signedXml">SignedXml object doing the signing or verification</param> /// <param name="canonicalizationTransform">transform canonicalizing the input</param> internal static void LogBeginCanonicalization(SignedXml signedXml, Transform canonicalizationTransform) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_BeginCanonicalization, canonicalizationTransform.Algorithm, canonicalizationTransform.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCanonicalization, logMessage); } if (VerboseLoggingEnabled) { string canonicalizationSettings = string.Format(CultureInfo.InvariantCulture, SR.Log_CanonicalizationSettings, canonicalizationTransform.Resolver.GetType(), canonicalizationTransform.BaseURI); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginCanonicalization, canonicalizationSettings); } } /// <summary> /// Log that we're going to be validating the signature format itself /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="formatValidator">Callback delegate which is being used for format verification</param> internal static void LogBeginCheckSignatureFormat(SignedXml signedXml, Func<SignedXml, bool> formatValidator) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(formatValidator != null, "formatValidator != null"); if (InformationLoggingEnabled) { MethodInfo validationMethod = formatValidator.Method; string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_CheckSignatureFormat, validationMethod.Module.Assembly.FullName, validationMethod.DeclaringType.FullName, validationMethod.Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignatureFormat, logMessage); } } /// <summary> /// Log that checking SignedInfo is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="signedInfo">SignedInfo object being verified</param> internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signedInfo != null, " signedInfo != null"); if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_CheckSignedInfo, signedInfo.Id != null ? signedInfo.Id : NullString); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage); } } /// <summary> /// Log that signature computation is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the signing</param> /// <param name="context">Context of the signature</param> internal static void LogBeginSignatureComputation(SignedXml signedXml, XmlElement context) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginSignatureComputation, SR.Log_BeginSignatureComputation); } if (VerboseLoggingEnabled) { string contextData = string.Format(CultureInfo.InvariantCulture, SR.Log_XmlContext, context != null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginSignatureComputation, contextData); } } /// <summary> /// Log that signature verification is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="context">Context of the verification</param> internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement context) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginSignatureVerification, SR.Log_BeginSignatureVerification); } if (VerboseLoggingEnabled) { string contextData = string.Format(CultureInfo.InvariantCulture, SR.Log_XmlContext, context != null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginSignatureVerification, contextData); } } /// <summary> /// Log the canonicalized data /// </summary> /// <param name="signedXml">SignedXml object doing the signing or verification</param> /// <param name="canonicalizationTransform">transform canonicalizing the input</param> internal static void LogCanonicalizedOutput(SignedXml signedXml, Transform canonicalizationTransform) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); if (VerboseLoggingEnabled) { using (StreamReader reader = new StreamReader(canonicalizationTransform.GetOutput(typeof(Stream)) as Stream)) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_CanonicalizedOutput, reader.ReadToEnd()); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.CanonicalizedData, logMessage); } } } /// <summary> /// Log that the signature format callback has rejected the signature /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="result">result of the signature format verification</param> internal static void LogFormatValidationResult(SignedXml signedXml, bool result) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { string logMessage = result ? SR.Log_FormatValidationSuccessful : SR.Log_FormatValidationNotSuccessful; WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.FormatValidationResult, logMessage); } } /// <summary> /// Log that a signature is being rejected as having an invalid format due to its canonicalization /// algorithm not being on the valid list. /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="result">result of the signature format verification</param> internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string algorithm, IEnumerable<string> validAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(validAlgorithms != null, "validAlgorithms != null"); if (InformationLoggingEnabled) { StringBuilder validAlgorithmBuilder = new StringBuilder(); foreach (string validAlgorithm in validAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_UnsafeCanonicalizationMethod, algorithm, validAlgorithmBuilder.ToString()); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeCanonicalizationMethod, logMessage); } } /// <summary> /// Log that a signature is being rejected as having an invalid signature due to a transform /// algorithm not being on the valid list. /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="algorithm">Transform algorithm that was not allowed</param> /// <param name="validC14nAlgorithms">The valid C14N algorithms</param> /// <param name="validTransformAlgorithms">The valid C14N algorithms</param> internal static void LogUnsafeTransformMethod( SignedXml signedXml, string algorithm, IEnumerable<string> validC14nAlgorithms, IEnumerable<string> validTransformAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(validC14nAlgorithms != null, "validC14nAlgorithms != null"); Debug.Assert(validTransformAlgorithms != null, "validTransformAlgorithms != null"); if (InformationLoggingEnabled) { StringBuilder validAlgorithmBuilder = new StringBuilder(); foreach (string validAlgorithm in validC14nAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } foreach (string validAlgorithm in validTransformAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_UnsafeTransformMethod, algorithm, validAlgorithmBuilder.ToString()); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeTransformMethod, logMessage); } } /// <summary> /// Log namespaces which are being propagated into the signature /// </summary> /// <param name="signedXml">SignedXml doing the signing or verification</param> /// <param name="namespaces">namespaces being propagated</param> internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList namespaces) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { if (namespaces != null) { foreach (XmlAttribute propagatedNamespace in namespaces) { string propagationMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_PropagatingNamespace, propagatedNamespace.Name, propagatedNamespace.Value); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.NamespacePropagation, propagationMessage); } } else { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.NamespacePropagation, SR.Log_NoNamespacesPropagated); } } } /// <summary> /// Log the output of a reference /// </summary> /// <param name="reference">The reference being processed</param> /// <param name="data">Stream containing the output of the reference</param> /// <returns>Stream containing the output of the reference</returns> internal static Stream LogReferenceData(Reference reference, Stream data) { if (VerboseLoggingEnabled) { // // Since the input data stream could be from the network or another source that does not // support rewinding, we will read the stream into a temporary MemoryStream that can be used // to stringify the output and also return to the reference so that it can produce the hash // value. // MemoryStream ms = new MemoryStream(); // First read the input stream into our temporary stream byte[] buffer = new byte[4096]; int readBytes = 0; do { readBytes = data.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, readBytes); } while (readBytes == buffer.Length); // Log out information about it string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_TransformedReferenceContents, Encoding.UTF8.GetString(ms.ToArray())); WriteLine(reference, TraceEventType.Verbose, SignedXmlDebugEvent.ReferenceData, logMessage); // Rewind to the beginning, so that the entire input stream is hashed ms.Seek(0, SeekOrigin.Begin); return ms; } else { return data; } } /// <summary> /// Log the computation of a signature value when signing with an asymmetric algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key used for signing</param> /// <param name="signatureDescription">signature description being used to create the signature</param> /// <param name="hash">hash algorithm used to digest the output</param> /// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param> internal static void LogSigning(SignedXml signedXml, object key, SignatureDescription signatureDescription, HashAlgorithm hash, AsymmetricSignatureFormatter asymmetricSignatureFormatter) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hash != null, "hash != null"); Debug.Assert(asymmetricSignatureFormatter != null, "asymmetricSignatureFormatter != null"); if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_SigningAsymmetric, GetKeyName(key), signatureDescription.GetType().Name, hash.GetType().Name, asymmetricSignatureFormatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } } /// <summary> /// Log the computation of a signature value when signing with a keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key the signature is created with</param> /// <param name="hash">hash algorithm used to digest the output</param> /// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param> internal static void LogSigning(SignedXml signedXml, KeyedHashAlgorithm key) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_SigningHmac, key.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } } /// <summary> /// Log the calculation of a hash value of a reference /// </summary> /// <param name="signedXml">SignedXml object driving the signature</param> /// <param name="reference">Reference being hashed</param> internal static void LogSigningReference(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (VerboseLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_SigningReference, GetObjectId(reference), reference.Uri, reference.Id, reference.Type, reference.DigestMethod, hashAlgorithmName); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.SigningReference, logMessage); } } /// <summary> /// Log the specific point where a signature is determined to not be verifiable /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="failureLocation">location that the signature was determined to be invalid</param> internal static void LogVerificationFailure(SignedXml signedXml, string failureLocation) { if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_VerificationFailed, failureLocation); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerificationFailure, logMessage); } } /// <summary> /// Log the success or failure of a signature verification operation /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">public key used to verify the signature</param> /// <param name="verified">true if the signature verified, false otherwise</param> internal static void LogVerificationResult(SignedXml signedXml, object key, bool verified) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string resource = verified ? SR.Log_VerificationWithKeySuccessful : SR.Log_VerificationWithKeyNotSuccessful; string logMessage = string.Format(CultureInfo.InvariantCulture, resource, GetKeyName(key)); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.SignatureVerificationResult, logMessage); } } /// <summary> /// Log the check for appropriate X509 key usage /// </summary> /// <param name="signedXml">SignedXml doing the signature verification</param> /// <param name="certificate">certificate having its key usages checked</param> /// <param name="keyUsages">key usages being examined</param> internal static void LogVerifyKeyUsage(SignedXml signedXml, X509Certificate certificate, X509KeyUsageExtension keyUsages) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(certificate != null, "certificate != null"); if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_KeyUsages, keyUsages.KeyUsages, GetOidName(keyUsages.Oid), GetKeyName(certificate)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, logMessage); } } /// <summary> /// Log that we are verifying a reference /// </summary> /// <param name="signedXml">SignedXMl object doing the verification</param> /// <param name="reference">reference being verified</param> internal static void LogVerifyReference(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_VerifyReference, GetObjectId(reference), reference.Uri, reference.Id, reference.Type); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifyReference, logMessage); } } /// <summary> /// Log the hash comparison when verifying a reference /// </summary> /// <param name="signedXml">SignedXml object verifying the signature</param> /// <param name="reference">reference being verified</param> /// <param name="actualHash">actual hash value of the reference</param> /// <param name="expectedHash">hash value the signature expected the reference to have</param> internal static void LogVerifyReferenceHash(SignedXml signedXml, Reference reference, byte[] actualHash, byte[] expectedHash) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); Debug.Assert(actualHash != null, "actualHash != null"); Debug.Assert(expectedHash != null, "expectedHash != null"); if (VerboseLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_ReferenceHash, GetObjectId(reference), reference.DigestMethod, hashAlgorithmName, FormatBytes(actualHash), FormatBytes(expectedHash)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifyReference, logMessage); } } /// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using an /// asymmetric key /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">key being used to verify the signed info</param> /// <param name="signatureDescription">type of signature description class used</param> /// <param name="hashAlgorithm">type of hash algorithm used</param> /// <param name="asymmetricSignatureDeformatter">type of signature deformatter used</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, AsymmetricAlgorithm key, SignatureDescription signatureDescription, HashAlgorithm hashAlgorithm, AsymmetricSignatureDeformatter asymmetricSignatureDeformatter, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null"); Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null"); if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_VerifySignedInfoAsymmetric, GetKeyName(key), signatureDescription.GetType().Name, hashAlgorithm.GetType().Name, asymmetricSignatureDeformatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = string.Format(CultureInfo.InvariantCulture, SR.Log_ActualHashValue, FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = string.Format(CultureInfo.InvariantCulture, SR.Log_RawSignatureValue, FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } } /// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using a /// keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="mac">hash algorithm doing the verification</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, KeyedHashAlgorithm mac, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(mac != null, "mac != null"); if (InformationLoggingEnabled) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_VerifySignedInfoHmac, mac.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = string.Format(CultureInfo.InvariantCulture, SR.Log_ActualHashValue, FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = string.Format(CultureInfo.InvariantCulture, SR.Log_RawSignatureValue, FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } } /// <summary> /// Log that an X509 chain is being built for a certificate /// </summary> /// <param name="signedXml">SignedXml object building the chain</param> /// <param name="chain">chain built for the certificate</param> /// <param name="certificate">certificate having the chain built for it</param> internal static void LogVerifyX509Chain(SignedXml signedXml, X509Chain chain, X509Certificate certificate) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(certificate != null, "certificate != null"); Debug.Assert(chain != null, "chain != null"); if (InformationLoggingEnabled) { string buildMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_BuildX509Chain, GetKeyName(certificate)); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.X509Verification, buildMessage); } if (VerboseLoggingEnabled) { // Dump out the flags and other miscelanious information used for building string revocationMode = string.Format(CultureInfo.InvariantCulture, SR.Log_RevocationMode, chain.ChainPolicy.RevocationFlag); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationMode); string revocationFlag = string.Format(CultureInfo.InvariantCulture, SR.Log_RevocationFlag, chain.ChainPolicy.RevocationFlag); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationFlag); string verificationFlags = string.Format(CultureInfo.InvariantCulture, SR.Log_VerificationFlag, chain.ChainPolicy.VerificationFlags); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationFlags); string verificationTime = string.Format(CultureInfo.InvariantCulture, SR.Log_VerificationTime, chain.ChainPolicy.VerificationTime); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationTime); string urlTimeout = string.Format(CultureInfo.InvariantCulture, SR.Log_UrlTimeout, chain.ChainPolicy.UrlRetrievalTimeout); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, urlTimeout); } // If there were any errors in the chain, make sure to dump those out if (InformationLoggingEnabled) { foreach (X509ChainStatus status in chain.ChainStatus) { if (status.Status != X509ChainStatusFlags.NoError) { string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_X509ChainError, status.Status, status.StatusInformation); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.X509Verification, logMessage); } } } // Finally, dump out the chain itself if (VerboseLoggingEnabled) { StringBuilder chainElements = new StringBuilder(); chainElements.Append(SR.Log_CertificateChain); foreach (X509ChainElement element in chain.ChainElements) { chainElements.AppendFormat(CultureInfo.InvariantCulture, " {0}", GetKeyName(element.Certificate)); } WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, chainElements.ToString()); } } /// <summary> /// Write information when user hits the Signed XML recursion depth limit issue. /// This is helpful in debugging this kind of issues. /// </summary> /// <param name="signedXml">SignedXml object verifying the signature</param> /// <param name="reference">reference being verified</param> internal static void LogSignedXmlRecursionLimit(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (InformationLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = string.Format(CultureInfo.InvariantCulture, SR.Log_SignedXmlRecursionLimit, GetObjectId(reference), reference.DigestMethod, hashAlgorithmName); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } } /// <summary> /// Write data to the log /// </summary> /// <param name="source">object doing the trace</param> /// <param name="eventType">severity of the debug event</param> /// <param name="data">data being written</param> /// <param name="eventId">type of event being traced</param> private static void WriteLine(object source, TraceEventType eventType, SignedXmlDebugEvent eventId, string data) { Debug.Assert(source != null, "source != null"); Debug.Assert(!string.IsNullOrEmpty(data), "!string.IsNullOrEmpty(data)"); Debug.Assert(InformationLoggingEnabled, "InformationLoggingEnabled"); s_traceSource.TraceEvent(eventType, (int)eventId, "[{0}, {1}] {2}", GetObjectId(source), eventId, data); } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Commons.Logging.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Commons.Logging { /// <summary> /// <para>A simple logging interface abstracting logging APIs. In order to be instantiated successfully by LogFactory, classes that implement this interface must have a constructor that takes a single String parameter representing the "name" of this Log.</para><para>The six logging levels used by <code>Log</code> are (in order): <ol><li><para>trace (the least serious) </para></li><li><para>debug </para></li><li><para>info </para></li><li><para>warn </para></li><li><para>error </para></li><li><para>fatal (the most serious) </para></li></ol>The mapping of these log levels to the concepts used by the underlying logging system is implementation dependent. The implemention should ensure, though, that this ordering behaves as expected.</para><para>Performance is often a logging concern. By examining the appropriate property, a component can avoid expensive operations (producing information to be logged).</para><para>For example, <code><pre> /// if (log.isDebugEnabled()) { /// ... do something expensive ... /// log.debug(theResult); /// } /// </pre></code> </para><para>Configuration of the underlying logging system will generally be done external to the Logging APIs, through whatever mechanism is supported by that system.</para><para><para> </para><simplesectsep></simplesectsep><para>Rod Waldhoff </para><para></para><title>Id:</title><para>Log.java 381838 2006-02-28 23:57:11Z skitching </para></para> /// </summary> /// <java-name> /// org/apache/commons/logging/Log /// </java-name> [Dot42.DexImport("org/apache/commons/logging/Log", AccessFlags = 1537)] public partial interface ILog /* scope: __dot42__ */ { /// <summary> /// <para>Is debug logging currently enabled? </para><para>Call this method to prevent having to perform expensive operations (for example, <code>String</code> concatenation) when the log level is more than debug. </para><para></para> /// </summary> /// <returns> /// <para>true if debug is enabled in the underlying logger. </para> /// </returns> /// <java-name> /// isDebugEnabled /// </java-name> [Dot42.DexImport("isDebugEnabled", "()Z", AccessFlags = 1025)] bool IsDebugEnabled() /* MethodBuilder.Create */ ; /// <summary> /// <para>Is error logging currently enabled? </para><para>Call this method to prevent having to perform expensive operations (for example, <code>String</code> concatenation) when the log level is more than error. </para><para></para> /// </summary> /// <returns> /// <para>true if error is enabled in the underlying logger. </para> /// </returns> /// <java-name> /// isErrorEnabled /// </java-name> [Dot42.DexImport("isErrorEnabled", "()Z", AccessFlags = 1025)] bool IsErrorEnabled() /* MethodBuilder.Create */ ; /// <summary> /// <para>Is fatal logging currently enabled? </para><para>Call this method to prevent having to perform expensive operations (for example, <code>String</code> concatenation) when the log level is more than fatal. </para><para></para> /// </summary> /// <returns> /// <para>true if fatal is enabled in the underlying logger. </para> /// </returns> /// <java-name> /// isFatalEnabled /// </java-name> [Dot42.DexImport("isFatalEnabled", "()Z", AccessFlags = 1025)] bool IsFatalEnabled() /* MethodBuilder.Create */ ; /// <summary> /// <para>Is info logging currently enabled? </para><para>Call this method to prevent having to perform expensive operations (for example, <code>String</code> concatenation) when the log level is more than info. </para><para></para> /// </summary> /// <returns> /// <para>true if info is enabled in the underlying logger. </para> /// </returns> /// <java-name> /// isInfoEnabled /// </java-name> [Dot42.DexImport("isInfoEnabled", "()Z", AccessFlags = 1025)] bool IsInfoEnabled() /* MethodBuilder.Create */ ; /// <summary> /// <para>Is trace logging currently enabled? </para><para>Call this method to prevent having to perform expensive operations (for example, <code>String</code> concatenation) when the log level is more than trace. </para><para></para> /// </summary> /// <returns> /// <para>true if trace is enabled in the underlying logger. </para> /// </returns> /// <java-name> /// isTraceEnabled /// </java-name> [Dot42.DexImport("isTraceEnabled", "()Z", AccessFlags = 1025)] bool IsTraceEnabled() /* MethodBuilder.Create */ ; /// <summary> /// <para>Is warn logging currently enabled? </para><para>Call this method to prevent having to perform expensive operations (for example, <code>String</code> concatenation) when the log level is more than warn. </para><para></para> /// </summary> /// <returns> /// <para>true if warn is enabled in the underlying logger. </para> /// </returns> /// <java-name> /// isWarnEnabled /// </java-name> [Dot42.DexImport("isWarnEnabled", "()Z", AccessFlags = 1025)] bool IsWarnEnabled() /* MethodBuilder.Create */ ; /// <summary> /// <para>Log a message with trace log level. </para><para></para> /// </summary> /// <java-name> /// trace /// </java-name> [Dot42.DexImport("trace", "(Ljava/lang/Object;)V", AccessFlags = 1025)] void Trace(object message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log an error with trace log level. </para><para></para> /// </summary> /// <java-name> /// trace /// </java-name> [Dot42.DexImport("trace", "(Ljava/lang/Object;Ljava/lang/Throwable;)V", AccessFlags = 1025)] void Trace(object message, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log a message with debug log level. </para><para></para> /// </summary> /// <java-name> /// debug /// </java-name> [Dot42.DexImport("debug", "(Ljava/lang/Object;)V", AccessFlags = 1025)] void Debug(object message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log an error with debug log level. </para><para></para> /// </summary> /// <java-name> /// debug /// </java-name> [Dot42.DexImport("debug", "(Ljava/lang/Object;Ljava/lang/Throwable;)V", AccessFlags = 1025)] void Debug(object message, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log a message with info log level. </para><para></para> /// </summary> /// <java-name> /// info /// </java-name> [Dot42.DexImport("info", "(Ljava/lang/Object;)V", AccessFlags = 1025)] void Info(object message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log an error with info log level. </para><para></para> /// </summary> /// <java-name> /// info /// </java-name> [Dot42.DexImport("info", "(Ljava/lang/Object;Ljava/lang/Throwable;)V", AccessFlags = 1025)] void Info(object message, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log a message with warn log level. </para><para></para> /// </summary> /// <java-name> /// warn /// </java-name> [Dot42.DexImport("warn", "(Ljava/lang/Object;)V", AccessFlags = 1025)] void Warn(object message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log an error with warn log level. </para><para></para> /// </summary> /// <java-name> /// warn /// </java-name> [Dot42.DexImport("warn", "(Ljava/lang/Object;Ljava/lang/Throwable;)V", AccessFlags = 1025)] void Warn(object message, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log a message with error log level. </para><para></para> /// </summary> /// <java-name> /// error /// </java-name> [Dot42.DexImport("error", "(Ljava/lang/Object;)V", AccessFlags = 1025)] void Error(object message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log an error with error log level. </para><para></para> /// </summary> /// <java-name> /// error /// </java-name> [Dot42.DexImport("error", "(Ljava/lang/Object;Ljava/lang/Throwable;)V", AccessFlags = 1025)] void Error(object message, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log a message with fatal log level. </para><para></para> /// </summary> /// <java-name> /// fatal /// </java-name> [Dot42.DexImport("fatal", "(Ljava/lang/Object;)V", AccessFlags = 1025)] void Fatal(object message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Log an error with fatal log level. </para><para></para> /// </summary> /// <java-name> /// fatal /// </java-name> [Dot42.DexImport("fatal", "(Ljava/lang/Object;Ljava/lang/Throwable;)V", AccessFlags = 1025)] void Fatal(object message, global::System.Exception t) /* MethodBuilder.Create */ ; } }
using System; using System.ComponentModel; using System.Linq; using Xamarin.Forms; using SignaturePad.Forms; using Color = Xamarin.Forms.Color; using Point = Xamarin.Forms.Point; #if WINDOWS_PHONE using Xamarin.Forms.Platform.WinPhone; using NativeSignaturePadCanvasView = Xamarin.Controls.SignaturePadCanvasView; using NativePoint = System.Windows.Point; #elif WINDOWS_UWP using Xamarin.Forms.Platform.UWP; using NativeSignaturePadCanvasView = Xamarin.Controls.SignaturePadCanvasView; using NativePoint = Windows.Foundation.Point; #elif WINDOWS_PHONE_APP || WINDOWS_APP using Xamarin.Forms.Platform.WinRT; using NativeSignaturePadCanvasView = Xamarin.Controls.SignaturePadCanvasView; using NativePoint = Windows.Foundation.Point; #elif __IOS__ using Xamarin.Forms.Platform.iOS; using NativeSignaturePadCanvasView = Xamarin.Controls.SignaturePadCanvasView; using NativePoint = CoreGraphics.CGPoint; #elif __ANDROID__ using Xamarin.Forms.Platform.Android; using NativeSignaturePadCanvasView = Xamarin.Controls.SignaturePadCanvasView; using NativePoint = System.Drawing.PointF; #endif [assembly: ExportRenderer (typeof (SignaturePadCanvasView), typeof (SignaturePadCanvasRenderer))] namespace SignaturePad.Forms { public class SignaturePadCanvasRenderer : ViewRenderer<SignaturePadCanvasView, NativeSignaturePadCanvasView> { #if __ANDROID__ [Obsolete ("This constructor is obsolete as of version 2.5. Please use 'SignaturePadCanvasRenderer (Context)' instead.")] #endif public SignaturePadCanvasRenderer () { } #if __ANDROID__ public SignaturePadCanvasRenderer (Android.Content.Context context) : base (context) { } #endif protected override void OnElementChanged (ElementChangedEventArgs<SignaturePadCanvasView> e) { base.OnElementChanged (e); if (Control == null && e.NewElement != null) { // Instantiate the native control and assign it to the Control property #if __ANDROID__ var native = new NativeSignaturePadCanvasView (Context); #else var native = new NativeSignaturePadCanvasView (); #endif native.StrokeCompleted += OnStrokeCompleted; native.Cleared += OnCleared; SetNativeControl (native); } if (e.OldElement != null) { // Unsubscribe from event handlers and cleanup any resources e.OldElement.ImageStreamRequested -= OnImageStreamRequested; e.OldElement.IsBlankRequested -= OnIsBlankRequested; e.OldElement.PointsRequested -= OnPointsRequested; e.OldElement.PointsSpecified -= OnPointsSpecified; e.OldElement.StrokesRequested -= OnStrokesRequested; e.OldElement.StrokesSpecified -= OnStrokesSpecified; e.OldElement.ClearRequested -= OnClearRequested; } if (e.NewElement != null) { // Configure the control and subscribe to event handlers e.NewElement.ImageStreamRequested += OnImageStreamRequested; e.NewElement.IsBlankRequested += OnIsBlankRequested; e.NewElement.PointsRequested += OnPointsRequested; e.NewElement.PointsSpecified += OnPointsSpecified; e.NewElement.StrokesRequested += OnStrokesRequested; e.NewElement.StrokesSpecified += OnStrokesSpecified; e.NewElement.ClearRequested += OnClearRequested; UpdateAll (); } } protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged (sender, e); Update (e.PropertyName); } private void OnStrokeCompleted (object sender, EventArgs e) { Element?.OnStrokeCompleted (); } private void OnCleared (object sender, EventArgs e) { Element?.OnCleared (); } private void OnImageStreamRequested (object sender, SignaturePadCanvasView.ImageStreamRequestedEventArgs e) { var ctrl = Control; if (ctrl != null) { var format = e.ImageFormat == SignatureImageFormat.Png ? Xamarin.Controls.SignatureImageFormat.Png : Xamarin.Controls.SignatureImageFormat.Jpeg; var settings = new Xamarin.Controls.ImageConstructionSettings (); if (e.Settings.BackgroundColor.HasValue) { settings.BackgroundColor = e.Settings.BackgroundColor.Value.ToNative (); } if (e.Settings.DesiredSizeOrScale.HasValue) { var val = e.Settings.DesiredSizeOrScale.Value; settings.DesiredSizeOrScale = new Xamarin.Controls.SizeOrScale (val.X, val.Y, (Xamarin.Controls.SizeOrScaleType)(int)val.Type, val.KeepAspectRatio); } settings.ShouldCrop = e.Settings.ShouldCrop; if (e.Settings.StrokeColor.HasValue) { settings.StrokeColor = e.Settings.StrokeColor.Value.ToNative (); } settings.StrokeWidth = e.Settings.StrokeWidth; settings.Padding = e.Settings.Padding; e.ImageStreamTask = ctrl.GetImageStreamAsync (format, settings); } } private void OnIsBlankRequested (object sender, SignaturePadCanvasView.IsBlankRequestedEventArgs e) { var ctrl = Control; if (ctrl != null) { e.IsBlank = ctrl.IsBlank; } } private void OnPointsRequested (object sender, SignaturePadCanvasView.PointsEventArgs e) { var ctrl = Control; if (ctrl != null) { e.Points = ctrl.Points.Select (p => new Point (p.X, p.Y)); } } private void OnPointsSpecified (object sender, SignaturePadCanvasView.PointsEventArgs e) { var ctrl = Control; if (ctrl != null) { ctrl.LoadPoints (e.Points.Select (p => new NativePoint ((float)p.X, (float)p.Y)).ToArray ()); } } private void OnStrokesRequested (object sender, SignaturePadCanvasView.StrokesEventArgs e) { var ctrl = Control; if (ctrl != null) { e.Strokes = ctrl.Strokes.Select (s => s.Select (p => new Point (p.X, p.Y))); } } private void OnStrokesSpecified (object sender, SignaturePadCanvasView.StrokesEventArgs e) { var ctrl = Control; if (ctrl != null) { ctrl.LoadStrokes (e.Strokes.Select (s => s.Select (p => new NativePoint ((float)p.X, (float)p.Y)).ToArray ()).ToArray ()); } } private void OnClearRequested (object sender, EventArgs e) { var ctrl = Control; if (ctrl != null) { ctrl.Clear (); } } /// <summary> /// Update all the properties on the native view. /// </summary> private void UpdateAll () { if (Control == null || Element == null) { return; } if (Element.StrokeColor != Color.Default) { Control.StrokeColor = Element.StrokeColor.ToNative (); } if (Element.StrokeWidth > 0) { Control.StrokeWidth = Element.StrokeWidth; } } /// <summary> /// Update a specific property on the native view. /// </summary> private void Update (string property) { if (Control == null || Element == null) { return; } if (property == SignaturePadCanvasView.StrokeColorProperty.PropertyName) { Control.StrokeColor = Element.StrokeColor.ToNative (); } else if (property == SignaturePadCanvasView.StrokeWidthProperty.PropertyName) { Control.StrokeWidth = Element.StrokeWidth; } } } }
// 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 System.IO; using System.Linq; using System.Xml; using System.Text; using System.Collections; using System.Text.RegularExpressions; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.BackEnd; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { public class BuildRequestConfiguration_Tests { [Fact] public void TestConstructorNullFile() { Assert.Throws<ArgumentNullException>(() => { BuildRequestData config1 = new BuildRequestData(null, new Dictionary<string, string>(), "toolsVersion", new string[0], null); } ); } [Fact] public void TestConstructorNullProps() { Assert.Throws<ArgumentNullException>(() => { BuildRequestData config1 = new BuildRequestData("file", null, "toolsVersion", new string[0], null); } ); } [Fact] public void TestConstructor1() { BuildRequestData config1 = new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null); } [Fact] public void TestConstructorInvalidConfigId() { Assert.Throws<InternalErrorException>(() => { BuildRequestData data = new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(1, data, "2.0"); config1.ShallowCloneWithNewId(0); } ); } [Fact] public void TestConstructor2PositiveConfigId() { BuildRequestData config1 = new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null); new BuildRequestConfiguration(1, config1, "2.0"); } [Fact] public void TestConstructor2NegativeConfigId() { BuildRequestData config1 = new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null); new BuildRequestConfiguration(-1, config1, "2.0"); } [Fact] public void TestConstructor2NullFile() { Assert.Throws<ArgumentNullException>(() => { BuildRequestData config1 = new BuildRequestData(null, new Dictionary<string, string>(), "toolsVersion", new string[0], null); } ); } [Fact] public void TestConstructor2NullProps() { Assert.Throws<ArgumentNullException>(() => { BuildRequestData config1 = new BuildRequestData("file", null, "toolsVersion", new string[0], null); } ); } [Fact] public void TestWasGeneratedByNode() { BuildRequestData data1 = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(-1, data1, "2.0"); Assert.True(config1.WasGeneratedByNode); BuildRequestData data2 = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config2 = new BuildRequestConfiguration(1, data2, "2.0"); Assert.False(config2.WasGeneratedByNode); BuildRequestData data3 = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config3 = new BuildRequestConfiguration(data3, "2.0"); Assert.False(config3.WasGeneratedByNode); } [Fact] public void TestDefaultConfigurationId() { BuildRequestData data1 = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(-1, data1, "2.0"); Assert.Equal(-1, config1.ConfigurationId); BuildRequestData data2 = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config2 = new BuildRequestConfiguration(1, data2, "2.0"); Assert.Equal(1, config2.ConfigurationId); BuildRequestData data3 = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config3 = new BuildRequestConfiguration(0, data3, "2.0"); Assert.Equal(0, config3.ConfigurationId); } [Fact] public void TestSetConfigurationIdBad() { Assert.Throws<InternalErrorException>(() => { BuildRequestData data = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(-1, data, "2.0"); config1.ConfigurationId = -2; } ); } [Fact] public void TestSetConfigurationIdGood() { BuildRequestData data = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(data, "2.0"); Assert.Equal(0, config1.ConfigurationId); config1.ConfigurationId = 1; Assert.Equal(1, config1.ConfigurationId); } [Fact] public void TestGetFileName() { BuildRequestData data = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(data, "2.0"); Assert.Equal(config1.ProjectFullPath, Path.GetFullPath("file")); } [Fact] public void TestGetToolsVersion() { BuildRequestData data1 = new BuildRequestData("file", new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(data1, "2.0"); Assert.Equal("toolsVersion", config1.ToolsVersion); } [Fact] public void TestGetProperties() { Dictionary<string, string> props = new Dictionary<string, string>(); BuildRequestConfiguration config1 = new BuildRequestConfiguration(new BuildRequestData("file", props, "toolsVersion", new string[0], null), "2.0"); Assert.Equal(props.Count, Helpers.MakeList((IEnumerable<ProjectPropertyInstance>)(config1.GlobalProperties)).Count); } [Fact] public void TestSetProjectGood() { BuildRequestData data1 = new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(data1, "2.0"); Assert.Null(config1.Project); Project project = new Project(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace' />")))); ProjectInstance projectInstance = project.CreateProjectInstance(); config1.Project = projectInstance; Assert.Same(config1.Project, projectInstance); } [Fact] public void TestPacketType() { BuildRequestData data1 = new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(data1, "2.0"); Assert.Equal(NodePacketType.BuildRequestConfiguration, config1.Type); } [Fact] public void TestGetHashCode() { BuildRequestConfiguration config1 = new BuildRequestConfiguration(new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null), "2.0"); BuildRequestConfiguration config2 = new BuildRequestConfiguration(new BuildRequestData("File", new Dictionary<string, string>(), "ToolsVersion", new string[0], null), "2.0"); BuildRequestConfiguration config3 = new BuildRequestConfiguration(new BuildRequestData("file2", new Dictionary<string, string>(), "toolsVersion", new string[0], null), "2.0"); BuildRequestConfiguration config4 = new BuildRequestConfiguration(new BuildRequestData("file2", new Dictionary<string, string>(), "toolsVersion2", new string[0], null), "2.0"); BuildRequestConfiguration config5 = new BuildRequestConfiguration(new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion2", new string[0], null), "2.0"); Assert.Equal(config1.GetHashCode(), config2.GetHashCode()); Assert.NotEqual(config1.GetHashCode(), config3.GetHashCode()); Assert.NotEqual(config1.GetHashCode(), config5.GetHashCode()); Assert.NotEqual(config4.GetHashCode(), config5.GetHashCode()); } [Fact] public void TestEquals() { BuildRequestConfiguration config1 = new BuildRequestConfiguration(new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null), "2.0"); Assert.Equal(config1, config1); BuildRequestConfiguration config2 = new BuildRequestConfiguration(new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion", new string[0], null), "2.0"); Assert.Equal(config1, config2); BuildRequestConfiguration config3 = new BuildRequestConfiguration(new BuildRequestData("file2", new Dictionary<string, string>(), "toolsVersion", new string[0], null), "2.0"); Assert.NotEqual(config1, config3); BuildRequestConfiguration config4 = new BuildRequestConfiguration(new BuildRequestData("file", new Dictionary<string, string>(), "toolsVersion2", new string[0], null), "2.0"); Assert.NotEqual(config1, config4); PropertyDictionary<ProjectPropertyInstance> props = new PropertyDictionary<ProjectPropertyInstance>(); props.Set(ProjectPropertyInstance.Create("prop1", "value1")); BuildRequestData data = new BuildRequestData("file", props.ToDictionary(), "toolsVersion", new string[0], null); BuildRequestConfiguration config5 = new BuildRequestConfiguration(data, "2.0"); Assert.NotEqual(config1, config5); Assert.Equal(config1, config2); Assert.NotEqual(config1, config3); } [Fact] public void TestTranslation() { PropertyDictionary<ProjectPropertyInstance> properties = new PropertyDictionary<ProjectPropertyInstance>(); properties.Set(ProjectPropertyInstance.Create("this", "that")); properties.Set(ProjectPropertyInstance.Create("foo", "bar")); BuildRequestData data = new BuildRequestData("file", properties.ToDictionary(), "4.0", new string[0], null); BuildRequestConfiguration config = new BuildRequestConfiguration(data, "2.0"); Assert.Equal(NodePacketType.BuildRequestConfiguration, config.Type); ((ITranslatable)config).Translate(TranslationHelpers.GetWriteTranslator()); INodePacket packet = BuildRequestConfiguration.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); BuildRequestConfiguration deserializedConfig = packet as BuildRequestConfiguration; Assert.Equal(config, deserializedConfig); } [Fact] public void TestProperties() { BuildRequestConfiguration configuration = new BuildRequestConfiguration(new BuildRequestData("path", new Dictionary<string, string>(), "2.0", new string[] { }, null), "2.0"); Assert.True(configuration.IsCacheable); Assert.False(configuration.IsLoaded); Assert.False(configuration.IsCached); Assert.False(configuration.IsActivelyBuilding); } [Fact] public void TestCache() { string projectBody = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <PropertyGroup> <One>1</One> <Two>2</Two> <Three>$(ThreeIn)</Three> </PropertyGroup> <ItemGroup> <Foo Include=""*""/> <Bar Include=""msbuild.out""> <One>1</One> </Bar> <Baz Include=""$(BazIn)""/> </ItemGroup> <Target Name='Build'> <CallTarget Targets='Foo;Goo'/> </Target> <Target Name='Foo' DependsOnTargets='Foo2'> <FooTarget/> </Target> <Target Name='Goo'> <GooTarget/> </Target> <Target Name='Foo2'> <Foo2Target/> </Target> </Project>"); Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties["ThreeIn"] = "3"; globalProperties["BazIn"] = "bazfile"; Project project = new Project( XmlReader.Create(new StringReader(projectBody)), globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion, new ProjectCollection()); project.FullPath = "foo"; ProjectInstance instance = project.CreateProjectInstance(); BuildRequestConfiguration configuration = new BuildRequestConfiguration(new BuildRequestData(instance, new string[] { }, null), "2.0"); configuration.ConfigurationId = 1; string originalValue = Environment.GetEnvironmentVariable("MSBUILDCACHE"); try { Environment.SetEnvironmentVariable("MSBUILDCACHE", "1"); Assert.Equal("3", instance.GlobalProperties["ThreeIn"]); Assert.Equal("bazfile", instance.GlobalProperties["BazIn"]); Assert.Equal("1", instance.PropertiesToBuildWith["One"].EvaluatedValue); Assert.Equal("2", instance.PropertiesToBuildWith["Two"].EvaluatedValue); Assert.Equal("3", instance.PropertiesToBuildWith["Three"].EvaluatedValue); int fooCount = instance.ItemsToBuildWith["Foo"].Count; Assert.True(fooCount > 0); Assert.Single(instance.ItemsToBuildWith["Bar"]); Assert.Single(instance.ItemsToBuildWith["Baz"]); Assert.Equal("bazfile", instance.ItemsToBuildWith["Baz"].First().EvaluatedInclude); Lookup lookup = configuration.BaseLookup; Assert.NotNull(lookup); Assert.Equal(fooCount, lookup.GetItems("Foo").Count); // Configuration initialized with a ProjectInstance should not be cacheable by default. Assert.False(configuration.IsCacheable); configuration.IsCacheable = true; configuration.CacheIfPossible(); Assert.Null(instance.GlobalPropertiesDictionary); Assert.Null(instance.ItemsToBuildWith); Assert.Null(instance.PropertiesToBuildWith); configuration.RetrieveFromCache(); Assert.Equal("3", instance.GlobalProperties["ThreeIn"]); Assert.Equal("bazfile", instance.GlobalProperties["BazIn"]); Assert.Equal("1", instance.PropertiesToBuildWith["One"].EvaluatedValue); Assert.Equal("2", instance.PropertiesToBuildWith["Two"].EvaluatedValue); Assert.Equal("3", instance.PropertiesToBuildWith["Three"].EvaluatedValue); Assert.Equal(fooCount, instance.ItemsToBuildWith["Foo"].Count); Assert.Single(instance.ItemsToBuildWith["Bar"]); Assert.Single(instance.ItemsToBuildWith["Baz"]); Assert.Equal("bazfile", instance.ItemsToBuildWith["Baz"].First().EvaluatedInclude); lookup = configuration.BaseLookup; Assert.NotNull(lookup); Assert.Equal(fooCount, lookup.GetItems("Foo").Count); } finally { configuration.ClearCacheFile(); Environment.SetEnvironmentVariable("MSBUILDCACHE", originalValue); } } [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void TestCache2() { string projectBody = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <PropertyGroup> <One>1</One> <Two>2</Two> <Three>$(ThreeIn)</Three> </PropertyGroup> <ItemGroup> <Foo Include=""*""/> <Bar Include=""msbuild.out""> <One>1</One> </Bar> <Baz Include=""$(BazIn)""/> </ItemGroup> <Target Name='Build'> <CallTarget Targets='Foo;Bar'/> </Target> <Target Name='Foo' DependsOnTargets='Foo'> <FooTarget/> </Target> <Target Name='Bar'> <BarTarget/> </Target> <Target Name='Foo'> <FooTarget/> </Target> </Project>"); Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties["ThreeIn"] = "3"; globalProperties["BazIn"] = "bazfile"; Project project = new Project(XmlReader.Create(new StringReader(projectBody)), globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion, new ProjectCollection()); project.FullPath = "foo"; ProjectInstance instance = project.CreateProjectInstance(); BuildRequestConfiguration configuration = new BuildRequestConfiguration(new BuildRequestData(instance, new string[] { }, null), "2.0"); string originalTmp = Environment.GetEnvironmentVariable("TMP"); string originalTemp = Environment.GetEnvironmentVariable("TEMP"); try { string problematicTmpPath = @"C:\Users\}\blabla\temp"; Environment.SetEnvironmentVariable("TMP", problematicTmpPath); Environment.SetEnvironmentVariable("TEMP", problematicTmpPath); FileUtilities.ClearCacheDirectoryPath(); string cacheFilePath = configuration.GetCacheFile(); Assert.StartsWith(problematicTmpPath, cacheFilePath); } finally { Environment.SetEnvironmentVariable("TMP", originalTmp); Environment.SetEnvironmentVariable("TEMP", originalTemp); FileUtilities.ClearCacheDirectoryPath(); } } } }
/******************************************************************** * * PropertyBag.cs * -------------- * Derived from PropertyBag.cs by Tony Allowatt * CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp * Last Update: 04/05/2005 * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using System.Reflection; using CslaGenerator.Attributes; using CslaGenerator.Metadata; namespace CslaGenerator.Util.PropertyBags { /// <summary> /// Represents a collection of custom properties that can be selected into a /// PropertyGrid to provide functionality beyond that of the simple reflection /// normally used to query an object's properties. /// </summary> public class UpdateValuePropertyBag : ICustomTypeDescriptor { #region PropertySpecCollection class definition /// <summary> /// Encapsulates a collection of PropertySpec objects. /// </summary> [Serializable] public class PropertySpecCollection : IList { private readonly ArrayList _innerArray; /// <summary> /// Initializes a new instance of the PropertySpecCollection class. /// </summary> public PropertySpecCollection() { _innerArray = new ArrayList(); } /// <summary> /// Gets or sets the element at the specified index. /// In C#, this property is the indexer for the PropertySpecCollection class. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <value> /// The element at the specified index. /// </value> public PropertySpec this[int index] { get { return (PropertySpec) _innerArray[index]; } set { _innerArray[index] = value; } } #region IList Members /// <summary> /// Gets the number of elements in the PropertySpecCollection. /// </summary> /// <value> /// The number of elements contained in the PropertySpecCollection. /// </value> public int Count { get { return _innerArray.Count; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection has a fixed size. /// </summary> /// <value> /// true if the PropertySpecCollection has a fixed size; otherwise, false. /// </value> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value> /// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> object ICollection.SyncRoot { get { return null; } } /// <summary> /// Removes all elements from the PropertySpecCollection. /// </summary> public void Clear() { _innerArray.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the PropertySpecCollection. /// </summary> /// <returns>An IEnumerator for the entire PropertySpecCollection.</returns> public IEnumerator GetEnumerator() { return _innerArray.GetEnumerator(); } /// <summary> /// Removes the object at the specified index of the PropertySpecCollection. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> public void RemoveAt(int index) { _innerArray.RemoveAt(index); } #endregion /// <summary> /// Adds a PropertySpec to the end of the PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param> /// <returns>The PropertySpecCollection index at which the value has been added.</returns> public int Add(PropertySpec value) { int index = _innerArray.Add(value); return index; } /// <summary> /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection. /// </summary> /// <param name="array">The PropertySpec array whose elements should be added to the end of the /// PropertySpecCollection.</param> public void AddRange(PropertySpec[] array) { _innerArray.AddRange(array); } /// <summary> /// Determines whether a PropertySpec is in the PropertySpecCollection. /// </summary> /// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate /// can be a null reference (Nothing in Visual Basic).</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(PropertySpec item) { return _innerArray.Contains(item); } /// <summary> /// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(string name) { foreach (PropertySpec spec in _innerArray) if (spec.Name == name) return true; return false; } /// <summary> /// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the /// beginning of the target array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from PropertySpecCollection. The Array must have zero-based indexing.</param> public void CopyTo(PropertySpec[] array) { _innerArray.CopyTo(array); } /// <summary> /// Copies the PropertySpecCollection or a portion of it to a one-dimensional array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from the collection.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(PropertySpec[] array, int index) { _innerArray.CopyTo(array, index); } /// <summary> /// Searches for the specified PropertySpec and returns the zero-based index of the first /// occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(PropertySpec value) { return _innerArray.IndexOf(value); } /// <summary> /// Searches for the PropertySpec with the specified name and returns the zero-based index of /// the first occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(string name) { int i = 0; foreach (PropertySpec spec in _innerArray) { //if (spec.Name == name) if (spec.TargetProperty == name) return i; i++; } return -1; } /// <summary> /// Inserts a PropertySpec object into the PropertySpecCollection at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value">The PropertySpec to insert.</param> public void Insert(int index, PropertySpec value) { _innerArray.Insert(index, value); } /// <summary> /// Removes the first occurrence of a specific object from the PropertySpecCollection. /// </summary> /// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(PropertySpec obj) { _innerArray.Remove(obj); } /// <summary> /// Removes the property with the specified name from the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(string name) { int index = IndexOf(name); RemoveAt(index); } /// <summary> /// Copies the elements of the PropertySpecCollection to a new PropertySpec array. /// </summary> /// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns> public PropertySpec[] ToArray() { return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec)); } #region Explicit interface implementations for ICollection and IList /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void ICollection.CopyTo(Array array, int index) { CopyTo((PropertySpec[]) array, index); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.Add(object value) { return Add((PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> bool IList.Contains(object obj) { return Contains((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (PropertySpec) value; } } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.IndexOf(object obj) { return IndexOf((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Insert(int index, object value) { Insert(index, (PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Remove(object value) { Remove((PropertySpec) value); } #endregion } #endregion #region PropertySpecDescriptor class definition private class PropertySpecDescriptor : PropertyDescriptor { private readonly UpdateValuePropertyBag _bag; private readonly PropertySpec _item; public PropertySpecDescriptor(PropertySpec item, UpdateValuePropertyBag bag, string name, Attribute[] attrs) : base(name, attrs) { _bag = bag; _item = item; } public override Type ComponentType { get { return _item.GetType(); } } public override bool IsReadOnly { get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); } } public override Type PropertyType { get { return Type.GetType(_item.TypeName); } } public override bool CanResetValue(object component) { if (_item.DefaultValue == null) return false; return !GetValue(component).Equals(_item.DefaultValue); } public override object GetValue(object component) { // Have the property bag raise an event to get the current value // of the property. var e = new PropertySpecEventArgs(_item, null); _bag.OnGetValue(e); return e.Value; } public override void ResetValue(object component) { SetValue(component, _item.DefaultValue); } public override void SetValue(object component, object value) { // Have the property bag raise an event to set the current value // of the property. var e = new PropertySpecEventArgs(_item, value); _bag.OnSetValue(e); } public override bool ShouldSerializeValue(object component) { object val = GetValue(component); if (_item.DefaultValue == null && val == null) return false; return !val.Equals(_item.DefaultValue); } } #endregion #region Properties and Events private readonly PropertySpecCollection _properties; private string _defaultProperty; private UpdateValueProperty[] _selectedObject; /// <summary> /// Initializes a new instance of the UpdateValuePropertyBag class. /// </summary> public UpdateValuePropertyBag() { _defaultProperty = null; _properties = new PropertySpecCollection(); } public UpdateValuePropertyBag(UpdateValueProperty obj) : this(new[] {obj}) { } public UpdateValuePropertyBag(UpdateValueProperty[] obj) { _defaultProperty = "Name"; _properties = new PropertySpecCollection(); _selectedObject = obj; InitPropertyBag(); } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public string DefaultProperty { get { return _defaultProperty; } set { _defaultProperty = value; } } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public UpdateValueProperty[] SelectedObject { get { return _selectedObject; } set { _selectedObject = value; InitPropertyBag(); } } /// <summary> /// Gets the collection of properties contained within this UpdateValuePropertyBag. /// </summary> public PropertySpecCollection Properties { get { return _properties; } } /// <summary> /// Occurs when a PropertyGrid requests the value of a property. /// </summary> public event PropertySpecEventHandler GetValue; /// <summary> /// Occurs when the user changes the value of a property in a PropertyGrid. /// </summary> public event PropertySpecEventHandler SetValue; /// <summary> /// Raises the GetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnGetValue(PropertySpecEventArgs e) { if (e.Value != null) GetValue(this, e); e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue); } /// <summary> /// Raises the SetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnSetValue(PropertySpecEventArgs e) { if (SetValue != null) SetValue(this, e); SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value); } #endregion #region Initialize Propertybag private void InitPropertyBag() { PropertyInfo pi; Type t = typeof (UpdateValueProperty); // _selectedObject.GetType(); PropertyInfo[] props = t.GetProperties(); // Display information for all properties. for (int i = 0; i < props.Length; i++) { pi = props[i]; object[] myAttributes = pi.GetCustomAttributes(true); string category = ""; string description = ""; bool isreadonly = false; bool isbrowsable = true; object defaultvalue = null; string userfriendlyname = ""; string typeconverter = ""; string designertypename = ""; string helptopic = ""; bool bindable = true; string editor = ""; for (int n = 0; n < myAttributes.Length; n++) { var a = (Attribute) myAttributes[n]; switch (a.GetType().ToString()) { case "System.ComponentModel.CategoryAttribute": category = ((CategoryAttribute) a).Category; break; case "System.ComponentModel.DescriptionAttribute": description = ((DescriptionAttribute) a).Description; break; case "System.ComponentModel.ReadOnlyAttribute": isreadonly = ((ReadOnlyAttribute) a).IsReadOnly; break; case "System.ComponentModel.BrowsableAttribute": isbrowsable = ((BrowsableAttribute) a).Browsable; break; case "System.ComponentModel.DefaultValueAttribute": defaultvalue = ((DefaultValueAttribute) a).Value; break; case "CslaGenerator.Attributes.UserFriendlyNameAttribute": userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName; break; case "CslaGenerator.Attributes.HelpTopicAttribute": helptopic = ((HelpTopicAttribute) a).HelpTopic; break; case "System.ComponentModel.TypeConverterAttribute": typeconverter = ((TypeConverterAttribute) a).ConverterTypeName; break; case "System.ComponentModel.DesignerAttribute": designertypename = ((DesignerAttribute) a).DesignerTypeName; break; case "System.ComponentModel.BindableAttribute": bindable = ((BindableAttribute) a).Bindable; break; case "System.ComponentModel.EditorAttribute": editor = ((EditorAttribute) a).EditorTypeName; break; } } userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name; var types = new List<string>(); foreach (var obj in _selectedObject) { if (!types.Contains(obj.Name)) types.Add(obj.Name); } // here get rid of ComponentName and Parent bool isValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent"); if (isValidProperty && IsBrowsable(types.ToArray(), pi.Name)) { // CR added missing parameters //this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, pi.Name,helptopic)); Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, pi.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable)); } } } #endregion private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>(); private PropertyInfo GetPropertyInfoCache(string propertyName) { if (!propertyInfoCache.ContainsKey(propertyName)) { propertyInfoCache.Add(propertyName, typeof (UpdateValueProperty).GetProperty(propertyName)); } return propertyInfoCache[propertyName]; } private bool IsEnumerable(PropertyInfo prop) { if (prop.PropertyType == typeof (string)) return false; Type[] interfaces = prop.PropertyType.GetInterfaces(); foreach (Type typ in interfaces) if (typ.Name.Contains("IEnumerable")) return true; return false; } #region IsBrowsable map objectType:propertyName -> true | false private bool IsBrowsable(string[] objectType, string propertyName) { try { /*if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None || GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel) && (propertyName == "ReadRoles" || propertyName == "WriteRoles")) return false;*/ if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName))) return false; return true; } catch //(Exception e) { Debug.WriteLine(objectType + ":" + propertyName); return true; } } #endregion #region Reflection functions private object GetField(Type t, string name, object target) { object obj = null; Type tx; FieldInfo[] fields; //fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); fields = target.GetType().GetFields(BindingFlags.Public); tx = target.GetType(); obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {}); return obj; } private object SetField(Type t, string name, object value, object target) { object obj; obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value}); return obj; } private bool SetProperty(object obj, string propertyName, object val) { try { // get a reference to the PropertyInfo, exit if no property with that // name PropertyInfo pi = typeof (UpdateValueProperty).GetProperty(propertyName); if (pi == null) return false; // convert the value to the expected type val = Convert.ChangeType(val, pi.PropertyType); // attempt the assignment foreach (UpdateValueProperty bo in (UpdateValueProperty[]) obj) pi.SetValue(bo, val, null); return true; } catch { return false; } } private object GetProperty(object obj, string propertyName, object defaultValue) { try { PropertyInfo pi = GetPropertyInfoCache(propertyName); if (!(pi == null)) { var objs = (UpdateValueProperty[]) obj; var valueList = new ArrayList(); foreach (UpdateValueProperty bo in objs) { object value = pi.GetValue(bo, null); if (!valueList.Contains(value)) { valueList.Add(value); } } switch (valueList.Count) { case 1: return valueList[0]; default: return string.Empty; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } // if property doesn't exist or throws return defaultValue; } #endregion #region ICustomTypeDescriptor explicit interface definitions // Most of the functions required by the ICustomTypeDescriptor are // merely pssed on to the default TypeDescriptor for this type, // which will do something appropriate. The exceptions are noted // below. AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { // This function searches the property list for the property // with the same name as the DefaultProperty specified, and // returns a property descriptor for it. If no property is // found that matches DefaultProperty, a null reference is // returned instead. PropertySpec propertySpec = null; if (_defaultProperty != null) { int index = _properties.IndexOf(_defaultProperty); propertySpec = _properties[index]; } if (propertySpec != null) return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null); return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // Rather than passing this function on to the default TypeDescriptor, // which would return the actual properties of UpdateValuePropertyBag, I construct // a list here that contains property descriptors for the elements of the // Properties list in the bag. var props = new ArrayList(); foreach (PropertySpec property in _properties) { var attrs = new ArrayList(); // If a category, description, editor, or type converter are specified // in the PropertySpec, create attributes to define that relationship. if (property.Category != null) attrs.Add(new CategoryAttribute(property.Category)); if (property.Description != null) attrs.Add(new DescriptionAttribute(property.Description)); if (property.EditorTypeName != null) attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor))); if (property.ConverterTypeName != null) attrs.Add(new TypeConverterAttribute(property.ConverterTypeName)); // Additionally, append the custom attributes associated with the // PropertySpec, if any. if (property.Attributes != null) attrs.AddRange(property.Attributes); if (property.DefaultValue != null) attrs.Add(new DefaultValueAttribute(property.DefaultValue)); attrs.Add(new BrowsableAttribute(property.Browsable)); attrs.Add(new ReadOnlyAttribute(property.ReadOnly)); attrs.Add(new BindableAttribute(property.Bindable)); var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute)); // Create a new property descriptor for the property item, and add // it to the list. var pd = new PropertySpecDescriptor(property, this, property.Name, attrArray); props.Add(pd); } // Convert the list of PropertyDescriptors to a collection that the // ICustomTypeDescriptor can use, and return it. var propArray = (PropertyDescriptor[]) props.ToArray( typeof (PropertyDescriptor)); return new PropertyDescriptorCollection(propArray); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion } }
#region License //L // 2007 - 2013 Copyright Northwestern University // // Distributed under the OSI-approved BSD 3-Clause License. // See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details. //L #endregion using System.Collections; using System.Collections.Generic; using System.Diagnostics; using ClearCanvas.Dicom.DataStore; namespace AIM.Annotation { internal class AimSopInstanceInformation { private readonly string _studyInstanceUID; private readonly string _seriesInstanceUID; private readonly string _sopInstanceUID; private readonly string _instanceFileName; public AimSopInstanceInformation(string studyInstanceUID, string seriesInstanceUID, string sopInstanceUID, string instanceFileName) { _studyInstanceUID = studyInstanceUID; _seriesInstanceUID = seriesInstanceUID; _sopInstanceUID = sopInstanceUID; _instanceFileName = instanceFileName; } public string StudyInstanceUID { get { return _studyInstanceUID; } } public string SeriesInstanceUID { get { return _seriesInstanceUID; } } public string SOPInstanceUID { get { return _sopInstanceUID; } } public string InstanceFileName { get { return _instanceFileName; } } } /// <summary> /// Contains mapping information for available Annotation instances /// </summary> internal class AimInstanceDictionary : IEnumerable<ISopInstance> { // Dictionary: // Study Instance UID -> Series Instance UID -> SOP Istance UID -> SOP Instance File Path Name private readonly Dictionary<string, Dictionary<string, Dictionary<string, string>>> _studyDictionary; public AimInstanceDictionary() { _studyDictionary = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>(); } public void Add(string studyInstanceUID, string seriesInstanceUID, string sopInstanceUID, string instanceFileName) { if (studyInstanceUID == null || seriesInstanceUID == null || sopInstanceUID == null || instanceFileName == null) return; if (ContainsStudy(studyInstanceUID)) { if (_studyDictionary[studyInstanceUID].ContainsKey(seriesInstanceUID)) { if (_studyDictionary[studyInstanceUID][seriesInstanceUID].ContainsKey(sopInstanceUID)) { Debug.Assert(false, "Given annotation instance has been previously recorded: " + sopInstanceUID); return; } } else _studyDictionary[studyInstanceUID].Add(seriesInstanceUID, new Dictionary<string, string>()); } else { _studyDictionary.Add(studyInstanceUID, new Dictionary<string, Dictionary<string, string>>()); _studyDictionary[studyInstanceUID].Add(seriesInstanceUID, new Dictionary<string, string>()); } _studyDictionary[studyInstanceUID][seriesInstanceUID].Add(sopInstanceUID, instanceFileName); } public void Remove(string studyInstanceUID, string seriesInstanceUID, string sopInstanceUID) { if (studyInstanceUID == null || seriesInstanceUID == null || sopInstanceUID == null) return; if (ContainsInstance(studyInstanceUID, seriesInstanceUID, sopInstanceUID)) { _studyDictionary[studyInstanceUID][seriesInstanceUID].Remove(sopInstanceUID); if (_studyDictionary[studyInstanceUID][seriesInstanceUID].Count == 0) _studyDictionary[studyInstanceUID].Remove(seriesInstanceUID); if (_studyDictionary[studyInstanceUID].Count == 0) _studyDictionary.Remove(studyInstanceUID); } } public void Clear() { foreach (var studyInfo in _studyDictionary.Values) { foreach (var seriesInfo in studyInfo.Values) { seriesInfo.Clear(); } studyInfo.Clear(); } _studyDictionary.Clear(); } public bool ContainsStudy(string studyInstanceUID) { if (studyInstanceUID == null) return false; return _studyDictionary.ContainsKey(studyInstanceUID); } public bool ContainsSeries(string studyInstanceUID, string seriesInstanceUID) { if (seriesInstanceUID == null) return false; return ContainsStudy(studyInstanceUID) && _studyDictionary[studyInstanceUID].ContainsKey(seriesInstanceUID); } public bool ContainsInstance(string studyInstanceUID, string seriesInstanceUID, string sopInstanceUID) { if (sopInstanceUID == null) return false; return ContainsSeries(studyInstanceUID, seriesInstanceUID) && _studyDictionary[studyInstanceUID][seriesInstanceUID].ContainsKey(sopInstanceUID); } public int Count() { var count = 0; foreach(var studyInstanceInfo in _studyDictionary.Values) { Debug.Assert(studyInstanceInfo != null); foreach (var seriesInfo in studyInstanceInfo.Values) { Debug.Assert(seriesInfo != null); count += seriesInfo.Count; } } return count; } public string SopInstanceFileName(string studyInstanceUID, string seriesInstanceUID, string sopInstanceUID) { return ContainsInstance(studyInstanceUID, seriesInstanceUID, sopInstanceUID) ? _studyDictionary[studyInstanceUID][seriesInstanceUID][sopInstanceUID] : null; } IEnumerator<ISopInstance> IEnumerable<ISopInstance>.GetEnumerator() { using (var reader = DataAccessLayer.GetIDataStoreReader()) { foreach(var studyUID in _studyDictionary.Keys) { var studyInfo = _studyDictionary[studyUID]; Debug.Assert(studyInfo != null); foreach (var seriesInstanceUID in studyInfo.Keys) { var seriesInfo = studyInfo[seriesInstanceUID]; Debug.Assert(seriesInfo != null); foreach (var sopInstanceUID in seriesInfo.Keys) { foreach (var sopInstance in reader.GetStudy(studyUID).GetSopInstances()) { if (sopInstance.SopInstanceUid != sopInstanceUID) continue; yield return sopInstance; break; } } } } } } public IEnumerator GetEnumerator() { return ((IEnumerable<ISopInstance>) this).GetEnumerator(); } public List<AimSopInstanceInformation> this[string studyInstanceUID] { get { List<AimSopInstanceInformation> sopInstanceList = null; if (ContainsStudy(studyInstanceUID)) { sopInstanceList = new List<AimSopInstanceInformation>(); foreach (var seriesInstanceUID in _studyDictionary[studyInstanceUID].Keys) { foreach (var sopInstanceUID in _studyDictionary[studyInstanceUID][seriesInstanceUID].Keys) sopInstanceList.Add( new AimSopInstanceInformation(studyInstanceUID, seriesInstanceUID, sopInstanceUID, _studyDictionary[studyInstanceUID][seriesInstanceUID][sopInstanceUID])); } } return sopInstanceList; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SignInt16() { var test = new SimpleBinaryOpTest__SignInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SignInt16 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int16); private const int Op2ElementCount = VectorSize / sizeof(Int16); private const int RetElementCount = VectorSize / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable; static SimpleBinaryOpTest__SignInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue + 1, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SignInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue + 1, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue + 1, short.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], VectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Ssse3.Sign( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Ssse3.Sign( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Ssse3.Sign( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Ssse3.Sign( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Ssse3.Sign(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Ssse3.Sign(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Ssse3.Sign(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SignInt16(); var result = Ssse3.Sign(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Ssse3.Sign(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { if (result[0] != (right[0] < 0 ? (short)(-left[0]) : (right[0] > 0 ? left[0] : 0))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (right[i] < 0 ? (short)(-left[i]) : (right[i] > 0 ? left[i] : 0))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Ssse3)}.{nameof(Ssse3.Sign)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// // Copyright 2011-2013, Xamarin 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 System.Text; using Android.Content; using Android.Content.Res; using Android.Database; using Android.Provider; using StructuredName = Android.Provider.ContactsContract.CommonDataKinds.StructuredName; using StructuredPostal = Android.Provider.ContactsContract.CommonDataKinds.StructuredPostal; using CommonColumns = Android.Provider.ContactsContract.CommonDataKinds.CommonColumns; using Uri = Android.Net.Uri; using InstantMessaging = Android.Provider.ContactsContract.CommonDataKinds.Im; using OrganizationData = Android.Provider.ContactsContract.CommonDataKinds.Organization; using WebsiteData = Android.Provider.ContactsContract.CommonDataKinds.Website; using Relation = Android.Provider.ContactsContract.CommonDataKinds.Relation; using Plugin.Contacts.Abstractions; using System.Threading.Tasks; namespace Plugin.Contacts { internal static class ContactHelper { internal static IEnumerable<Contact> GetContacts(bool rawContacts, ContentResolver content, Resources resources) { Uri curi = (rawContacts) ? ContactsContract.RawContacts.ContentUri : ContactsContract.Contacts.ContentUri; ICursor cursor = null; try { cursor = content.Query(curi, null, null, null, null); if (cursor == null) yield break; foreach (Contact contact in GetContacts(cursor, rawContacts, content, resources, 256)) yield return contact; } finally { if (cursor != null) cursor.Close(); } } internal static IEnumerable<Contact> GetContacts(ICursor cursor, bool rawContacts, ContentResolver content, Resources resources, int batchSize) { if (cursor == null) yield break; string column = (rawContacts) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; string[] ids = new string[batchSize]; int columnIndex = cursor.GetColumnIndex(column); HashSet<string> uniques = new HashSet<string>(); int i = 0; while (cursor.MoveToNext()) { if (i == batchSize) { i = 0; foreach (Contact c in GetContacts(rawContacts, content, resources, ids)) yield return c; } string id = cursor.GetString(columnIndex); if (id == null || uniques.Contains(id)) continue; uniques.Add(id); ids[i++] = id; } if (i > 0) { foreach (Contact c in GetContacts(rawContacts, content, resources, ids.Take(i).ToArray())) yield return c; } } internal static IEnumerable<Contact> GetContacts(bool rawContacts, ContentResolver content, Resources resources, string[] ids) { ICursor c = null; string column = (rawContacts) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; StringBuilder whereb = new StringBuilder(); for (int i = 0; i < ids.Length; i++) { if (i > 0) whereb.Append(" OR "); whereb.Append(column); whereb.Append("=?"); } int x = 0; var map = new Dictionary<string, Contact>(ids.Length); try { Contact currentContact = null; c = content.Query(ContactsContract.Data.ContentUri, null, whereb.ToString(), ids, ContactsContract.ContactsColumns.LookupKey); if (c == null) yield break; int idIndex = c.GetColumnIndex(column); int dnIndex = c.GetColumnIndex(ContactsContract.ContactsColumns.DisplayName); while (c.MoveToNext()) { string id = c.GetString(idIndex); if (currentContact == null || currentContact.Id != id) { // We need to yield these in the original ID order if (currentContact != null) { if (currentContact.Id == ids[x]) { yield return currentContact; x++; } else map.Add(currentContact.Id, currentContact); } currentContact = new Contact(id, !rawContacts) { Tag = content }; currentContact.DisplayName = c.GetString(dnIndex); } FillContactWithRow(resources, currentContact, c); } if (currentContact != null) map.Add(currentContact.Id, currentContact); for (; x < ids.Length; x++) { Contact tContact = null; if(map.TryGetValue(ids[x], out tContact)) yield return tContact; } } finally { if (c != null) c.Close(); } } internal static Contact GetContact(bool rawContact, ContentResolver content, Resources resources, ICursor cursor) { string id = (rawContact) ? cursor.GetString(cursor.GetColumnIndex(ContactsContract.RawContactsColumns.ContactId)) : cursor.GetString(cursor.GetColumnIndex(ContactsContract.ContactsColumns.LookupKey)); var contact = new Contact(id, !rawContact) { Tag = content }; contact.DisplayName = GetString(cursor, ContactsContract.ContactsColumns.DisplayName); FillContactExtras(rawContact, content, resources, id, contact); return contact; } internal static void FillContactExtras(bool rawContact, ContentResolver content, Resources resources, string recordId, Contact contact) { ICursor c = null; string column = (rawContact) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; try { if (string.IsNullOrWhiteSpace(recordId)) return; c = content.Query(ContactsContract.Data.ContentUri, null, column + " = ?", new[] { recordId }, null); if (c == null) return; while (c.MoveToNext()) FillContactWithRow(resources, contact, c); } finally { if (c != null) c.Close(); } } private static void FillContactWithRow(Resources resources, Contact contact, ICursor c) { string dataType = c.GetString(c.GetColumnIndex(ContactsContract.DataColumns.Mimetype)); switch (dataType) { case ContactsContract.CommonDataKinds.Nickname.ContentItemType: contact.Nickname = c.GetString(c.GetColumnIndex(ContactsContract.CommonDataKinds.Nickname.Name)); break; case StructuredName.ContentItemType: contact.Prefix = c.GetString(StructuredName.Prefix); contact.FirstName = c.GetString(StructuredName.GivenName); contact.MiddleName = c.GetString(StructuredName.MiddleName); contact.LastName = c.GetString(StructuredName.FamilyName); contact.Suffix = c.GetString(StructuredName.Suffix); break; case ContactsContract.CommonDataKinds.Phone.ContentItemType: contact.Phones.Add(GetPhone(c, resources)); break; case ContactsContract.CommonDataKinds.Email.ContentItemType: contact.Emails.Add(GetEmail(c, resources)); break; case ContactsContract.CommonDataKinds.Note.ContentItemType: contact.Notes.Add(GetNote(c, resources)); break; case ContactsContract.CommonDataKinds.Organization.ContentItemType: contact.Organizations.Add(GetOrganization(c, resources)); break; case StructuredPostal.ContentItemType: contact.Addresses.Add(GetAddress(c, resources)); break; case InstantMessaging.ContentItemType: contact.InstantMessagingAccounts.Add(GetImAccount(c, resources)); break; case WebsiteData.ContentItemType: contact.Websites.Add(GetWebsite(c, resources)); break; case Relation.ContentItemType: contact.Relationships.Add(GetRelationship(c, resources)); break; } } internal static Note GetNote(ICursor c, Resources resources) { return new Note { Contents = GetString(c, ContactsContract.DataColumns.Data1) }; } internal static Relationship GetRelationship(ICursor c, Resources resources) { Relationship r = new Relationship { Name = c.GetString(Relation.Name) }; RelationDataKind rtype = (RelationDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); switch (rtype) { case RelationDataKind.DomesticPartner: case RelationDataKind.Spouse: case RelationDataKind.Friend: r.Type = RelationshipType.SignificantOther; break; case RelationDataKind.Child: r.Type = RelationshipType.Child; break; default: r.Type = RelationshipType.Other; break; } return r; } internal static InstantMessagingAccount GetImAccount(ICursor c, Resources resources) { InstantMessagingAccount ima = new InstantMessagingAccount(); ima.Account = c.GetString(CommonColumns.Data); //IMTypeDataKind imKind = (IMTypeDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type)); //ima.Type = imKind.ToInstantMessagingType(); //ima.Label = InstantMessaging.GetTypeLabel (resources, imKind, c.GetString (CommonColumns.Label)); IMProtocolDataKind serviceKind = (IMProtocolDataKind)c.GetInt(c.GetColumnIndex(InstantMessaging.Protocol)); ima.Service = serviceKind.ToInstantMessagingService(); ima.ServiceLabel = (serviceKind != IMProtocolDataKind.Custom) ? InstantMessaging.GetProtocolLabel(resources, serviceKind, String.Empty) : c.GetString(InstantMessaging.CustomProtocol); return ima; } internal static Address GetAddress(ICursor c, Resources resources) { Address a = new Address(); a.Country = c.GetString(StructuredPostal.Country); a.Region = c.GetString(StructuredPostal.Region); a.City = c.GetString(StructuredPostal.City); a.PostalCode = c.GetString(StructuredPostal.Postcode); AddressDataKind kind = (AddressDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); a.Type = kind.ToAddressType(); a.Label = (kind != AddressDataKind.Custom) ? StructuredPostal.GetTypeLabel(resources, kind, String.Empty) : c.GetString(CommonColumns.Label); string street = c.GetString(StructuredPostal.Street); string pobox = c.GetString(StructuredPostal.Pobox); if (street != null) a.StreetAddress = street; if (pobox != null) { if (street != null) a.StreetAddress += Environment.NewLine; a.StreetAddress += pobox; } return a; } internal static Phone GetPhone(ICursor c, Resources resources) { Phone p = new Phone(); p.Number = GetString(c, ContactsContract.CommonDataKinds.Phone.Number); PhoneDataKind pkind = (PhoneDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); p.Type = pkind.ToPhoneType(); p.Label = (pkind != PhoneDataKind.Custom) ? ContactsContract.CommonDataKinds.Phone.GetTypeLabel(resources, pkind, String.Empty) : c.GetString(CommonColumns.Label); return p; } internal static Email GetEmail(ICursor c, Resources resources) { Email e = new Email(); e.Address = c.GetString(ContactsContract.DataColumns.Data1); EmailDataKind ekind = (EmailDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); e.Type = ekind.ToEmailType(); e.Label = (ekind != EmailDataKind.Custom) ? ContactsContract.CommonDataKinds.Email.GetTypeLabel(resources, ekind, String.Empty) : c.GetString(CommonColumns.Label); return e; } internal static Organization GetOrganization(ICursor c, Resources resources) { Organization o = new Organization(); o.Name = c.GetString(OrganizationData.Company); o.ContactTitle = c.GetString(OrganizationData.Title); OrganizationDataKind d = (OrganizationDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); o.Type = d.ToOrganizationType(); o.Label = (d != OrganizationDataKind.Custom) ? OrganizationData.GetTypeLabel(resources, d, String.Empty) : c.GetString(CommonColumns.Label); return o; } internal static Website GetWebsite(ICursor c, Resources resources) { Website w = new Website(); w.Address = c.GetString(WebsiteData.Url); //WebsiteDataKind kind = (WebsiteDataKind)c.GetInt (c.GetColumnIndex (CommonColumns.Type)); //w.Type = kind.ToWebsiteType(); //w.Label = (kind != WebsiteDataKind.Custom) // ? resources.GetString ((int) kind) // : c.GetString (CommonColumns.Label); return w; } //internal static WebsiteType ToWebsiteType (this WebsiteDataKind websiteKind) //{ // switch (websiteKind) // { // case WebsiteDataKind.Work: // return WebsiteType.Work; // case WebsiteDataKind.Home: // return WebsiteType.Home; // default: // return WebsiteType.Other; // } //} internal static string GetString(this ICursor c, string colName) { return c.GetString(c.GetColumnIndex(colName)); } internal static AddressType ToAddressType(this AddressDataKind addressKind) { switch (addressKind) { case AddressDataKind.Home: return AddressType.Home; case AddressDataKind.Work: return AddressType.Work; default: return AddressType.Other; } } internal static EmailType ToEmailType(this EmailDataKind emailKind) { switch (emailKind) { case EmailDataKind.Home: return EmailType.Home; case EmailDataKind.Work: return EmailType.Work; default: return EmailType.Other; } } internal static PhoneType ToPhoneType(this PhoneDataKind phoneKind) { switch (phoneKind) { case PhoneDataKind.Home: return PhoneType.Home; case PhoneDataKind.Mobile: return PhoneType.Mobile; case PhoneDataKind.FaxHome: return PhoneType.HomeFax; case PhoneDataKind.Work: return PhoneType.Work; case PhoneDataKind.FaxWork: return PhoneType.WorkFax; case PhoneDataKind.Pager: case PhoneDataKind.WorkPager: return PhoneType.Pager; default: return PhoneType.Other; } } internal static OrganizationType ToOrganizationType(this OrganizationDataKind organizationKind) { switch (organizationKind) { case OrganizationDataKind.Work: return OrganizationType.Work; default: return OrganizationType.Other; } } internal static InstantMessagingService ToInstantMessagingService(this IMProtocolDataKind protocolKind) { switch (protocolKind) { case IMProtocolDataKind.Aim: return InstantMessagingService.Aim; case IMProtocolDataKind.Msn: return InstantMessagingService.Msn; case IMProtocolDataKind.Yahoo: return InstantMessagingService.Yahoo; case IMProtocolDataKind.Jabber: return InstantMessagingService.Jabber; case IMProtocolDataKind.Icq: return InstantMessagingService.Icq; default: return InstantMessagingService.Other; } } //internal static InstantMessagingType ToInstantMessagingType (this IMTypeDataKind imKind) //{ // switch (imKind) // { // case IMTypeDataKind.Home: // return InstantMessagingType.Home; // case IMTypeDataKind.Work: // return InstantMessagingType.Work; // default: // return InstantMessagingType.Other; // } //} } }
//Copyright (c) ServiceStack, Inc. All Rights Reserved. //License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt using System; using System.Globalization; using System.IO; namespace ServiceStack.Text { public static class Env { static Env() { if (PclExport.Instance == null) throw new ArgumentException("PclExport.Instance needs to be initialized"); #if NETSTANDARD IsNetStandard = true; try { IsLinux = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux); IsWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows); IsOSX = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX); IsNetCore3 = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription.StartsWith(".NET Core 3"); var fxDesc = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription; IsMono = fxDesc.Contains("Mono"); IsNetCore = fxDesc.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase); } catch (Exception) {} //throws PlatformNotSupportedException in AWS lambda IsUnix = IsOSX || IsLinux; HasMultiplePlatformTargets = true; IsUWP = IsRunningAsUwp(); #elif NET472 IsNetFramework = true; switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: IsWindows = true; break; } var platform = (int)Environment.OSVersion.Platform; IsUnix = platform == 4 || platform == 6 || platform == 128; if (File.Exists(@"/System/Library/CoreServices/SystemVersion.plist")) IsOSX = true; var osType = File.Exists(@"/proc/sys/kernel/ostype") ? File.ReadAllText(@"/proc/sys/kernel/ostype") : null; IsLinux = osType?.IndexOf("Linux", StringComparison.OrdinalIgnoreCase) >= 0; try { IsMono = AssemblyUtils.FindType("Mono.Runtime") != null; } catch (Exception) {} SupportsDynamic = true; #endif #if NETCORE2_1 IsNetStandard = false; IsNetCore = true; IsNetCore21 = true; SupportsDynamic = true; #endif #if NETSTANDARD2_0 IsNetStandard20 = true; #endif if (!IsUWP) { try { IsAndroid = AssemblyUtils.FindType("Android.Manifest") != null; if (IsOSX && IsMono) { var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); //iOS detection no longer trustworthy so assuming iOS based on some current heuristics. TODO: improve iOS detection IsIOS = runtimeDir.StartsWith("/private/var") || runtimeDir.Contains("/CoreSimulator/Devices/"); } } catch (Exception) {} } SupportsExpressions = true; SupportsEmit = !(IsUWP || IsIOS); if (!SupportsEmit) { ReflectionOptimizer.Instance = ExpressionReflectionOptimizer.Provider; } VersionString = ServiceStackVersion.ToString(CultureInfo.InvariantCulture); ServerUserAgent = "ServiceStack/" + VersionString + " " + PclExport.Instance.PlatformName + (IsMono ? "/Mono" : "") + (IsLinux ? "/Linux" : IsOSX ? "/OSX" : IsUnix ? "/Unix" : IsWindows ? "/Windows" : "/UnknownOS") + (IsIOS ? "/iOS" : IsAndroid ? "/Android" : IsUWP ? "/UWP" : ""); __releaseDate = new DateTime(2001,01,01); } public static string VersionString { get; set; } public static decimal ServiceStackVersion = 5.7m; public static bool IsLinux { get; set; } public static bool IsOSX { get; set; } public static bool IsUnix { get; set; } public static bool IsWindows { get; set; } public static bool IsMono { get; set; } public static bool IsIOS { get; set; } public static bool IsAndroid { get; set; } public static bool IsNetNative { get; set; } public static bool IsUWP { get; private set; } public static bool IsNetStandard { get; set; } public static bool IsNetCore21 { get; set; } public static bool IsNetStandard20 { get; set; } public static bool IsNetFramework { get; set; } public static bool IsNetCore { get; set; } public static bool IsNetCore3 { get; set; } public static bool SupportsExpressions { get; private set; } public static bool SupportsEmit { get; private set; } public static bool SupportsDynamic { get; private set; } private static bool strictMode; public static bool StrictMode { get => strictMode; set => Config.Instance.ThrowOnError = strictMode = value; } public static string ServerUserAgent { get; set; } public static bool HasMultiplePlatformTargets { get; set; } private static readonly DateTime __releaseDate; public static DateTime GetReleaseDate() { return __releaseDate; } [Obsolete("Use ReferenceAssemblyPath")] public static string ReferenceAssembyPath => ReferenceAssemblyPath; private static string referenceAssemblyPath; public static string ReferenceAssemblyPath { get { if (!IsMono && referenceAssemblyPath == null) { var programFilesPath = PclExport.Instance.GetEnvironmentVariable("ProgramFiles(x86)") ?? @"C:\Program Files (x86)"; var netFxReferenceBasePath = programFilesPath + @"\Reference Assemblies\Microsoft\Framework\.NETFramework\"; if ((netFxReferenceBasePath + @"v4.5.2\").DirectoryExists()) referenceAssemblyPath = netFxReferenceBasePath + @"v4.5.2\"; else if ((netFxReferenceBasePath + @"v4.5.1\").DirectoryExists()) referenceAssemblyPath = netFxReferenceBasePath + @"v4.5.1\"; else if ((netFxReferenceBasePath + @"v4.5\").DirectoryExists()) referenceAssemblyPath = netFxReferenceBasePath + @"v4.5\"; else if ((netFxReferenceBasePath + @"v4.0\").DirectoryExists()) referenceAssemblyPath = netFxReferenceBasePath + @"v4.0\"; else { var v4Dirs = PclExport.Instance.GetDirectoryNames(netFxReferenceBasePath, "v4*"); if (v4Dirs.Length == 0) { var winPath = PclExport.Instance.GetEnvironmentVariable("SYSTEMROOT") ?? @"C:\Windows"; var gacPath = winPath + @"\Microsoft.NET\Framework\"; v4Dirs = PclExport.Instance.GetDirectoryNames(gacPath, "v4*"); } if (v4Dirs.Length > 0) { referenceAssemblyPath = v4Dirs[v4Dirs.Length - 1] + @"\"; //latest v4 } else { throw new FileNotFoundException( "Could not infer .NET Reference Assemblies path, e.g '{0}'.\n".Fmt(netFxReferenceBasePath + @"v4.0\") + "Provide path manually 'Env.ReferenceAssembyPath'."); } } } return referenceAssemblyPath; } set => referenceAssemblyPath = value; } #if NETSTANDARD private static bool IsRunningAsUwp() { try { IsNetNative = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase); return IsInAppContainer || IsNetNative; } catch (Exception) {} return false; } private static bool IsWindows7OrLower { get { int versionMajor = Environment.OSVersion.Version.Major; int versionMinor = Environment.OSVersion.Version.Minor; double version = versionMajor + (double)versionMinor / 10; return version <= 6.1; } } // From: https://github.com/dotnet/corefx/blob/master/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Windows.cs private static int s_isInAppContainer = -1; private static bool IsInAppContainer { // This actually checks whether code is running in a modern app. // Currently this is the only situation where we run in app container. // If we want to distinguish the two cases in future, // EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token. get { if (s_isInAppContainer != -1) return s_isInAppContainer == 1; if (!IsWindows || IsWindows7OrLower) { s_isInAppContainer = 0; return false; } byte[] buffer = TypeConstants.EmptyByteArray; uint bufferSize = 0; try { int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer); switch (result) { case 15703: // APPMODEL_ERROR_NO_APPLICATION s_isInAppContainer = 0; break; case 0: // ERROR_SUCCESS case 122: // ERROR_INSUFFICIENT_BUFFER // Success is actually insufficent buffer as we're really only looking for // not NO_APPLICATION and we're not actually giving a buffer here. The // API will always return NO_APPLICATION if we're not running under a // WinRT process, no matter what size the buffer is. s_isInAppContainer = 1; break; default: throw new InvalidOperationException($"Failed to get AppId, result was {result}."); } } catch (Exception e) { // We could catch this here, being friendly with older portable surface area should we // desire to use this method elsewhere. if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal)) { // API doesn't exist, likely pre Win8 s_isInAppContainer = 0; } else { throw; } } return s_isInAppContainer == 1; } } [System.Runtime.InteropServices.DllImport("kernel32.dll", ExactSpelling = true)] private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId); #endif } }
#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; using System.Globalization; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; namespace Newtonsoft.Json.Serialization { internal class JsonSerializerProxy : JsonSerializer { private readonly JsonSerializerReader _serializerReader; private readonly JsonSerializerWriter _serializerWriter; private readonly JsonSerializer _serializer; public override event EventHandler<ErrorEventArgs> Error { add => _serializer.Error += value; remove => _serializer.Error -= value; } public override IReferenceResolver ReferenceResolver { get => _serializer.ReferenceResolver; set => _serializer.ReferenceResolver = value; } public override ITraceWriter TraceWriter { get => _serializer.TraceWriter; set => _serializer.TraceWriter = value; } public override IEqualityComparer EqualityComparer { get => _serializer.EqualityComparer; set => _serializer.EqualityComparer = value; } public override JsonConverterCollection Converters => _serializer.Converters; public override DefaultValueHandling DefaultValueHandling { get => _serializer.DefaultValueHandling; set => _serializer.DefaultValueHandling = value; } public override IContractResolver ContractResolver { get => _serializer.ContractResolver; set => _serializer.ContractResolver = value; } public override MissingMemberHandling MissingMemberHandling { get => _serializer.MissingMemberHandling; set => _serializer.MissingMemberHandling = value; } public override NullValueHandling NullValueHandling { get => _serializer.NullValueHandling; set => _serializer.NullValueHandling = value; } public override ObjectCreationHandling ObjectCreationHandling { get => _serializer.ObjectCreationHandling; set => _serializer.ObjectCreationHandling = value; } public override ReferenceLoopHandling ReferenceLoopHandling { get => _serializer.ReferenceLoopHandling; set => _serializer.ReferenceLoopHandling = value; } public override PreserveReferencesHandling PreserveReferencesHandling { get => _serializer.PreserveReferencesHandling; set => _serializer.PreserveReferencesHandling = value; } public override TypeNameHandling TypeNameHandling { get => _serializer.TypeNameHandling; set => _serializer.TypeNameHandling = value; } public override MetadataPropertyHandling MetadataPropertyHandling { get => _serializer.MetadataPropertyHandling; set => _serializer.MetadataPropertyHandling = value; } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public override FormatterAssemblyStyle TypeNameAssemblyFormat { get => _serializer.TypeNameAssemblyFormat; set => _serializer.TypeNameAssemblyFormat = value; } public override TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get => _serializer.TypeNameAssemblyFormatHandling; set => _serializer.TypeNameAssemblyFormatHandling = value; } public override ConstructorHandling ConstructorHandling { get => _serializer.ConstructorHandling; set => _serializer.ConstructorHandling = value; } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public override SerializationBinder Binder { get => _serializer.Binder; set => _serializer.Binder = value; } public override ISerializationBinder SerializationBinder { get => _serializer.SerializationBinder; set => _serializer.SerializationBinder = value; } public override StreamingContext Context { get => _serializer.Context; set => _serializer.Context = value; } public override Formatting Formatting { get => _serializer.Formatting; set => _serializer.Formatting = value; } public override DateFormatHandling DateFormatHandling { get => _serializer.DateFormatHandling; set => _serializer.DateFormatHandling = value; } public override DateTimeZoneHandling DateTimeZoneHandling { get => _serializer.DateTimeZoneHandling; set => _serializer.DateTimeZoneHandling = value; } public override DateParseHandling DateParseHandling { get => _serializer.DateParseHandling; set => _serializer.DateParseHandling = value; } public override FloatFormatHandling FloatFormatHandling { get => _serializer.FloatFormatHandling; set => _serializer.FloatFormatHandling = value; } public override FloatParseHandling FloatParseHandling { get => _serializer.FloatParseHandling; set => _serializer.FloatParseHandling = value; } public override StringEscapeHandling StringEscapeHandling { get => _serializer.StringEscapeHandling; set => _serializer.StringEscapeHandling = value; } public override string DateFormatString { get => _serializer.DateFormatString; set => _serializer.DateFormatString = value; } public override CultureInfo Culture { get => _serializer.Culture; set => _serializer.Culture = value; } public override int? MaxDepth { get => _serializer.MaxDepth; set => _serializer.MaxDepth = value; } public override bool CheckAdditionalContent { get => _serializer.CheckAdditionalContent; set => _serializer.CheckAdditionalContent = value; } internal JsonSerializerBase GetInternalSerializer() { if (_serializerReader != null) { return _serializerReader; } else { return _serializerWriter; } } public JsonSerializerProxy(JsonSerializerReader serializerReader) { ValidationUtils.ArgumentNotNull(serializerReader, nameof(serializerReader)); _serializerReader = serializerReader; _serializer = serializerReader.Serializer; } public JsonSerializerProxy(JsonSerializerWriter serializerWriter) { ValidationUtils.ArgumentNotNull(serializerWriter, nameof(serializerWriter)); _serializerWriter = serializerWriter; _serializer = serializerWriter.Serializer; } internal override object DeserializeInternal(JsonReader reader, Type objectType) { if (_serializerReader != null) { return _serializerReader.Deserialize(reader, objectType, false); } else { return _serializer.Deserialize(reader, objectType); } } internal override void PopulateInternal(JsonReader reader, object target) { if (_serializerReader != null) { _serializerReader.Populate(reader, target); } else { _serializer.Populate(reader, target); } } internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) { if (_serializerWriter != null) { _serializerWriter.Serialize(jsonWriter, value, rootType); } else { _serializer.Serialize(jsonWriter, value); } } } }
/////////////////////////////////////////////////////////////////////////// // Description: Data Access class for the table 'RS_Pangkat' // Generated by LLBLGen v1.21.2003.712 Final on: 18 December 2007, 21:01:07 // Because the Base Class already implements IDispose, this class doesn't. /////////////////////////////////////////////////////////////////////////// using System; using System.Data; using System.Data.SqlTypes; using System.Data.SqlClient; namespace SIMRS.DataAccess { /// <summary> /// Purpose: Data Access class for the table 'RS_Pangkat'. /// </summary> public class RS_Pangkat : DBInteractionBase { #region Class Member Declarations private SqlBoolean _published; private SqlDateTime _modifiedDate, _createdDate; private SqlInt32 _createdBy, _ordering, _modifiedBy, _id, _kelompokPangkatId, _kelompokPangkatIdOld, _statusId, _statusIdOld; private SqlString _kode, _nama, _keterangan; #endregion /// <summary> /// Purpose: Class constructor. /// </summary> public RS_Pangkat() { // Nothing for now. } public bool IsExist() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_IsExist]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@StatusId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusId)); cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString()); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_IsExist' reported the ErrorCode: " + _errorCode); } return IsExist == 1; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::IsExist::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Insert method. This method will insert one new row into the database. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>StatusId. May be SqlInt32.Null</LI> /// <LI>KelompokPangkatId. May be SqlInt32.Null</LI> /// <LI>Keterangan. May be SqlString.Null</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>ModifiedBy. May be SqlInt32.Null</LI> /// <LI>ModifiedDate. May be SqlDateTime.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Insert() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_Insert]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@StatusId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusId)); cmdToExecute.Parameters.Add(new SqlParameter("@KelompokPangkatId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelompokPangkatId)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published)); cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_Insert' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::Insert::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Update method. This method will Update one existing row in the database. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>StatusId. May be SqlInt32.Null</LI> /// <LI>KelompokPangkatId. May be SqlInt32.Null</LI> /// <LI>Keterangan. May be SqlString.Null</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>ModifiedBy. May be SqlInt32.Null</LI> /// <LI>ModifiedDate. May be SqlDateTime.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Update() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_Update]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@StatusId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusId)); cmdToExecute.Parameters.Add(new SqlParameter("@KelompokPangkatId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelompokPangkatId)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published)); cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_Update' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::Update::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Update method for updating one or more rows using the Foreign Key 'StatusId. /// This method will Update one or more existing rows in the database. It will reset the field 'StatusId' in /// all rows which have as value for this field the value as set in property 'StatusIdOld' to /// the value as set in property 'StatusId'. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>StatusId. May be SqlInt32.Null</LI> /// <LI>StatusIdOld. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public bool UpdateAllWStatusIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_UpdateAllWStatusIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@StatusId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _statusId)); cmdToExecute.Parameters.Add(new SqlParameter("@StatusIdOld", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusIdOld)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_UpdateAllWStatusIdLogic' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::UpdateAllWStatusIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Update method for updating one or more rows using the Foreign Key 'KelompokPangkatId. /// This method will Update one or more existing rows in the database. It will reset the field 'KelompokPangkatId' in /// all rows which have as value for this field the value as set in property 'KelompokPangkatIdOld' to /// the value as set in property 'KelompokPangkatId'. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>KelompokPangkatId. May be SqlInt32.Null</LI> /// <LI>KelompokPangkatIdOld. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public bool UpdateAllWKelompokPangkatIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_UpdateAllWKelompokPangkatIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@KelompokPangkatId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kelompokPangkatId)); cmdToExecute.Parameters.Add(new SqlParameter("@KelompokPangkatIdOld", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelompokPangkatIdOld)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_UpdateAllWKelompokPangkatIdLogic' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::UpdateAllWKelompokPangkatIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Delete() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_Delete]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_Delete' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::Delete::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Delete method for a foreign key. This method will Delete one or more rows from the database, based on the Foreign Key 'StatusId' /// </summary> /// <returns>True if succeeded, false otherwise. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>StatusId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public bool DeleteAllWStatusIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_DeleteAllWStatusIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@StatusId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _statusId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_DeleteAllWStatusIdLogic' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::DeleteAllWStatusIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Delete method for a foreign key. This method will Delete one or more rows from the database, based on the Foreign Key 'KelompokPangkatId' /// </summary> /// <returns>True if succeeded, false otherwise. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>KelompokPangkatId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public bool DeleteAllWKelompokPangkatIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_DeleteAllWKelompokPangkatIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@KelompokPangkatId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kelompokPangkatId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_DeleteAllWKelompokPangkatIdLogic' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::DeleteAllWKelompokPangkatIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>StatusId</LI> /// <LI>KelompokPangkatId</LI> /// <LI>Keterangan</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>ModifiedBy</LI> /// <LI>ModifiedDate</LI> /// </UL> /// Will fill all properties corresponding with a field in the table with the value of the row selected. /// </remarks> public override DataTable SelectOne() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_SelectOne]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Pangkat"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_SelectOne' reported the ErrorCode: " + _errorCode); } if (toReturn.Rows.Count > 0) { _id = (Int32)toReturn.Rows[0]["Id"]; _kode = (string)toReturn.Rows[0]["Kode"]; _nama = (string)toReturn.Rows[0]["Nama"]; _statusId = toReturn.Rows[0]["StatusId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["StatusId"]; _kelompokPangkatId = toReturn.Rows[0]["KelompokPangkatId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["KelompokPangkatId"]; _keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"]; _published = (bool)toReturn.Rows[0]["Published"]; _ordering = (Int32)toReturn.Rows[0]["Ordering"]; _createdBy = (Int32)toReturn.Rows[0]["CreatedBy"]; _createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"]; _modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"]; _modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"]; } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::SelectOne::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: SelectAll method. This method will Select all rows from the table. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override DataTable SelectAll() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_SelectAll]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Pangkat"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_SelectAll' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::SelectAll::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'StatusId' /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>StatusId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public DataTable SelectAllWStatusIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_SelectAllWStatusIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Pangkat"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@StatusId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_SelectAllWStatusIdLogic' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::SelectAllWStatusIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'KelompokPangkatId' /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>KelompokPangkatId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public DataTable SelectAllWKelompokPangkatIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_SelectAllWKelompokPangkatIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Pangkat"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@KelompokPangkatId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _kelompokPangkatId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_SelectAllWKelompokPangkatIdLogic' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::SelectAllWKelompokPangkatIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } public DataTable GetList() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_GetList]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Pangkat"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_GetList' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::GetList::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } public DataTable GetListByStatusId() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_Pangkat_GetListByStatusId]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_Pangkat"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@StatusId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_Pangkat_GetListByStatusId' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_Pangkat::GetListByStatusId::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } #region Class Property Declarations public SqlInt32 Id { get { return _id; } set { SqlInt32 idTmp = (SqlInt32)value; if (idTmp.IsNull) { throw new ArgumentOutOfRangeException("Id", "Id can't be NULL"); } _id = value; } } public SqlString Kode { get { return _kode; } set { SqlString kodeTmp = (SqlString)value; if (kodeTmp.IsNull) { throw new ArgumentOutOfRangeException("Kode", "Kode can't be NULL"); } _kode = value; } } public SqlString Nama { get { return _nama; } set { SqlString namaTmp = (SqlString)value; if (namaTmp.IsNull) { throw new ArgumentOutOfRangeException("Nama", "Nama can't be NULL"); } _nama = value; } } public SqlInt32 StatusId { get { return _statusId; } set { _statusId = value; } } public SqlInt32 StatusIdOld { get { return _statusIdOld; } set { _statusIdOld = value; } } public SqlInt32 KelompokPangkatId { get { return _kelompokPangkatId; } set { _kelompokPangkatId = value; } } public SqlInt32 KelompokPangkatIdOld { get { return _kelompokPangkatIdOld; } set { _kelompokPangkatIdOld = value; } } public SqlString Keterangan { get { return _keterangan; } set { _keterangan = value; } } public SqlBoolean Published { get { return _published; } set { _published = value; } } public SqlInt32 Ordering { get { return _ordering; } set { SqlInt32 orderingTmp = (SqlInt32)value; if (orderingTmp.IsNull) { throw new ArgumentOutOfRangeException("Ordering", "Ordering can't be NULL"); } _ordering = value; } } public SqlInt32 CreatedBy { get { return _createdBy; } set { SqlInt32 createdByTmp = (SqlInt32)value; if (createdByTmp.IsNull) { throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL"); } _createdBy = value; } } public SqlDateTime CreatedDate { get { return _createdDate; } set { SqlDateTime createdDateTmp = (SqlDateTime)value; if (createdDateTmp.IsNull) { throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL"); } _createdDate = value; } } public SqlInt32 ModifiedBy { get { return _modifiedBy; } set { _modifiedBy = value; } } public SqlDateTime ModifiedDate { get { return _modifiedDate; } set { _modifiedDate = value; } } #endregion } }
#if UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 #define UNITY_5_4_OR_LOWER #else #define UNITY_5_5_OR_HIGHER #endif #if UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 #define UNITY_5_5_OR_LOWER #else #define UNITY_5_6_OR_HIGHER #endif using UnityEngine; using UnityEditor; #if !UNITY_4_6 && !UNITY_4_7 using UnityEngine.Rendering; #endif using ProBuilder2.Common; using ProBuilder2.EditorCommon; using System.Collections; using System.Linq; public class pb_Preferences { private static bool prefsLoaded = false; static Color pbDefaultFaceColor; static Color pbDefaultEdgeColor; static Color pbDefaultSelectedVertexColor; static Color pbDefaultVertexColor; static bool defaultOpenInDockableWindow; static Material pbDefaultMaterial; static Vector2 settingsScroll = Vector2.zero; static bool pbShowEditorNotifications; static bool pbForceConvex = false; static bool pbDragCheckLimit = false; static bool pbForceVertexPivot = true; static bool pbForceGridPivot = true; static bool pbPerimeterEdgeBridgeOnly; static bool pbPBOSelectionOnly; static bool pbCloseShapeWindow = false; static bool pbUVEditorFloating = true; static bool pbStripProBuilderOnBuild = true; static bool pbDisableAutoUV2Generation = false; static bool pbShowSceneInfo = false; static bool pbUniqueModeShortcuts = false; static bool pbIconGUI = false; static bool pbShiftOnlyTooltips = false; static bool pbDrawAxisLines = true; static bool pbMeshesAreAssets = false; static bool pbElementSelectIsHamFisted = false; static bool pbDragSelectWholeElement = false; static bool pbEnableExperimental = false; static bool showMissingLightmapUvWarning = true; #if !UNITY_4_6 && !UNITY_4_7 static ShadowCastingMode pbShadowCastingMode = ShadowCastingMode.On; #endif static ColliderType defaultColliderType = ColliderType.BoxCollider; static SceneToolbarLocation pbToolbarLocation = SceneToolbarLocation.UpperCenter; static EntityType pbDefaultEntity = EntityType.Detail; static float pbUVGridSnapValue; static float pbVertexHandleSize; static pb_Shortcut[] defaultShortcuts; [PreferenceItem (pb_Constant.PRODUCT_NAME)] public static void PreferencesGUI () { // Load the preferences if (!prefsLoaded) { LoadPrefs(); prefsLoaded = true; } settingsScroll = EditorGUILayout.BeginScrollView(settingsScroll, GUILayout.MinHeight(180), GUILayout.MaxHeight(180)); EditorGUI.BeginChangeCheck(); if(GUILayout.Button("Reset All Preferences")) ResetToDefaults(); /** * GENERAL SETTINGS */ GUILayout.Label("General Settings", EditorStyles.boldLabel); pbStripProBuilderOnBuild = EditorGUILayout.Toggle(new GUIContent("Strip PB Scripts on Build", "If true, when building an executable all ProBuilder scripts will be stripped from your built product."), pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = EditorGUILayout.Toggle(new GUIContent("Disable Auto UV2 Generation", "Disables automatic generation of UV2 channel. If Unity is sluggish when working with large ProBuilder objects, disabling UV2 generation will improve performance. Use `Actions/Generate UV2` or `Actions/Generate Scene UV2` to build lightmap UVs prior to baking."), pbDisableAutoUV2Generation); pbShowSceneInfo = EditorGUILayout.Toggle(new GUIContent("Show Scene Info", "Displays the selected object vertex and triangle counts in the scene view."), pbShowSceneInfo); pbShowEditorNotifications = EditorGUILayout.Toggle("Show Editor Notifications", pbShowEditorNotifications); /** * TOOLBAR SETTINGS */ GUILayout.Label("Toolbar Settings", EditorStyles.boldLabel); pbIconGUI = EditorGUILayout.Toggle(new GUIContent("Use Icon GUI", "Toggles the ProBuilder window interface between text and icon versions."), pbIconGUI); pbShiftOnlyTooltips = EditorGUILayout.Toggle(new GUIContent("Shift Key Tooltips", "Tooltips will only show when the Shift key is held"), pbShiftOnlyTooltips); pbToolbarLocation = (SceneToolbarLocation) EditorGUILayout.EnumPopup("Toolbar Location", pbToolbarLocation); pbUniqueModeShortcuts = EditorGUILayout.Toggle(new GUIContent("Unique Mode Shortcuts", "When off, the G key toggles between Object and Element modes and H enumerates the element modes. If on, G, H, J, and K are shortcuts to Object, Vertex, Edge, and Face modes respectively."), pbUniqueModeShortcuts); defaultOpenInDockableWindow = EditorGUILayout.Toggle("Open in Dockable Window", defaultOpenInDockableWindow); /** * DEFAULT SETTINGS */ GUILayout.Label("Defaults", EditorStyles.boldLabel); pbDefaultMaterial = (Material) EditorGUILayout.ObjectField("Default Material", pbDefaultMaterial, typeof(Material), false); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Entity"); pbDefaultEntity = ((EntityType)EditorGUILayout.EnumPopup( (EntityType)pbDefaultEntity )); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Collider"); defaultColliderType = ((ColliderType)EditorGUILayout.EnumPopup( (ColliderType)defaultColliderType )); GUILayout.EndHorizontal(); if((ColliderType)defaultColliderType == ColliderType.MeshCollider) pbForceConvex = EditorGUILayout.Toggle("Force Convex Mesh Collider", pbForceConvex); #if !UNITY_4_6 && !UNITY_4_7 GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Shadow Casting Mode"); pbShadowCastingMode = (ShadowCastingMode) EditorGUILayout.EnumPopup(pbShadowCastingMode); GUILayout.EndHorizontal(); #endif /** * MISC. SETTINGS */ GUILayout.Label("Misc. Settings", EditorStyles.boldLabel); pbDragCheckLimit = EditorGUILayout.Toggle(new GUIContent("Limit Drag Check to Selection", "If true, when drag selecting faces, only currently selected pb-Objects will be tested for matching faces. If false, all pb_Objects in the scene will be checked. The latter may be slower in large scenes."), pbDragCheckLimit); pbPBOSelectionOnly = EditorGUILayout.Toggle(new GUIContent("Only PBO are Selectable", "If true, you will not be able to select non probuilder objects in Geometry and Texture mode"), pbPBOSelectionOnly); pbCloseShapeWindow = EditorGUILayout.Toggle(new GUIContent("Close shape window after building", "If true the shape window will close after hitting the build button"), pbCloseShapeWindow); pbDrawAxisLines = EditorGUILayout.Toggle(new GUIContent("Dimension Overlay Lines", "When the Dimensions Overlay is on, this toggle shows or hides the axis lines."), pbDrawAxisLines); showMissingLightmapUvWarning = EditorGUILayout.Toggle("Show Missing Lightmap UVs Warning", showMissingLightmapUvWarning); GUILayout.Space(4); /** * GEOMETRY EDITING SETTINGS */ GUILayout.Label("Geometry Editing Settings", EditorStyles.boldLabel); pbElementSelectIsHamFisted = !EditorGUILayout.Toggle(new GUIContent("Precise Element Selection", "When enabled you will be able to select object faces when in Vertex of Edge mode by clicking the center of a face. When disabled, edge and vertex selection will always be restricted to the nearest element."), !pbElementSelectIsHamFisted); pbDragSelectWholeElement = EditorGUILayout.Toggle("Precise Drag Select", pbDragSelectWholeElement); pbDefaultFaceColor = EditorGUILayout.ColorField("Selected Face Color", pbDefaultFaceColor); pbDefaultEdgeColor = EditorGUILayout.ColorField("Edge Wireframe Color", pbDefaultEdgeColor); pbDefaultVertexColor = EditorGUILayout.ColorField("Vertex Color", pbDefaultVertexColor); pbDefaultSelectedVertexColor = EditorGUILayout.ColorField("Selected Vertex Color", pbDefaultSelectedVertexColor); pbVertexHandleSize = EditorGUILayout.Slider("Vertex Handle Size", pbVertexHandleSize, 0f, 3f); pbForceVertexPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Vertex Point", "If true, new objects will automatically have their pivot point set to a vertex instead of the center."), pbForceVertexPivot); pbForceGridPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Grid", "If true, newly instantiated pb_Objects will be snapped to the nearest point on grid. If ProGrids is present, the snap value will be used, otherwise decimals are simply rounded to whole numbers."), pbForceGridPivot); pbPerimeterEdgeBridgeOnly = EditorGUILayout.Toggle(new GUIContent("Bridge Perimeter Edges Only", "If true, only edges on the perimeters of an object may be bridged. If false, you may bridge any between any two edges you like."), pbPerimeterEdgeBridgeOnly); GUILayout.Space(4); GUILayout.Label("Experimental", EditorStyles.boldLabel); pbEnableExperimental = EditorGUILayout.Toggle(new GUIContent("Experimental Features", "Enables some experimental new features that we're trying out. These may be incomplete or buggy, so please exercise caution when making use of this functionality!"), pbEnableExperimental); pbMeshesAreAssets = EditorGUILayout.Toggle(new GUIContent("Meshes Are Assets", "Experimental! Instead of storing mesh data in the scene, this toggle creates a Mesh cache in the Project that ProBuilder will use."), pbMeshesAreAssets); GUILayout.Space(4); /** * UV EDITOR SETTINGS */ GUILayout.Label("UV Editing Settings", EditorStyles.boldLabel); pbUVGridSnapValue = EditorGUILayout.FloatField("UV Snap Increment", pbUVGridSnapValue); pbUVGridSnapValue = Mathf.Clamp(pbUVGridSnapValue, .015625f, 2f); pbUVEditorFloating = EditorGUILayout.Toggle(new GUIContent("Editor window floating", "If true UV Editor window will open as a floating window"), pbUVEditorFloating); EditorGUILayout.EndScrollView(); GUILayout.Space(4); GUILayout.Label("Shortcut Settings", EditorStyles.boldLabel); ShortcutSelectPanel(); ShortcutEditPanel(); // Save the preferences if (EditorGUI.EndChangeCheck()) SetPrefs(); } public static void ResetToDefaults() { if(EditorUtility.DisplayDialog("Delete ProBuilder editor preferences?", "Are you sure you want to delete all existing ProBuilder preferences?\n\nThis action cannot be undone.", "Yes", "No")) { pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultFaceColor); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultEditLevel); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultSelectionMode); pb_PreferencesInternal.DeleteKey(pb_Constant.pbHandleAlignment); pb_PreferencesInternal.DeleteKey(pb_Constant.pbVertexColorTool); pb_PreferencesInternal.DeleteKey(pb_Constant.pbToolbarLocation); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultEntity); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultFaceColor); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultEdgeColor); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultSelectedVertexColor); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultVertexColor); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultOpenInDockableWindow); pb_PreferencesInternal.DeleteKey(pb_Constant.pbEditorPrefVersion); pb_PreferencesInternal.DeleteKey(pb_Constant.pbEditorShortcutsVersion); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultCollider); pb_PreferencesInternal.DeleteKey(pb_Constant.pbForceConvex); pb_PreferencesInternal.DeleteKey(pb_Constant.pbVertexColorPrefs); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowEditorNotifications); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDragCheckLimit); pb_PreferencesInternal.DeleteKey(pb_Constant.pbForceVertexPivot); pb_PreferencesInternal.DeleteKey(pb_Constant.pbForceGridPivot); pb_PreferencesInternal.DeleteKey(pb_Constant.pbManifoldEdgeExtrusion); pb_PreferencesInternal.DeleteKey(pb_Constant.pbPerimeterEdgeBridgeOnly); pb_PreferencesInternal.DeleteKey(pb_Constant.pbPBOSelectionOnly); pb_PreferencesInternal.DeleteKey(pb_Constant.pbCloseShapeWindow); pb_PreferencesInternal.DeleteKey(pb_Constant.pbUVEditorFloating); pb_PreferencesInternal.DeleteKey(pb_Constant.pbUVMaterialPreview); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowSceneToolbar); pb_PreferencesInternal.DeleteKey(pb_Constant.pbNormalizeUVsOnPlanarProjection); pb_PreferencesInternal.DeleteKey(pb_Constant.pbStripProBuilderOnBuild); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDisableAutoUV2Generation); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowSceneInfo); pb_PreferencesInternal.DeleteKey(pb_Constant.pbEnableBackfaceSelection); pb_PreferencesInternal.DeleteKey(pb_Constant.pbVertexPaletteDockable); pb_PreferencesInternal.DeleteKey(pb_Constant.pbExtrudeAsGroup); pb_PreferencesInternal.DeleteKey(pb_Constant.pbUniqueModeShortcuts); pb_PreferencesInternal.DeleteKey(pb_Constant.pbMaterialEditorFloating); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShapeWindowFloating); pb_PreferencesInternal.DeleteKey(pb_Constant.pbIconGUI); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShiftOnlyTooltips); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDrawAxisLines); pb_PreferencesInternal.DeleteKey(pb_Constant.pbCollapseVertexToFirst); pb_PreferencesInternal.DeleteKey(pb_Constant.pbMeshesAreAssets); pb_PreferencesInternal.DeleteKey(pb_Constant.pbElementSelectIsHamFisted); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDragSelectWholeElement); pb_PreferencesInternal.DeleteKey(pb_Constant.pbEnableExperimental); pb_PreferencesInternal.DeleteKey(pb_Constant.pbFillHoleSelectsEntirePath); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDetachToNewObject); pb_PreferencesInternal.DeleteKey(pb_Constant.pbPreserveFaces); pb_PreferencesInternal.DeleteKey(pb_Constant.pbVertexHandleSize); pb_PreferencesInternal.DeleteKey(pb_Constant.pbUVGridSnapValue); pb_PreferencesInternal.DeleteKey(pb_Constant.pbUVWeldDistance); pb_PreferencesInternal.DeleteKey(pb_Constant.pbWeldDistance); pb_PreferencesInternal.DeleteKey(pb_Constant.pbExtrudeDistance); pb_PreferencesInternal.DeleteKey(pb_Constant.pbBevelAmount); pb_PreferencesInternal.DeleteKey(pb_Constant.pbEdgeSubdivisions); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultShortcuts); pb_PreferencesInternal.DeleteKey(pb_Constant.pbDefaultMaterial); pb_PreferencesInternal.DeleteKey(pb_Constant.pbGrowSelectionUsingAngle); pb_PreferencesInternal.DeleteKey(pb_Constant.pbGrowSelectionAngle); pb_PreferencesInternal.DeleteKey(pb_Constant.pbGrowSelectionAngleIterative); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowDetail); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowOccluder); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowMover); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowCollider); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowTrigger); pb_PreferencesInternal.DeleteKey(pb_Constant.pbShowNoDraw); pb_PreferencesInternal.DeleteKey("pb_Lightmapping::showMissingLightmapUvWarning"); #if !UNITY_4_6 && !UNITY_4_7 pb_PreferencesInternal.DeleteKey(pb_Constant.pbShadowCastingMode); #endif } LoadPrefs(); } static int shortcutIndex = 0; #if UNITY_5_6_OR_HIGHER static Rect selectBox = new Rect(0, 214, 183, 156); static Rect shortcutEditRect = new Rect(190, 191, 178, 300); #else static Rect selectBox = new Rect(130, 253, 183, 142); static Rect shortcutEditRect = new Rect(320, 228, 178, 300); #endif static Vector2 shortcutScroll = Vector2.zero; static int CELL_HEIGHT = 20; static void ShortcutSelectPanel() { GUILayout.Space(4); GUI.contentColor = Color.white; GUI.Box(selectBox, ""); GUIStyle labelStyle = GUIStyle.none; if(EditorGUIUtility.isProSkin) labelStyle.normal.textColor = new Color(1f, 1f, 1f, .8f); labelStyle.alignment = TextAnchor.MiddleLeft; labelStyle.contentOffset = new Vector2(4f, 0f); shortcutScroll = EditorGUILayout.BeginScrollView(shortcutScroll, false, true, GUILayout.MaxWidth(183), GUILayout.MaxHeight(156)); for(int n = 1; n < defaultShortcuts.Length; n++) { if(n == shortcutIndex) { GUI.backgroundColor = new Color(0.23f, .49f, .89f, 1f); labelStyle.normal.background = EditorGUIUtility.whiteTexture; Color oc = labelStyle.normal.textColor; labelStyle.normal.textColor = Color.white; GUILayout.Box(defaultShortcuts[n].action, labelStyle, GUILayout.MinHeight(CELL_HEIGHT), GUILayout.MaxHeight(CELL_HEIGHT)); labelStyle.normal.background = null; labelStyle.normal.textColor = oc; GUI.backgroundColor = Color.white; } else { if(GUILayout.Button(defaultShortcuts[n].action, labelStyle, GUILayout.MinHeight(CELL_HEIGHT), GUILayout.MaxHeight(CELL_HEIGHT))) { shortcutIndex = n; } } } EditorGUILayout.EndScrollView(); } static void ShortcutEditPanel() { GUILayout.BeginArea(shortcutEditRect); // descriptionTitleRect = EditorGUI.RectField(new Rect(240,150,200,50), descriptionTitleRect); GUILayout.Label("Key", EditorStyles.boldLabel); KeyCode key = defaultShortcuts[shortcutIndex].key; key = (KeyCode) EditorGUILayout.EnumPopup(key); defaultShortcuts[shortcutIndex].key = key; GUILayout.Label("Modifiers", EditorStyles.boldLabel); // EnumMaskField returns a bit-mask where the flags correspond to the indices of the enum, not the enum values, // so this isn't technically correct. EventModifiers em = (EventModifiers) (((int)defaultShortcuts[shortcutIndex].eventModifiers) * 2); em = (EventModifiers)EditorGUILayout.EnumMaskField(em); defaultShortcuts[shortcutIndex].eventModifiers = (EventModifiers) (((int)em) / 2); GUILayout.Label("Description", EditorStyles.boldLabel); GUILayout.Label(defaultShortcuts[shortcutIndex].description, EditorStyles.wordWrappedLabel); GUILayout.EndArea(); } static void LoadPrefs() { pbStripProBuilderOnBuild = pb_PreferencesInternal.GetBool(pb_Constant.pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = pb_PreferencesInternal.GetBool(pb_Constant.pbDisableAutoUV2Generation); pbShowSceneInfo = pb_PreferencesInternal.GetBool(pb_Constant.pbShowSceneInfo); defaultOpenInDockableWindow = pb_PreferencesInternal.GetBool(pb_Constant.pbDefaultOpenInDockableWindow); pbDragCheckLimit = pb_PreferencesInternal.GetBool(pb_Constant.pbDragCheckLimit); pbForceConvex = pb_PreferencesInternal.GetBool(pb_Constant.pbForceConvex); pbForceGridPivot = pb_PreferencesInternal.GetBool(pb_Constant.pbForceGridPivot); pbForceVertexPivot = pb_PreferencesInternal.GetBool(pb_Constant.pbForceVertexPivot); pbPerimeterEdgeBridgeOnly = pb_PreferencesInternal.GetBool(pb_Constant.pbPerimeterEdgeBridgeOnly); pbPBOSelectionOnly = pb_PreferencesInternal.GetBool(pb_Constant.pbPBOSelectionOnly); pbCloseShapeWindow = pb_PreferencesInternal.GetBool(pb_Constant.pbCloseShapeWindow); pbUVEditorFloating = pb_PreferencesInternal.GetBool(pb_Constant.pbUVEditorFloating); // pbShowSceneToolbar = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneToolbar); pbShowEditorNotifications = pb_PreferencesInternal.GetBool(pb_Constant.pbShowEditorNotifications); pbUniqueModeShortcuts = pb_PreferencesInternal.GetBool(pb_Constant.pbUniqueModeShortcuts); pbIconGUI = pb_PreferencesInternal.GetBool(pb_Constant.pbIconGUI); pbShiftOnlyTooltips = pb_PreferencesInternal.GetBool(pb_Constant.pbShiftOnlyTooltips); pbDrawAxisLines = pb_PreferencesInternal.GetBool(pb_Constant.pbDrawAxisLines); pbMeshesAreAssets = pb_PreferencesInternal.GetBool(pb_Constant.pbMeshesAreAssets); pbElementSelectIsHamFisted = pb_PreferencesInternal.GetBool(pb_Constant.pbElementSelectIsHamFisted); pbDragSelectWholeElement = pb_PreferencesInternal.GetBool(pb_Constant.pbDragSelectWholeElement); pbEnableExperimental = pb_PreferencesInternal.GetBool(pb_Constant.pbEnableExperimental); showMissingLightmapUvWarning = pb_PreferencesInternal.GetBool("pb_Lightmapping::showMissingLightmapUvWarning", true); pbDefaultFaceColor = pb_PreferencesInternal.GetColor( pb_Constant.pbDefaultFaceColor ); pbDefaultEdgeColor = pb_PreferencesInternal.GetColor( pb_Constant.pbDefaultEdgeColor ); pbDefaultSelectedVertexColor = pb_PreferencesInternal.GetColor( pb_Constant.pbDefaultSelectedVertexColor ); pbDefaultVertexColor = pb_PreferencesInternal.GetColor( pb_Constant.pbDefaultVertexColor ); pbUVGridSnapValue = pb_PreferencesInternal.GetFloat(pb_Constant.pbUVGridSnapValue); pbVertexHandleSize = pb_PreferencesInternal.GetFloat(pb_Constant.pbVertexHandleSize); defaultColliderType = pb_PreferencesInternal.GetEnum<ColliderType>(pb_Constant.pbDefaultCollider); pbToolbarLocation = pb_PreferencesInternal.GetEnum<SceneToolbarLocation>(pb_Constant.pbToolbarLocation); pbDefaultEntity = pb_PreferencesInternal.GetEnum<EntityType>(pb_Constant.pbDefaultEntity); #if !UNITY_4_6 && !UNITY_4_7 pbShadowCastingMode = pb_PreferencesInternal.GetEnum<ShadowCastingMode>(pb_Constant.pbShadowCastingMode); #endif pbDefaultMaterial = pb_PreferencesInternal.GetMaterial(pb_Constant.pbDefaultMaterial); defaultShortcuts = pb_PreferencesInternal.GetShortcuts().ToArray(); } public static void SetPrefs() { pb_PreferencesInternal.SetBool (pb_Constant.pbStripProBuilderOnBuild, pbStripProBuilderOnBuild); pb_PreferencesInternal.SetBool (pb_Constant.pbDisableAutoUV2Generation, pbDisableAutoUV2Generation); pb_PreferencesInternal.SetBool (pb_Constant.pbShowSceneInfo, pbShowSceneInfo, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetInt (pb_Constant.pbToolbarLocation, (int) pbToolbarLocation, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetInt (pb_Constant.pbDefaultEntity, (int) pbDefaultEntity); pb_PreferencesInternal.SetColor (pb_Constant.pbDefaultFaceColor, pbDefaultFaceColor, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetColor (pb_Constant.pbDefaultEdgeColor, pbDefaultEdgeColor, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetColor (pb_Constant.pbDefaultSelectedVertexColor, pbDefaultSelectedVertexColor, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetColor (pb_Constant.pbDefaultVertexColor, pbDefaultVertexColor, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetString (pb_Constant.pbDefaultShortcuts, pb_Shortcut.ShortcutsToString(defaultShortcuts), pb_PreferenceLocation.Global); pb_PreferencesInternal.SetMaterial(pb_Constant.pbDefaultMaterial, pbDefaultMaterial); pb_PreferencesInternal.SetInt (pb_Constant.pbDefaultCollider, (int) defaultColliderType); #if !UNITY_4_6 && !UNITY_4_7 pb_PreferencesInternal.SetInt (pb_Constant.pbShadowCastingMode, (int) pbShadowCastingMode); #endif pb_PreferencesInternal.SetBool (pb_Constant.pbDefaultOpenInDockableWindow, defaultOpenInDockableWindow, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbShowEditorNotifications, pbShowEditorNotifications, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbForceConvex, pbForceConvex); pb_PreferencesInternal.SetBool (pb_Constant.pbDragCheckLimit, pbDragCheckLimit, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbForceVertexPivot, pbForceVertexPivot, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbForceGridPivot, pbForceGridPivot, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbPerimeterEdgeBridgeOnly, pbPerimeterEdgeBridgeOnly, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbPBOSelectionOnly, pbPBOSelectionOnly, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbCloseShapeWindow, pbCloseShapeWindow, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbUVEditorFloating, pbUVEditorFloating, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbUniqueModeShortcuts, pbUniqueModeShortcuts, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbIconGUI, pbIconGUI, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbShiftOnlyTooltips, pbShiftOnlyTooltips, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbDrawAxisLines, pbDrawAxisLines, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbMeshesAreAssets, pbMeshesAreAssets); pb_PreferencesInternal.SetBool (pb_Constant.pbElementSelectIsHamFisted, pbElementSelectIsHamFisted, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbDragSelectWholeElement, pbDragSelectWholeElement, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool (pb_Constant.pbEnableExperimental, pbEnableExperimental, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetBool ("pb_Lightmapping::showMissingLightmapUvWarning", showMissingLightmapUvWarning, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetFloat (pb_Constant.pbVertexHandleSize, pbVertexHandleSize, pb_PreferenceLocation.Global); pb_PreferencesInternal.SetFloat (pb_Constant.pbUVGridSnapValue, pbUVGridSnapValue, pb_PreferenceLocation.Global); if(pb_Editor.instance != null) pb_Editor.instance.OnEnable(); SceneView.RepaintAll(); } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IProductionLotApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search productionLots by filter /// </summary> /// <remarks> /// Returns the list of productionLots that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;ProductionLot&gt;</returns> List<ProductionLot> GetProductionLotByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search productionLots by filter /// </summary> /// <remarks> /// Returns the list of productionLots that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;ProductionLot&gt;</returns> ApiResponse<List<ProductionLot>> GetProductionLotByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a productionLot by id /// </summary> /// <remarks> /// Returns the productionLot identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="productionLotId">Id of the productionLot to be returned.</param> /// <returns>ProductionLot</returns> ProductionLot GetProductionLotById (int? productionLotId); /// <summary> /// Get a productionLot by id /// </summary> /// <remarks> /// Returns the productionLot identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="productionLotId">Id of the productionLot to be returned.</param> /// <returns>ApiResponse of ProductionLot</returns> ApiResponse<ProductionLot> GetProductionLotByIdWithHttpInfo (int? productionLotId); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search productionLots by filter /// </summary> /// <remarks> /// Returns the list of productionLots that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;ProductionLot&gt;</returns> System.Threading.Tasks.Task<List<ProductionLot>> GetProductionLotByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search productionLots by filter /// </summary> /// <remarks> /// Returns the list of productionLots that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;ProductionLot&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<ProductionLot>>> GetProductionLotByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a productionLot by id /// </summary> /// <remarks> /// Returns the productionLot identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="productionLotId">Id of the productionLot to be returned.</param> /// <returns>Task of ProductionLot</returns> System.Threading.Tasks.Task<ProductionLot> GetProductionLotByIdAsync (int? productionLotId); /// <summary> /// Get a productionLot by id /// </summary> /// <remarks> /// Returns the productionLot identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="productionLotId">Id of the productionLot to be returned.</param> /// <returns>Task of ApiResponse (ProductionLot)</returns> System.Threading.Tasks.Task<ApiResponse<ProductionLot>> GetProductionLotByIdAsyncWithHttpInfo (int? productionLotId); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ProductionLotApi : IProductionLotApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ProductionLotApi"/> class. /// </summary> /// <returns></returns> public ProductionLotApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.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="ProductionLotApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ProductionLotApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.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 Infoplus.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> /// Search productionLots by filter Returns the list of productionLots that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;ProductionLot&gt;</returns> public List<ProductionLot> GetProductionLotByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<ProductionLot>> localVarResponse = GetProductionLotByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search productionLots by filter Returns the list of productionLots that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;ProductionLot&gt;</returns> public ApiResponse< List<ProductionLot> > GetProductionLotByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/productionLot/search"; 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[] { }; 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 (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // 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.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetProductionLotByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<ProductionLot>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<ProductionLot>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductionLot>))); } /// <summary> /// Search productionLots by filter Returns the list of productionLots that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;ProductionLot&gt;</returns> public async System.Threading.Tasks.Task<List<ProductionLot>> GetProductionLotByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<ProductionLot>> localVarResponse = await GetProductionLotByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search productionLots by filter Returns the list of productionLots that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;ProductionLot&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<ProductionLot>>> GetProductionLotByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/productionLot/search"; 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[] { }; 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 (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // 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.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetProductionLotByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<ProductionLot>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<ProductionLot>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductionLot>))); } /// <summary> /// Get a productionLot by id Returns the productionLot identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="productionLotId">Id of the productionLot to be returned.</param> /// <returns>ProductionLot</returns> public ProductionLot GetProductionLotById (int? productionLotId) { ApiResponse<ProductionLot> localVarResponse = GetProductionLotByIdWithHttpInfo(productionLotId); return localVarResponse.Data; } /// <summary> /// Get a productionLot by id Returns the productionLot identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="productionLotId">Id of the productionLot to be returned.</param> /// <returns>ApiResponse of ProductionLot</returns> public ApiResponse< ProductionLot > GetProductionLotByIdWithHttpInfo (int? productionLotId) { // verify the required parameter 'productionLotId' is set if (productionLotId == null) throw new ApiException(400, "Missing required parameter 'productionLotId' when calling ProductionLotApi->GetProductionLotById"); var localVarPath = "/v1.0/productionLot/{productionLotId}"; 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[] { }; 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 (productionLotId != null) localVarPathParams.Add("productionLotId", Configuration.ApiClient.ParameterToString(productionLotId)); // path parameter // 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.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetProductionLotById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductionLot>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductionLot) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductionLot))); } /// <summary> /// Get a productionLot by id Returns the productionLot identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="productionLotId">Id of the productionLot to be returned.</param> /// <returns>Task of ProductionLot</returns> public async System.Threading.Tasks.Task<ProductionLot> GetProductionLotByIdAsync (int? productionLotId) { ApiResponse<ProductionLot> localVarResponse = await GetProductionLotByIdAsyncWithHttpInfo(productionLotId); return localVarResponse.Data; } /// <summary> /// Get a productionLot by id Returns the productionLot identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="productionLotId">Id of the productionLot to be returned.</param> /// <returns>Task of ApiResponse (ProductionLot)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProductionLot>> GetProductionLotByIdAsyncWithHttpInfo (int? productionLotId) { // verify the required parameter 'productionLotId' is set if (productionLotId == null) throw new ApiException(400, "Missing required parameter 'productionLotId' when calling ProductionLotApi->GetProductionLotById"); var localVarPath = "/v1.0/productionLot/{productionLotId}"; 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[] { }; 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 (productionLotId != null) localVarPathParams.Add("productionLotId", Configuration.ApiClient.ParameterToString(productionLotId)); // path parameter // 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.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetProductionLotById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductionLot>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductionLot) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductionLot))); } } }
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 Tests.ApiHarness.Areas.HelpPage.ModelDescriptions; using Tests.ApiHarness.Areas.HelpPage.Models; namespace Tests.ApiHarness.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <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; } /// <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> /// 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> /// 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> /// 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 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> /// 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> /// 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); } 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 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 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 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 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 bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } 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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { private sealed class CurlResponseMessage : HttpResponseMessage { internal uint _headerBytesReceived; internal CurlResponseMessage(EasyRequest easy) { Debug.Assert(easy != null, "Expected non-null EasyRequest"); RequestMessage = easy._requestMessage; ResponseStream = new CurlResponseStream(easy); Content = new NoWriteNoSeekStreamContent(ResponseStream); // On Windows, we pass the equivalent of the easy._cancellationToken // in to StreamContent's ctor. This in turn passes that token through // to ReadAsync operations on the stream response stream when HttpClient // reads from the response stream to buffer it with ResponseContentRead. // We don't need to do that here in the Unix implementation as, until the // SendAsync task completes, the handler will have registered with the // CancellationToken with an action that will cancel all work related to // the easy handle if cancellation occurs, and that includes canceling any // pending reads on the response stream. It wouldn't hurt anything functionally // to still pass easy._cancellationToken here, but it will increase costs // a bit, as each read will then need to allocate a larger state object as // well as register with and unregister from the cancellation token. } internal CurlResponseStream ResponseStream { get; } } /// <summary> /// Provides a response stream that allows libcurl to transfer data asynchronously to a reader. /// When writing data to the response stream, either all or none of the data will be transferred, /// and if none, libcurl will pause the connection until a reader is waiting to consume the data. /// Readers consume the data via ReadAsync, which registers a read state with the stream, to be /// filled in by a pending write. Read is just a thin wrapper around ReadAsync, since the underlying /// mechanism must be asynchronous to prevent blocking libcurl's processing. /// </summary> private sealed class CurlResponseStream : Stream { /// <summary> /// A sentinel object used in the <see cref="_completed"/> field to indicate that /// the stream completed successfully. /// </summary> private static readonly Exception s_completionSentinel = new Exception(nameof(s_completionSentinel)); /// <summary>A object used to synchronize all access to state on this response stream.</summary> private readonly object _lockObject = new object(); /// <summary>The associated EasyRequest.</summary> private readonly EasyRequest _easy; /// <summary>Stores whether Dispose has been called on the stream.</summary> private bool _disposed = false; /// <summary> /// Null if the Stream has not been completed, non-null if it has been completed. /// If non-null, it'll either be the <see cref="s_completionSentinel"/> object, meaning the stream completed /// successfully, or it'll be an Exception object representing the error that caused completion. /// That error will be transferred to any subsequent read requests. /// </summary> private Exception _completed; /// <summary> /// The state associated with a pending read request. When a reader requests data, it puts /// its state here for the writer to fill in when data is available. /// </summary> private ReadState _pendingReadRequest; /// <summary> /// When data is provided by libcurl, it must be consumed all or nothing: either all of the data is consumed, or /// we must pause the connection. Since a read could need to be satisfied with only some of the data provided, /// we store the rest here until all reads can consume it. If a subsequent write callback comes in to provide /// more data, the connection will then be paused until this buffer is entirely consumed. /// </summary> private byte[] _remainingData; /// <summary> /// The offset into <see cref="_remainingData"/> from which the next read should occur. /// </summary> private int _remainingDataOffset; /// <summary> /// The remaining number of bytes in <see cref="_remainingData"/> available to be read. /// </summary> private int _remainingDataCount; internal CurlResponseStream(EasyRequest easy) { Debug.Assert(easy != null, "Expected non-null associated EasyRequest"); _easy = easy; } public override bool CanRead => !_disposed; public override bool CanWrite => false; public override bool CanSeek => false; public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } public override void Flush() { // Nothing to do. } /// <summary> /// Writes the <paramref name="length"/> bytes starting at <paramref name="pointer"/> to the stream. /// </summary> /// <returns> /// <paramref name="length"/> if all of the data was written, or /// <see cref="Interop.libcurl.CURL_WRITEFUNC_PAUSE"/> if the data wasn't copied and the connection /// should be paused until a reader is available. /// </returns> internal ulong TransferDataToResponseStream(IntPtr pointer, long length) { Debug.Assert(pointer != IntPtr.Zero, "Expected a non-null pointer"); Debug.Assert(length >= 0, "Expected a non-negative length"); EventSourceTrace("Length: {0}", length); CheckDisposed(); // If there's no data to write, consider everything transferred. if (length == 0) { return 0; } lock (_lockObject) { VerifyInvariants(); // If there's existing data in the remaining data buffer, or if there's no pending read request, // we need to pause until the existing data is consumed or until there's a waiting read. if (_remainingDataCount > 0) { EventSourceTrace("Pausing transfer to response stream. Remaining bytes: {0}", _remainingDataCount); return Interop.Http.CURL_WRITEFUNC_PAUSE; } else if (_pendingReadRequest == null) { EventSourceTrace("Pausing transfer to response stream. No pending read request"); return Interop.Http.CURL_WRITEFUNC_PAUSE; } // There's no data in the buffer and there is a pending read request. // Transfer as much data as we can to the read request, completing it. int numBytesForTask = (int)Math.Min(length, _pendingReadRequest._buffer.Length); Debug.Assert(numBytesForTask > 0, "We must be copying a positive amount."); unsafe { new Span<byte>((byte*)pointer, numBytesForTask).CopyTo(_pendingReadRequest._buffer.Span); } EventSourceTrace("Completing pending read with {0} bytes", numBytesForTask); _pendingReadRequest.SetResult(numBytesForTask); ClearPendingReadRequest(); // If there's any data left, transfer it to our remaining buffer. libcurl does not support // partial transfers of data, so since we just took some of it to satisfy the read request // we must take the rest of it. (If libcurl then comes back to us subsequently with more data // before this buffered data has been consumed, at that point we won't consume any of the // subsequent offering and will ask libcurl to pause.) if (numBytesForTask < length) { IntPtr remainingPointer = pointer + numBytesForTask; _remainingDataCount = checked((int)(length - numBytesForTask)); _remainingDataOffset = 0; // Make sure our remaining data buffer exists and is big enough to hold the data if (_remainingData == null) { _remainingData = new byte[_remainingDataCount]; } else if (_remainingData.Length < _remainingDataCount) { _remainingData = new byte[Math.Max(_remainingData.Length * 2, _remainingDataCount)]; } // Copy the remaining data to the buffer EventSourceTrace("Storing {0} bytes for later", _remainingDataCount); Marshal.Copy(remainingPointer, _remainingData, 0, _remainingDataCount); } // All of the data from libcurl was consumed. return (ulong)length; } } public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset > buffer.Length - count) throw new ArgumentException(SR.net_http_buffer_insufficient_length, nameof(buffer)); return ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default) { CheckDisposed(); EventSourceTrace("Buffer: {0}", destination.Length); // Check for cancellation if (cancellationToken.IsCancellationRequested) { EventSourceTrace("Canceled"); return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)); } lock (_lockObject) { VerifyInvariants(); // If there's currently a pending read, fail this read, as we don't support concurrent reads. if (_pendingReadRequest != null) { EventSourceTrace("Failing due to existing pending read; concurrent reads not supported."); return new ValueTask<int>(Task.FromException<int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads))); } // If the stream was already completed with failure, complete the read as a failure. if (_completed != null && _completed != s_completionSentinel) { EventSourceTrace("Failing read with error: {0}", _completed); OperationCanceledException oce = _completed as OperationCanceledException; return new ValueTask<int>((oce != null && oce.CancellationToken.IsCancellationRequested) ? Task.FromCanceled<int>(oce.CancellationToken) : Task.FromException<int>(MapToReadWriteIOException(_completed, isRead: true))); } // Quick check for if no data was actually requested. We do this after the check // for errors so that we can still fail the read and transfer the exception if we should. if (destination.Length == 0) { return new ValueTask<int>(0); } // If there's any data left over from a previous call, grab as much as we can. if (_remainingDataCount > 0) { int bytesToCopy = Math.Min(destination.Length, _remainingDataCount); new Span<byte>(_remainingData, _remainingDataOffset, bytesToCopy).CopyTo(destination.Span); _remainingDataOffset += bytesToCopy; _remainingDataCount -= bytesToCopy; Debug.Assert(_remainingDataCount >= 0, "The remaining count should never go negative"); Debug.Assert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size"); EventSourceTrace("Read {0} bytes", bytesToCopy); return new ValueTask<int>(bytesToCopy); } // If the stream has already been completed, complete the read immediately. if (_completed == s_completionSentinel) { EventSourceTrace("Stream already completed"); return new ValueTask<int>(0); } // Finally, the stream is still alive, and we want to read some data, but there's no data // in the buffer so we need to register ourself to get the next write. if (cancellationToken.CanBeCanceled) { // If the cancellation token is cancelable, then we need to register for cancellation. // We create a special CancelableReadState that carries with it additional info: // the cancellation token and the registration with that token. When cancellation // is requested, we schedule a work item that tries to remove the read state // from being pending, canceling it in the process. This needs to happen under the // lock, which is why we schedule the operation to run asynchronously: if it ran // synchronously, it could deadlock due to code on another thread holding the lock // and calling Dispose on the registration concurrently with the call to Cancel // the cancellation token. Dispose on the registration won't return until the action // associated with the registration has completed, but if that action is currently // executing and is blocked on the lock that's held while calling Dispose... deadlock. var crs = new CancelableReadState(destination, this); crs._registration = cancellationToken.Register(s1 => { ((CancelableReadState)s1)._stream.EventSourceTrace("Cancellation invoked. Queueing work item to cancel read state"); Task.Factory.StartNew(s2 => { var crsRef = (CancelableReadState)s2; lock (crsRef._stream._lockObject) { Debug.Assert(crsRef._registration.Token.IsCancellationRequested, "We should only be here if cancellation was requested."); if (crsRef._stream._pendingReadRequest == crsRef) { crsRef._stream.EventSourceTrace("Canceling"); crsRef.TrySetCanceled(crsRef._registration.Token); crsRef._stream.ClearPendingReadRequest(); } } }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); }, crs); _pendingReadRequest = crs; } else { // The token isn't cancelable. Just create a normal read state. _pendingReadRequest = new ReadState(destination); } _easy._associatedMultiAgent.RequestUnpause(_easy); _easy._selfStrongToWeakReference.MakeStrong(); // convert from a weak to a strong ref to keep the easy alive during the read return new ValueTask<int>(_pendingReadRequest.Task); } } /// <summary>Notifies the stream that no more data will be written.</summary> internal void SignalComplete(Exception error = null, bool forceCancel = false) { lock (_lockObject) { VerifyInvariants(); // If we already completed, nothing more to do if (_completed != null) { EventSourceTrace("Already completed"); return; } // Mark ourselves as being completed EventSourceTrace("Marking as complete"); _completed = error ?? s_completionSentinel; // If the request wasn't already completed, and if requested, send a cancellation // request to ensure that the connection gets cleaned up. This is only necessary // to do if this method is being called for a reason other than the request/response // completing naturally, e.g. if the response stream is being disposed of before // all of the response has been downloaded. if (forceCancel) { EventSourceTrace("Completing the response stream prematurely."); _easy._associatedMultiAgent.RequestCancel(_easy); } // If there's a pending read request, complete it, either with 0 bytes for success // or with the exception/CancellationToken for failure. ReadState pendingRead = _pendingReadRequest; if (pendingRead != null) { if (_completed == s_completionSentinel) { EventSourceTrace("Completing pending read with 0 bytes"); pendingRead.TrySetResult(0); } else { EventSourceTrace("Failing pending read task with error: {0}", _completed); OperationCanceledException oce = _completed as OperationCanceledException; if (oce != null) { pendingRead.TrySetCanceled(oce.CancellationToken); } else { pendingRead.TrySetException(MapToReadWriteIOException(_completed, isRead: true)); } } ClearPendingReadRequest(); } } } /// <summary> /// Clears a pending read request, making sure any cancellation registration is unregistered and /// ensuring that the EasyRequest has dropped its strong reference to itself, which should only /// exist while an active async operation is going. /// </summary> private void ClearPendingReadRequest() { Debug.Assert(Monitor.IsEntered(_lockObject), "Lock object must be held to manipulate _pendingReadRequest"); Debug.Assert(_pendingReadRequest != null, "Should only be clearing the pending read request if there is one"); Debug.Assert(_pendingReadRequest.Task.IsCompleted, "The pending request should have been completed"); (_pendingReadRequest as CancelableReadState)?._registration.Dispose(); _pendingReadRequest = null; // The async operation has completed. We no longer want to be holding a strong reference. _easy._selfStrongToWeakReference.MakeWeak(); } ~CurlResponseStream() { Dispose(disposing: false); } protected override void Dispose(bool disposing) { // disposing is ignored. We need to SignalComplete whether this is due to Dispose // or due to finalization, so that we don't leave Tasks uncompleted, don't leave // connections paused, etc. if (!_disposed) { EventSourceTrace("Disposing response stream"); _disposed = true; SignalComplete(forceCancel: true); } base.Dispose(disposing); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, agent: null, easy: _easy, memberName: memberName); } private void EventSourceTrace<TArg0, TArg1, TArg2>(string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, arg1, arg2, agent: null, easy: _easy, memberName: memberName); } private void EventSourceTrace(string message, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(message, agent: null, easy: _easy, memberName: memberName); } /// <summary>Verifies various invariants that must be true about our state.</summary> [Conditional("DEBUG")] private void VerifyInvariants() { Debug.Assert(Monitor.IsEntered(_lockObject), "Can only verify invariants while holding the lock"); Debug.Assert(_remainingDataCount >= 0, "Remaining data count should never be negative."); Debug.Assert(_remainingDataCount == 0 || _remainingData != null, "If there's remaining data, there must be a buffer to store it."); Debug.Assert(_remainingData == null || _remainingDataCount <= _remainingData.Length, "The buffer must be large enough for the data length."); Debug.Assert(_remainingData == null || _remainingDataOffset <= _remainingData.Length, "The offset must not walk off the buffer."); Debug.Assert(!((_remainingDataCount > 0) && (_pendingReadRequest != null)), "We can't have both remaining data and a pending request."); Debug.Assert(!((_completed != null) && (_pendingReadRequest != null)), "We can't both be completed and have a pending request."); Debug.Assert(_pendingReadRequest == null || !_pendingReadRequest.Task.IsCompleted, "A pending read request must not have been completed yet."); } /// <summary>State associated with a pending read request.</summary> private class ReadState : TaskCompletionSource<int> { internal readonly Memory<byte> _buffer; internal ReadState(Memory<byte> buffer) : base(TaskCreationOptions.RunContinuationsAsynchronously) { _buffer = buffer; } } /// <summary>State associated with a pending read request that's cancelable.</summary> private sealed class CancelableReadState : ReadState { internal readonly CurlResponseStream _stream; internal CancellationTokenRegistration _registration; internal CancelableReadState(Memory<byte> buffer, CurlResponseStream responseStream) : base(buffer) { _stream = responseStream; } } } } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text; namespace AdoNetTest.BIN.BusinessObjects { /// <summary> /// Encapsulates product information with related supplier and product category /// </summary> public class Product : BusinessObject { public long ProductId { get; set; } public string Name { get; set; } public string Description { get; set; } private Category category; public Category Category { get { if (category == null) category = new Category(); return category; } set { category = value; } } private Supplier supplier; public Supplier Supplier { get { if (supplier == null) supplier = new Supplier(); return supplier; } set { supplier = value; } } public float UnitCost { get; set; } public float RetailPrice { get; set; } public int UnitsInStock { get; set; } public int ReorderQuantity { get; set; } public DateTime LastOrderDate { get; set; } public DateTime NextOrderDate { get; set; } public Product() { ProductId = 0; Name = String.Empty; Description = String.Empty; Category = new Category(); Supplier = new Supplier(); UnitCost = 0; RetailPrice = 0; UnitsInStock = 0; ReorderQuantity = 0; LastOrderDate = DateTime.Today; NextOrderDate = DateTime.Today; } public Product(long productId) : this() { ProductId = productId; } public Product(long productId, string name, string description, long categoryId, long supplierId, float unitCost, float retailPrice, int unitsInStock, int reorderQuantity, DateTime lastOrderDate, DateTime nextOrderDate) : this() { ProductId = productId; Name = name; Description = description; Category.CategoryId = categoryId; Supplier.SupplierId = supplierId; UnitCost = unitCost; RetailPrice = retailPrice; UnitsInStock = unitsInStock; ReorderQuantity = reorderQuantity; LastOrderDate = lastOrderDate; NextOrderDate = nextOrderDate; } public Product(DataRow row) : this() { ProductId = long.Parse(row[0].ToString()); Name = row[1].ToString(); Description = row[2].ToString(); Category.CategoryId = long.Parse(row[3].ToString()); Supplier.SupplierId = long.Parse(row[4].ToString()); UnitCost = float.Parse(row[5].ToString()); RetailPrice = float.Parse(row[6].ToString()); UnitsInStock = int.Parse(row[7].ToString()); ReorderQuantity = int.Parse(row[8].ToString()); LastOrderDate = DateTime.Parse(row[9].ToString()); NextOrderDate = DateTime.Parse(row[10].ToString()); } public override bool Equals(object obj) { if (!(obj is Product)) return false; Product product = (Product)obj; return (this.ProductId == product.ProductId && this.Name == product.Name && this.Description == product.Description && this.Category.CategoryId == product.Category.CategoryId && this.Supplier.SupplierId == product.Supplier.SupplierId && this.UnitCost == product.UnitCost && this.RetailPrice == product.RetailPrice && this.UnitsInStock == product.UnitsInStock && this.ReorderQuantity == product.ReorderQuantity && this.LastOrderDate == product.LastOrderDate && this.NextOrderDate == product.NextOrderDate); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return String.Format( "{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}\n", this.ProductId, this.Name, this.Description, this.Category.CategoryId, this.Supplier.SupplierId, this.UnitCost, this.RetailPrice, this.UnitsInStock, this.ReorderQuantity, this.LastOrderDate, this.NextOrderDate); } } }
using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Threading; namespace System.Net.Mime { internal class MimeMultiPart:MimeBasePart { Collection<MimeBasePart> parts; static int boundary; AsyncCallback mimePartSentCallback; private bool allowUnicode; internal MimeMultiPart(MimeMultiPartType type) { MimeMultiPartType = type; } internal MimeMultiPartType MimeMultiPartType { set { if (value > MimeMultiPartType.Related || value < MimeMultiPartType.Mixed) { throw new NotSupportedException(value.ToString()); } SetType(value); } } void SetType(MimeMultiPartType type) { ContentType.MediaType = "multipart" + "/" + type.ToString().ToLower(CultureInfo.InvariantCulture); ContentType.Boundary = GetNextBoundary(); } internal Collection<MimeBasePart> Parts { get{ if (parts == null) { parts = new Collection<MimeBasePart>(); } return parts; } } internal void Complete(IAsyncResult result, Exception e){ //if we already completed and we got called again, //it mean's that there was an exception in the callback and we //should just rethrow it. MimePartContext context = (MimePartContext)result.AsyncState; if (context.completed) { throw e; } try{ context.outputStream.Close(); } catch(Exception ex){ if (e == null) { e = ex; } } context.completed = true; context.result.InvokeCallback(e); } internal void MimeWriterCloseCallback(IAsyncResult result) { if (result.CompletedSynchronously ) { return; } ((MimePartContext)result.AsyncState).completedSynchronously = false; try{ MimeWriterCloseCallbackHandler(result); } catch (Exception e) { Complete(result,e); } } void MimeWriterCloseCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState; ((MimeWriter)context.writer).EndClose(result); Complete(result,null); } internal void MimePartSentCallback(IAsyncResult result) { if (result.CompletedSynchronously ) { return; } ((MimePartContext)result.AsyncState).completedSynchronously = false; try{ MimePartSentCallbackHandler(result); } catch (Exception e) { Complete(result,e); } } void MimePartSentCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState; MimeBasePart part = (MimeBasePart)context.partsEnumerator.Current; part.EndSend(result); if (context.partsEnumerator.MoveNext()) { part = (MimeBasePart)context.partsEnumerator.Current; IAsyncResult sendResult = part.BeginSend(context.writer, mimePartSentCallback, allowUnicode, context); if (sendResult.CompletedSynchronously) { MimePartSentCallbackHandler(sendResult); } return; } else { IAsyncResult closeResult = ((MimeWriter)context.writer).BeginClose(new AsyncCallback(MimeWriterCloseCallback), context); if (closeResult.CompletedSynchronously) { MimeWriterCloseCallbackHandler(closeResult); } } } internal void ContentStreamCallback(IAsyncResult result) { if (result.CompletedSynchronously ) { return; } ((MimePartContext)result.AsyncState).completedSynchronously = false; try{ ContentStreamCallbackHandler(result); } catch (Exception e) { Complete(result,e); } } void ContentStreamCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState; context.outputStream = context.writer.EndGetContentStream(result); context.writer = new MimeWriter(context.outputStream, ContentType.Boundary); if (context.partsEnumerator.MoveNext()) { MimeBasePart part = (MimeBasePart)context.partsEnumerator.Current; mimePartSentCallback = new AsyncCallback(MimePartSentCallback); IAsyncResult sendResult = part.BeginSend(context.writer, mimePartSentCallback, allowUnicode, context); if (sendResult.CompletedSynchronously) { MimePartSentCallbackHandler(sendResult); } return; } else { IAsyncResult closeResult = ((MimeWriter)context.writer).BeginClose(new AsyncCallback(MimeWriterCloseCallback),context); if (closeResult.CompletedSynchronously) { MimeWriterCloseCallbackHandler(closeResult); } } } internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode, object state) { this.allowUnicode = allowUnicode; PrepareHeaders(allowUnicode); writer.WriteHeaders(Headers, allowUnicode); MimePartAsyncResult result = new MimePartAsyncResult(this, state, callback); MimePartContext context = new MimePartContext(writer, result, Parts.GetEnumerator()); IAsyncResult contentResult = writer.BeginGetContentStream(new AsyncCallback(ContentStreamCallback), context); if (contentResult.CompletedSynchronously) { ContentStreamCallbackHandler(contentResult); } return result; } internal class MimePartContext { internal MimePartContext(BaseWriter writer, LazyAsyncResult result, IEnumerator<MimeBasePart> partsEnumerator) { this.writer = writer; this.result = result; this.partsEnumerator = partsEnumerator; } internal IEnumerator<MimeBasePart> partsEnumerator; internal Stream outputStream; internal LazyAsyncResult result; internal BaseWriter writer; internal bool completed; internal bool completedSynchronously = true; } internal override void Send(BaseWriter writer, bool allowUnicode) { PrepareHeaders(allowUnicode); writer.WriteHeaders(Headers, allowUnicode); Stream outputStream = writer.GetContentStream(); MimeWriter mimeWriter = new MimeWriter(outputStream, ContentType.Boundary); foreach (MimeBasePart part in Parts) { part.Send(mimeWriter, allowUnicode); } mimeWriter.Close(); outputStream.Close(); } internal string GetNextBoundary() { int b = Interlocked.Increment(ref boundary) - 1; string boundaryString = "--boundary_" + b.ToString(CultureInfo.InvariantCulture)+"_"+Guid.NewGuid().ToString(null, CultureInfo.InvariantCulture); return boundaryString; } } }
// 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] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct UInt16 : IComparable, IConvertible, IFormattable, IComparable<ushort>, IEquatable<ushort>, ISpanFormattable { private readonly ushort m_value; // Do not rename (binary serialization) public const ushort MaxValue = (ushort)0xFFFF; public const ushort MinValue = 0; // 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 UInt16, this method throws an ArgumentException. // public int CompareTo(object? value) { if (value == null) { return 1; } if (value is ushort) { return ((int)m_value - (int)(((ushort)value).m_value)); } throw new ArgumentException(SR.Arg_MustBeUInt16); } public int CompareTo(ushort value) { return ((int)m_value - (int)value); } public override bool Equals(object? obj) { if (!(obj is ushort)) { return false; } return m_value == ((ushort)obj).m_value; } [NonVersionable] public bool Equals(ushort obj) { return m_value == obj; } // Returns a HashCode for the UInt16 public override int GetHashCode() { return (int)m_value; } // Converts the current value to a String in base-10 with no extra padding. public override string ToString() { return Number.FormatUInt32(m_value, null, null); } public string ToString(IFormatProvider? provider) { return Number.FormatUInt32(m_value, null, provider); } public string ToString(string? format) { return Number.FormatUInt32(m_value, format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatUInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) { return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten); } [CLSCompliant(false)] public static ushort Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static ushort Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static ushort Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static ushort 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)); } [CLSCompliant(false)] public static ushort Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static ushort Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { Number.ParsingStatus status = Number.TryParseUInt32(s, style, info, out uint i); if (status != Number.ParsingStatus.OK) { Number.ThrowOverflowOrFormatException(status, TypeCode.UInt16); } if (i > MaxValue) Number.ThrowOverflowException(TypeCode.UInt16); return (ushort)i; } [CLSCompliant(false)] public static bool TryParse(string? s, out ushort result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, out ushort result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out ushort result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out ushort 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 ushort result) { if (Number.TryParseUInt32(s, style, info, out uint i) != Number.ParsingStatus.OK || i > MaxValue) { result = 0; return false; } result = (ushort)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt16; } 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 Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider? provider) { return 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, "UInt16", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.ObjectModel; using Dbg = System.Management.Automation.Diagnostics; //using System.Runtime.Serialization; //using System.ComponentModel; //using System.Runtime.InteropServices; //using System.Globalization; //using System.Management.Automation; //using System.Reflection; namespace System.Management.Automation.Host { /// <summary> /// Provides a description of a field for use by <see cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/>. /// <!--Used by the Msh engine to describe cmdlet parameters.--> /// </summary> /// <remarks> /// It is permitted to subclass <see cref="System.Management.Automation.Host.FieldDescription"/> /// but there is no established scenario for doing this, nor has it been tested. /// </remarks> public class FieldDescription { /// <summary> /// Initializes a new instance of FieldDescription and defines the Name value. /// </summary> /// <param name="name"> /// The name to identify this field description /// </param> /// <exception cref="System.Management.Automation.PSArgumentException"> /// <paramref name="name"/> is null or empty. /// </exception> public FieldDescription(string name) { // the only required parameter is the name. if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name", DescriptionsStrings.NullOrEmptyErrorTemplate, "name"); } this.name = name; } /// <summary> /// Gets the name of the field. /// </summary> public string Name { get { return name; } } /// <summary> /// Sets the ParameterTypeName, ParameterTypeFullName, and ParameterAssemblyFullName as a single operation. /// </summary> /// <param name="parameterType"> /// The Type that sets the properties. /// </param> /// <exception cref="System.Management.Automation.PSArgumentNullException"> /// If <paramref name="parameterType"/> is null. /// </exception> public void SetParameterType(System.Type parameterType) { if (parameterType == null) { throw PSTraceSource.NewArgumentNullException("parameterType"); } SetParameterTypeName(parameterType.Name); SetParameterTypeFullName(parameterType.FullName); SetParameterAssemblyFullName(parameterType.AssemblyQualifiedName); } /// <summary> /// Gets the short name of the parameter's type. /// </summary> /// <value> /// The type name of the parameter /// </value> /// <remarks> /// If not already set by a call to <see cref="System.Management.Automation.Host.FieldDescription.SetParameterType"/>, /// <see cref="System.String"/> will be used as the type. /// <!--The value of ParameterTypeName is the string value returned. /// by System.Type.Name.--> /// </remarks> public string ParameterTypeName { get { if (string.IsNullOrEmpty(parameterTypeName)) { // the default if the type name is not specified is 'string' SetParameterType(typeof(string)); } return parameterTypeName; } } /// <summary> /// Gets the full string name of the parameter's type. /// </summary> /// <remarks> /// If not already set by a call to <see cref="System.Management.Automation.Host.FieldDescription.SetParameterType"/>, /// <see cref="System.String"/> will be used as the type. /// <!--The value of ParameterTypeName is the string value returned. /// by System.Type.Name.--> /// </remarks> public string ParameterTypeFullName { get { if (string.IsNullOrEmpty(parameterTypeFullName)) { // the default if the type name is not specified is 'string' SetParameterType(typeof(string)); } return parameterTypeFullName; } } /// <summary> /// Gets the full name of the assembly containing the type identified by ParameterTypeFullName or ParameterTypeName. /// </summary> /// <remarks> /// If the assembly is not currently loaded in the hosting application's AppDomain, the hosting application needs /// to load the containing assembly to access the type information. AssemblyName is used for this purpose. /// /// If not already set by a call to <see cref="System.Management.Automation.Host.FieldDescription.SetParameterType"/>, /// <see cref="System.String"/> will be used as the type. /// </remarks> public string ParameterAssemblyFullName { get { if (string.IsNullOrEmpty(parameterAssemblyFullName)) { // the default if the type name is not specified is 'string' SetParameterType(typeof(string)); } return parameterAssemblyFullName; } } /// <summary> /// A short, human-presentable message to describe and identify the field. If supplied, a typical implementation of /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> will use this value instead of /// the field name to identify the field to the user. /// </summary> /// <exception cref="System.Management.Automation.PSArgumentNullException"> /// set to null. /// </exception> /// <remarks> /// Note that the special character &amp; (ampersand) may be embedded in the label string to identify the next /// character in the label as a "hot key" (aka "keyboard accelerator") that the /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> implementation may use /// to allow the user to quickly set input focus to this field. The implementation of /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> is responsible for parsing /// the label string for this special character and rendering it accordingly. /// /// For example, a field named "SSN" might have "&amp;Social Security Number" as it's label. /// /// If no label is set, then the empty string is returned. /// </remarks> public string Label { get { Dbg.Assert(label != null, "label should not be null"); return label; } set { if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } label = value; } } /// <summary> /// Gets and sets the help message for this field. /// </summary> /// <exception cref="System.Management.Automation.PSArgumentNullException"> /// Set to null. /// </exception> /// <remarks> /// This should be a few sentences to describe the field, suitable for presentation as a tool tip. /// Avoid placing including formatting characters such as newline and tab. /// </remarks> public string HelpMessage { get { Dbg.Assert(helpMessage != null, "helpMessage should not be null"); return helpMessage; } set { if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } helpMessage = value; } } /// <summary> /// Gets and sets whether a value must be supplied for this field. /// </summary> public bool IsMandatory { get { return isMandatory; } set { isMandatory = value; } } /// <summary> /// Gets and sets the default value, if any, for the implementation of <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> /// to pre-populate its UI with. This is a PSObject instance so that the value can be serialized, converted, /// manipulated like any pipeline object. /// </summary> ///<remarks> /// It is up to the implementer of <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> to decide if it /// can make use of the object in its presentation of the fields prompt. /// ///</remarks> public PSObject DefaultValue { get { return defaultValue; } set { // null is allowed. defaultValue = value; } } /// <summary> /// Gets the Attribute classes that apply to the field. In the case that <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> /// is being called from the MSH engine, this will contain the set of prompting attributes that are attached to a /// cmdlet parameter declaration. /// </summary> public Collection<Attribute> Attributes { get { return metadata ?? (metadata = new Collection<Attribute>()); } } /// <summary> /// For use by remoting serialization. /// </summary> /// <param name="nameOfType"></param> /// <exception cref="System.Management.Automation.PSArgumentException"> /// If <paramref name="nameOfType"/> is null. /// </exception> internal void SetParameterTypeName(string nameOfType) { if (string.IsNullOrEmpty(nameOfType)) { throw PSTraceSource.NewArgumentException("nameOfType", DescriptionsStrings.NullOrEmptyErrorTemplate, "nameOfType"); } parameterTypeName = nameOfType; } /// <summary> /// For use by remoting serialization. /// </summary> /// <param name="fullNameOfType"></param> /// <exception cref="System.Management.Automation.PSArgumentException"> /// If <paramref name="fullNameOfType"/> is null. /// </exception> internal void SetParameterTypeFullName(string fullNameOfType) { if (string.IsNullOrEmpty(fullNameOfType)) { throw PSTraceSource.NewArgumentException("fullNameOfType", DescriptionsStrings.NullOrEmptyErrorTemplate, "fullNameOfType"); } parameterTypeFullName = fullNameOfType; } /// <summary> /// For use by remoting serialization. /// </summary> /// <param name="fullNameOfAssembly"></param> /// <exception cref="System.Management.Automation.PSArgumentException"> /// If <paramref name="fullNameOfAssembly"/> is null. /// </exception> internal void SetParameterAssemblyFullName(string fullNameOfAssembly) { if (string.IsNullOrEmpty(fullNameOfAssembly)) { throw PSTraceSource.NewArgumentException("fullNameOfAssembly", DescriptionsStrings.NullOrEmptyErrorTemplate, "fullNameOfAssembly"); } parameterAssemblyFullName = fullNameOfAssembly; } /// <summary> /// Indicates if this field description was /// modified by the remoting protocol layer. /// </summary> /// <remarks>Used by the console host to /// determine if this field description was /// modified by the remoting protocol layer /// and take appropriate actions</remarks> internal bool ModifiedByRemotingProtocol { get { return modifiedByRemotingProtocol; } set { modifiedByRemotingProtocol = value; } } /// <summary> /// Indicates if this field description /// is coming from a remote host. /// </summary> /// <remarks>Used by the console host to /// not cast strings to an arbitrary type, /// but let the server-side do the type conversion /// </remarks> internal bool IsFromRemoteHost { get { return isFromRemoteHost; } set { isFromRemoteHost = value; } } #region Helper #endregion Helper #region DO NOT REMOVE OR RENAME THESE FIELDS - it will break remoting compatibility with Windows PowerShell private readonly string name = null; private string label = string.Empty; private string parameterTypeName = null; private string parameterTypeFullName = null; private string parameterAssemblyFullName = null; private string helpMessage = string.Empty; private bool isMandatory = true; private PSObject defaultValue = null; private Collection<Attribute> metadata = new Collection<Attribute>(); private bool modifiedByRemotingProtocol = false; private bool isFromRemoteHost = false; #endregion } }
using System; using System.Globalization; using System.Linq; using System.Text; using System.Collections.Generic; using GroupDocs.Annotation.Domain; namespace GroupDocs.Demo.Annotation.Webforms.BusinessLogic { /// <summary> /// Class FileDataJsonSerializer. /// </summary> public class FileDataJsonSerializer { /// <summary> /// The _file data /// </summary> private readonly List<PageData> _fileData; /// <summary> /// The _default culture /// </summary> private readonly CultureInfo _defaultCulture = CultureInfo.InvariantCulture; /// <summary> /// Initializes a new instance of the <see cref="FileDataJsonSerializer"/> class. /// </summary> /// <param name="fileData">The file data.</param> public FileDataJsonSerializer(List<PageData> fileData) { _fileData = fileData; } /// <summary> /// Serializes this instance. /// </summary> /// <returns>System.String.</returns> public string Serialize(bool isDefault) { var isCellsFileData = _fileData.Any(_ => !string.IsNullOrEmpty(_.Name)); if (isCellsFileData && !isDefault) return SerializeCells(); return SerializeDefault(); } /// <summary> /// Serializes the default. /// </summary> /// <returns>System.String.</returns> private string SerializeDefault() { StringBuilder json = new StringBuilder(); json.Append(string.Format("{{\"maxPageHeight\":{0},\"widthForMaxHeight\":{1}", _fileData[0].Height, _fileData[0].Width)); json.Append(",\"pages\":["); int pageCount = _fileData.Count; for (int i = 0; i < pageCount; i++) { PageData pageData = _fileData[i]; bool needSeparator = pageData.Number != 1; if (needSeparator) json.Append(","); AppendPage(pageData, json); bool includeRows = pageData.Rows.Count > 0; if (includeRows) { json.Append(",\"rows\":["); for (int j = 0; j < pageData.Rows.Count; j++) { bool appendRowSeaparator = j != 0; if (appendRowSeaparator) json.Append(","); AppendRow(pageData.Rows[j], json); } json.Append("]"); // rows } json.Append("}"); // page } json.Append("]"); // pages json.Append("}"); // document return json.ToString(); } /// <summary> /// Serializes cells. /// </summary> /// <returns>System.String.</returns> private string SerializeCells() { StringBuilder json = new StringBuilder(); json.Append("{\"sheets\":["); int pageCount = _fileData.Count; for (int i = 0; i < pageCount; i++) { PageData pageData = _fileData[i]; bool needSeparator = pageData.Number != 1; if (needSeparator) json.Append(","); json.Append(string.Format("{{\"name\":\"{0}\"}}", pageData.Name)); } json.Append("]"); // pages json.Append("}"); // document return json.ToString(); } /// <summary> /// Appends the page. /// </summary> /// <param name="pageData">The page data.</param> /// <param name="json">The json.</param> private void AppendPage(PageData pageData, StringBuilder json) { json.Append(string.Format("{{\"w\":{0},\"h\":{1},\"number\":{2}", pageData.Width.ToString(_defaultCulture), pageData.Height.ToString(_defaultCulture), pageData.Number.ToString(_defaultCulture))); } /// <summary> /// Appends the row. /// </summary> /// <param name="rowData">The row data.</param> /// <param name="json">The json.</param> private void AppendRow(RowData rowData, StringBuilder json) { string[] textCoordinates = new string[rowData.TextCoordinates.Count]; for (int i = 0; i < rowData.TextCoordinates.Count; i++) textCoordinates[i] = rowData.TextCoordinates[i].ToString(_defaultCulture); string[] characterCoordinates = new string[rowData.CharacterCoordinates.Count]; for (int i = 0; i < rowData.CharacterCoordinates.Count; i++) characterCoordinates[i] = rowData.CharacterCoordinates[i].ToString(_defaultCulture); json.Append(String.Format("{{\"l\":{0},\"t\":{1},\"w\":{2},\"h\":{3},\"c\":[{4}],\"s\":\"{5}\",\"ch\":[{6}]}}", rowData.LineLeft.ToString(_defaultCulture), rowData.LineTop.ToString(_defaultCulture), rowData.LineWidth.ToString(_defaultCulture), rowData.LineHeight.ToString(_defaultCulture), string.Join(",", textCoordinates), JsonEncode(rowData.Text), string.Join(",", characterCoordinates))); } /// <summary> /// Appends the content control. /// </summary> /// <param name="contentControl">The content control.</param> /// <param name="json">The json.</param> private void AppendContentControl(ContentControl contentControl, StringBuilder json) { json.Append(string.Format("{{\"title\":\"{0}\", \"startPage\":{1}, \"endPage\":{2}}}", JsonEncode(contentControl.Title), contentControl.StartPageNumber.ToString(_defaultCulture), contentControl.EndPageNumber.ToString(_defaultCulture))); } /// <summary> /// Jsons the encode. /// </summary> /// <param name="text">The text.</param> /// <returns>System.String.</returns> private string JsonEncode(string text) { if (string.IsNullOrEmpty(text)) return string.Empty; int i; int length = text.Length; StringBuilder stringBuilder = new StringBuilder(length + 4); for (i = 0; i < length; i += 1) { char c = text[i]; switch (c) { case '\\': case '"': case '/': stringBuilder.Append('\\'); stringBuilder.Append(c); break; case '\b': stringBuilder.Append("\\b"); break; case '\t': stringBuilder.Append("\\t"); break; case '\n': stringBuilder.Append("\\n"); break; case '\f': stringBuilder.Append("\\f"); break; case '\r': stringBuilder.Append("\\r"); break; default: if (c < ' ') { string t = "000" + Convert.ToByte(c).ToString("X"); stringBuilder.Append("\\u" + t.Substring(t.Length - 4)); } else { stringBuilder.Append(c); } break; } } return stringBuilder.ToString(); } } }
namespace Yahoo.Samples { partial class SampleBrowser { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.scMain = new System.Windows.Forms.SplitContainer(); this.scSamples = new System.Windows.Forms.SplitContainer(); this.lstSample = new System.Windows.Forms.ListBox(); this.bsSamples = new System.Windows.Forms.BindingSource(this.components); this.lblSamples = new System.Windows.Forms.Label(); this.tlpSampleInfoBorder = new System.Windows.Forms.TableLayoutPanel(); this.tlpSampleInfo = new System.Windows.Forms.TableLayoutPanel(); this.lblName = new System.Windows.Forms.Label(); this.lblDescription = new System.Windows.Forms.Label(); this.btnRun = new System.Windows.Forms.Button(); this.scSourceOutput = new System.Windows.Forms.SplitContainer(); this.rtbSource = new System.Windows.Forms.RichTextBox(); this.lblSource = new System.Windows.Forms.Label(); this.lblResult = new System.Windows.Forms.Label(); this.rtbOutput = new System.Windows.Forms.RichTextBox(); this.scMain.Panel1.SuspendLayout(); this.scMain.Panel2.SuspendLayout(); this.scMain.SuspendLayout(); this.scSamples.Panel1.SuspendLayout(); this.scSamples.Panel2.SuspendLayout(); this.scSamples.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.bsSamples)).BeginInit(); this.tlpSampleInfoBorder.SuspendLayout(); this.tlpSampleInfo.SuspendLayout(); this.scSourceOutput.Panel1.SuspendLayout(); this.scSourceOutput.Panel2.SuspendLayout(); this.scSourceOutput.SuspendLayout(); this.SuspendLayout(); // // scMain // this.scMain.Dock = System.Windows.Forms.DockStyle.Fill; this.scMain.ForeColor = System.Drawing.SystemColors.ControlText; this.scMain.Location = new System.Drawing.Point(0, 0); this.scMain.Margin = new System.Windows.Forms.Padding(0); this.scMain.Name = "scMain"; // // scMain.Panel1 // this.scMain.Panel1.Controls.Add(this.scSamples); this.scMain.Panel1.Controls.Add(this.btnRun); this.scMain.Panel1MinSize = 150; // // scMain.Panel2 // this.scMain.Panel2.Controls.Add(this.scSourceOutput); this.scMain.Size = new System.Drawing.Size(618, 458); this.scMain.SplitterDistance = 238; this.scMain.SplitterWidth = 5; this.scMain.TabIndex = 0; this.scMain.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.scMain_SplitterMoved); // // scSamples // this.scSamples.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.scSamples.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.scSamples.Location = new System.Drawing.Point(8, 0); this.scSamples.Margin = new System.Windows.Forms.Padding(0); this.scSamples.Name = "scSamples"; this.scSamples.Orientation = System.Windows.Forms.Orientation.Horizontal; // // scSamples.Panel1 // this.scSamples.Panel1.Controls.Add(this.lstSample); this.scSamples.Panel1.Controls.Add(this.lblSamples); // // scSamples.Panel2 // this.scSamples.Panel2.Controls.Add(this.tlpSampleInfoBorder); this.scSamples.Size = new System.Drawing.Size(230, 423); this.scSamples.SplitterDistance = 328; this.scSamples.TabIndex = 0; this.scSamples.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.scSamples_SplitterMoved); // // lstSample // this.lstSample.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstSample.DataSource = this.bsSamples; this.lstSample.DisplayMember = "Name"; this.lstSample.FormattingEnabled = true; this.lstSample.IntegralHeight = false; this.lstSample.Location = new System.Drawing.Point(0, 22); this.lstSample.Name = "lstSample"; this.lstSample.Size = new System.Drawing.Size(230, 306); this.lstSample.TabIndex = 1; // // bsSamples // this.bsSamples.DataSource = typeof(Yahoo.Samples.Common.ISample); this.bsSamples.CurrentChanged += new System.EventHandler(this.bsSamples_CurrentChanged); // // lblSamples // this.lblSamples.AutoSize = true; this.lblSamples.Location = new System.Drawing.Point(0, 6); this.lblSamples.Name = "lblSamples"; this.lblSamples.Size = new System.Drawing.Size(96, 13); this.lblSamples.TabIndex = 0; this.lblSamples.Text = "Available Samples:"; // // tlpSampleInfoBorder // this.tlpSampleInfoBorder.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single; this.tlpSampleInfoBorder.ColumnCount = 1; this.tlpSampleInfoBorder.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tlpSampleInfoBorder.Controls.Add(this.tlpSampleInfo, 0, 0); this.tlpSampleInfoBorder.Dock = System.Windows.Forms.DockStyle.Fill; this.tlpSampleInfoBorder.Location = new System.Drawing.Point(0, 0); this.tlpSampleInfoBorder.Margin = new System.Windows.Forms.Padding(0); this.tlpSampleInfoBorder.Name = "tlpSampleInfoBorder"; this.tlpSampleInfoBorder.RowCount = 1; this.tlpSampleInfoBorder.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tlpSampleInfoBorder.Size = new System.Drawing.Size(230, 91); this.tlpSampleInfoBorder.TabIndex = 0; // // tlpSampleInfo // this.tlpSampleInfo.ColumnCount = 1; this.tlpSampleInfo.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tlpSampleInfo.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tlpSampleInfo.Controls.Add(this.lblName, 0, 0); this.tlpSampleInfo.Controls.Add(this.lblDescription, 0, 1); this.tlpSampleInfo.Dock = System.Windows.Forms.DockStyle.Fill; this.tlpSampleInfo.Location = new System.Drawing.Point(1, 1); this.tlpSampleInfo.Margin = new System.Windows.Forms.Padding(0); this.tlpSampleInfo.Name = "tlpSampleInfo"; this.tlpSampleInfo.RowCount = 2; this.tlpSampleInfo.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tlpSampleInfo.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tlpSampleInfo.Size = new System.Drawing.Size(228, 89); this.tlpSampleInfo.TabIndex = 0; // // lblName // this.lblName.AutoSize = true; this.lblName.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bsSamples, "Name", true)); this.lblName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblName.Location = new System.Drawing.Point(3, 0); this.lblName.Name = "lblName"; this.lblName.Size = new System.Drawing.Size(39, 13); this.lblName.TabIndex = 0; this.lblName.Text = "Name"; // // lblDescription // this.lblDescription.AutoSize = true; this.lblDescription.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bsSamples, "Description", true)); this.lblDescription.Location = new System.Drawing.Point(3, 13); this.lblDescription.Name = "lblDescription"; this.lblDescription.Size = new System.Drawing.Size(60, 13); this.lblDescription.TabIndex = 1; this.lblDescription.Text = "Description"; // // btnRun // this.btnRun.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnRun.Location = new System.Drawing.Point(160, 429); this.btnRun.Name = "btnRun"; this.btnRun.Size = new System.Drawing.Size(75, 23); this.btnRun.TabIndex = 1; this.btnRun.Text = "&Run"; this.btnRun.UseVisualStyleBackColor = true; this.btnRun.Click += new System.EventHandler(this.btnRun_Click); // // scSourceOutput // this.scSourceOutput.Dock = System.Windows.Forms.DockStyle.Fill; this.scSourceOutput.Location = new System.Drawing.Point(0, 0); this.scSourceOutput.Margin = new System.Windows.Forms.Padding(0); this.scSourceOutput.Name = "scSourceOutput"; this.scSourceOutput.Orientation = System.Windows.Forms.Orientation.Horizontal; // // scSourceOutput.Panel1 // this.scSourceOutput.Panel1.Controls.Add(this.rtbSource); this.scSourceOutput.Panel1.Controls.Add(this.lblSource); // // scSourceOutput.Panel2 // this.scSourceOutput.Panel2.Controls.Add(this.lblResult); this.scSourceOutput.Panel2.Controls.Add(this.rtbOutput); this.scSourceOutput.Size = new System.Drawing.Size(375, 458); this.scSourceOutput.SplitterDistance = 288; this.scSourceOutput.TabIndex = 3; this.scSourceOutput.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.scSourceOutput_SplitterMoved); // // rtbSource // this.rtbSource.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.rtbSource.Location = new System.Drawing.Point(0, 22); this.rtbSource.Name = "rtbSource"; this.rtbSource.ReadOnly = true; this.rtbSource.Size = new System.Drawing.Size(367, 265); this.rtbSource.TabIndex = 2; this.rtbSource.Text = ""; this.rtbSource.WordWrap = false; // // lblSource // this.lblSource.AutoSize = true; this.lblSource.Location = new System.Drawing.Point(1, 6); this.lblSource.Name = "lblSource"; this.lblSource.Size = new System.Drawing.Size(71, 13); this.lblSource.TabIndex = 1; this.lblSource.Text = "Source code:"; // // lblResult // this.lblResult.AutoSize = true; this.lblResult.Location = new System.Drawing.Point(1, 2); this.lblResult.Name = "lblResult"; this.lblResult.Size = new System.Drawing.Size(78, 13); this.lblResult.TabIndex = 0; this.lblResult.Text = "Sample output:"; // // rtbOutput // this.rtbOutput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.rtbOutput.Location = new System.Drawing.Point(0, 18); this.rtbOutput.Name = "rtbOutput"; this.rtbOutput.ReadOnly = true; this.rtbOutput.Size = new System.Drawing.Size(367, 142); this.rtbOutput.TabIndex = 1; this.rtbOutput.Text = ""; this.rtbOutput.WordWrap = false; // // SampleBrowser // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(618, 458); this.Controls.Add(this.scMain); this.Name = "SampleBrowser"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Yahoo! Developer Network - .NET Sample Browser"; this.SizeChanged += new System.EventHandler(this.SampleBrowser_SizeChanged); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SampleBrowser_FormClosing); this.LocationChanged += new System.EventHandler(this.SampleBrowser_LocationChanged); this.Load += new System.EventHandler(this.SampleBrowser_Load); this.scMain.Panel1.ResumeLayout(false); this.scMain.Panel2.ResumeLayout(false); this.scMain.ResumeLayout(false); this.scSamples.Panel1.ResumeLayout(false); this.scSamples.Panel1.PerformLayout(); this.scSamples.Panel2.ResumeLayout(false); this.scSamples.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.bsSamples)).EndInit(); this.tlpSampleInfoBorder.ResumeLayout(false); this.tlpSampleInfo.ResumeLayout(false); this.tlpSampleInfo.PerformLayout(); this.scSourceOutput.Panel1.ResumeLayout(false); this.scSourceOutput.Panel1.PerformLayout(); this.scSourceOutput.Panel2.ResumeLayout(false); this.scSourceOutput.Panel2.PerformLayout(); this.scSourceOutput.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer scMain; private System.Windows.Forms.Label lblSamples; private System.Windows.Forms.Button btnRun; private System.Windows.Forms.ListBox lstSample; private System.Windows.Forms.Label lblResult; private System.Windows.Forms.RichTextBox rtbOutput; private System.Windows.Forms.SplitContainer scSamples; private System.Windows.Forms.BindingSource bsSamples; private System.Windows.Forms.TableLayoutPanel tlpSampleInfo; private System.Windows.Forms.Label lblName; private System.Windows.Forms.Label lblDescription; private System.Windows.Forms.TableLayoutPanel tlpSampleInfoBorder; private System.Windows.Forms.SplitContainer scSourceOutput; private System.Windows.Forms.Label lblSource; private System.Windows.Forms.RichTextBox rtbSource; } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WebAPIImageUpload.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace System.Reflection.Metadata.Ecma335 { public sealed class MetadataAggregator { // For each heap handle and each delta contains aggregate heap lengths. // heapSizes[heap kind][reader index] == Sum { 0..index | reader[i].XxxHeapLength } private readonly ImmutableArray<ImmutableArray<int>> _heapSizes; private readonly ImmutableArray<ImmutableArray<RowCounts>> _rowCounts; // internal for testing internal struct RowCounts : IComparable<RowCounts> { public int AggregateInserts; public int Updates; public int CompareTo(RowCounts other) { return AggregateInserts - other.AggregateInserts; } public override string ToString() { return string.Format("+0x{0:x} ~0x{1:x}", AggregateInserts, Updates); } } public MetadataAggregator(MetadataReader baseReader, IReadOnlyList<MetadataReader> deltaReaders) : this(baseReader, null, null, deltaReaders) { } public MetadataAggregator( IReadOnlyList<int> baseTableRowCounts, IReadOnlyList<int> baseHeapSizes, IReadOnlyList<MetadataReader> deltaReaders) : this(null, baseTableRowCounts, baseHeapSizes, deltaReaders) { } private MetadataAggregator( MetadataReader baseReader, IReadOnlyList<int> baseTableRowCounts, IReadOnlyList<int> baseHeapSizes, IReadOnlyList<MetadataReader> deltaReaders) { if (baseTableRowCounts == null) { if (baseReader == null) { throw new ArgumentNullException("baseReader"); } if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0) { throw new ArgumentException("Base reader must be a full metadata reader.", "baseReader"); } CalculateBaseCounts(baseReader, out baseTableRowCounts, out baseHeapSizes); Debug.Assert(baseTableRowCounts != null); } else { if (baseTableRowCounts.Count != MetadataTokens.TableCount) { throw new ArgumentException("Must have " + MetadataTokens.TableCount + " elements", "baseTableRowCounts"); } if (baseHeapSizes == null) { throw new ArgumentNullException("baseHeapSizes"); } if (baseHeapSizes.Count != MetadataTokens.HeapCount) { throw new ArgumentException("Must have " + MetadataTokens.HeapCount + " elements", "baseTableRowCounts"); } } if (deltaReaders == null || deltaReaders.Count == 0) { throw new ArgumentException("Must not be empty.", "deltaReaders"); } for (int i = 0; i < deltaReaders.Count; i++) { if (deltaReaders[i].GetTableRowCount(TableIndex.EncMap) == 0 || !deltaReaders[i].IsMinimalDelta) { throw new ArgumentException("All delta readers must be minimal delta metadata readers.", "deltaReaders"); } } _heapSizes = CalculateHeapSizes(baseHeapSizes, deltaReaders); _rowCounts = CalculateRowCounts(baseTableRowCounts, deltaReaders); } // for testing only internal MetadataAggregator(RowCounts[][] rowCounts, int[][] heapSizes) { _rowCounts = ToImmutable(rowCounts); _heapSizes = ToImmutable(heapSizes); } private static void CalculateBaseCounts( MetadataReader baseReader, out IReadOnlyList<int> baseTableRowCounts, out IReadOnlyList<int> baseHeapSizes) { int[] rowCounts = new int[MetadataTokens.TableCount]; int[] heapSizes = new int[MetadataTokens.HeapCount]; for (int i = 0; i < rowCounts.Length; i++) { rowCounts[i] = baseReader.GetTableRowCount((TableIndex)i); } for (int i = 0; i < heapSizes.Length; i++) { heapSizes[i] = baseReader.GetHeapSize((HeapIndex)i); } baseTableRowCounts = rowCounts; baseHeapSizes = heapSizes; } private static ImmutableArray<ImmutableArray<int>> CalculateHeapSizes( IReadOnlyList<int> baseSizes, IReadOnlyList<MetadataReader> deltaReaders) { // GUID heap index is multiple of sizeof(Guid) == 16 const int guidSize = 16; int generationCount = 1 + deltaReaders.Count; var userStringSizes = new int[generationCount]; var stringSizes = new int[generationCount]; var blobSizes = new int[generationCount]; var guidSizes = new int[generationCount]; userStringSizes[0] = baseSizes[(int)HeapIndex.UserString]; stringSizes[0] = baseSizes[(int)HeapIndex.String]; blobSizes[0] = baseSizes[(int)HeapIndex.Blob]; guidSizes[0] = baseSizes[(int)HeapIndex.Guid] / guidSize; for (int r = 0; r < deltaReaders.Count; r++) { userStringSizes[r + 1] = userStringSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.UserString); stringSizes[r + 1] = stringSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.String); blobSizes[r + 1] = blobSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.Blob); guidSizes[r + 1] = guidSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.Guid) / guidSize; } return ImmutableArray.Create( userStringSizes.ToImmutableArray(), stringSizes.ToImmutableArray(), blobSizes.ToImmutableArray(), guidSizes.ToImmutableArray()); } private static ImmutableArray<ImmutableArray<RowCounts>> CalculateRowCounts( IReadOnlyList<int> baseRowCounts, IReadOnlyList<MetadataReader> deltaReaders) { // TODO: optimize - we don't need to allocate all these arrays var rowCounts = GetBaseRowCounts(baseRowCounts, generations: 1 + deltaReaders.Count); for (int generation = 1; generation <= deltaReaders.Count; generation++) { CalculateDeltaRowCountsForGeneration(rowCounts, generation, ref deltaReaders[generation - 1].EncMapTable); } return ToImmutable(rowCounts); } private static ImmutableArray<ImmutableArray<T>> ToImmutable<T>(T[][] array) { var immutable = new ImmutableArray<T>[array.Length]; for (int i = 0; i < array.Length; i++) { immutable[i] = array[i].ToImmutableArray(); } return immutable.ToImmutableArray(); } // internal for testing internal static RowCounts[][] GetBaseRowCounts(IReadOnlyList<int> baseRowCounts, int generations) { var rowCounts = new RowCounts[TableIndexExtensions.Count][]; for (int t = 0; t < rowCounts.Length; t++) { rowCounts[t] = new RowCounts[generations]; rowCounts[t][0].AggregateInserts = baseRowCounts[t]; } return rowCounts; } // internal for testing internal static void CalculateDeltaRowCountsForGeneration(RowCounts[][] rowCounts, int generation, ref EnCMapTableReader encMapTable) { foreach (var tableRowCounts in rowCounts) { tableRowCounts[generation].AggregateInserts = tableRowCounts[generation - 1].AggregateInserts; } int mapRowCount = encMapTable.NumberOfRows; for (int mapRid = 1; mapRid <= mapRowCount; mapRid++) { uint token = encMapTable.GetToken(mapRid); int rid = (int)(token & TokenTypeIds.RIDMask); var tableRowCounts = rowCounts[token >> TokenTypeIds.RowIdBitCount]; if (rid > tableRowCounts[generation].AggregateInserts) { if (rid != tableRowCounts[generation].AggregateInserts + 1) { throw new BadImageFormatException(SR.EnCMapNotSorted); } // insert: tableRowCounts[generation].AggregateInserts = rid; } else { // update: tableRowCounts[generation].Updates++; } } } public Handle GetGenerationHandle(Handle handle, out int generation) { if (handle.IsVirtual) { // TODO: if a virtual handle is connected to real handle then translate the rid, // otherwise return vhandle and base. throw new NotSupportedException(); } if (handle.IsHeapHandle) { int heapOffset = handle.Offset; HeapIndex heapIndex; MetadataTokens.TryGetHeapIndex(handle.Kind, out heapIndex); var sizes = _heapSizes[(int)heapIndex]; generation = sizes.BinarySearch(heapOffset); if (generation >= 0) { Debug.Assert(sizes[generation] == heapOffset); // the index points to the start of the next generation that added data to the heap: do { generation++; } while (generation < sizes.Length && sizes[generation] == heapOffset); } else { generation = ~generation; } if (generation >= sizes.Length) { throw new ArgumentException(SR.HandleBelongsToFutureGeneration, "handle"); } // GUID heap accumulates - previous heap is copied to the next generation int relativeHeapOffset = (handle.Type == HandleType.Guid || generation == 0) ? heapOffset : heapOffset - sizes[generation - 1]; return new Handle((byte)handle.Type, relativeHeapOffset); } else { int rowId = handle.RowId; var sizes = _rowCounts[(int)handle.Type]; generation = sizes.BinarySearch(new RowCounts { AggregateInserts = rowId }); if (generation >= 0) { Debug.Assert(sizes[generation].AggregateInserts == rowId); // the row is in a generation that inserted exactly one row -- the one that we are looking for; // or it's in a preceding generation if the current one didn't insert any rows of the kind: while (generation > 0 && sizes[generation - 1].AggregateInserts == rowId) { generation--; } } else { // the row is in a generation that inserted multiple new rows: generation = ~generation; if (generation >= sizes.Length) { throw new ArgumentException(SR.HandleBelongsToFutureGeneration, "handle"); } } // In each delta table updates always precede inserts. int relativeRowId = (generation == 0) ? rowId : rowId - sizes[generation - 1].AggregateInserts + sizes[generation].Updates; return new Handle((byte)handle.Type, relativeRowId); } } } }
namespace VersionOne.ServiceHost.ConfigurationTool.UI.Controls { partial class BugzillaPageControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.grpConnection = new System.Windows.Forms.GroupBox(); this.chkIgnoreCertificate = new System.Windows.Forms.CheckBox(); this.lblConnectionValidation = new System.Windows.Forms.Label(); this.btnVerify = new System.Windows.Forms.Button(); this.txtPassword = new System.Windows.Forms.TextBox(); this.lblPassword = new System.Windows.Forms.Label(); this.txtUserName = new System.Windows.Forms.TextBox(); this.lblUserName = new System.Windows.Forms.Label(); this.txtUrl = new System.Windows.Forms.TextBox(); this.lblUrl = new System.Windows.Forms.Label(); this.grpSearch = new System.Windows.Forms.GroupBox(); this.lblMin = new System.Windows.Forms.Label(); this.lblTimerInterval = new System.Windows.Forms.Label(); this.nmdInterval = new System.Windows.Forms.NumericUpDown(); this.txtSearchName = new System.Windows.Forms.TextBox(); this.lblSearchName = new System.Windows.Forms.Label(); this.txtDefectLinkFieldId = new System.Windows.Forms.TextBox(); this.lblDefectLinkFieldId = new System.Windows.Forms.Label(); this.chkDisable = new System.Windows.Forms.CheckBox(); this.rbTag = new System.Windows.Forms.RadioButton(); this.rbAssign = new System.Windows.Forms.RadioButton(); this.pnlTagOrAssign = new System.Windows.Forms.Panel(); this.grpUpdateBugs = new System.Windows.Forms.GroupBox(); this.chkCloseAccept = new System.Windows.Forms.CheckBox(); this.txtCreateResolveValue = new System.Windows.Forms.TextBox(); this.lblCreateResolveValue = new System.Windows.Forms.Label(); this.txtCloseResolveValue = new System.Windows.Forms.TextBox(); this.lblCloseResolveValue = new System.Windows.Forms.Label(); this.grpVersionOne = new System.Windows.Forms.GroupBox(); this.cboSourceFieldValue = new System.Windows.Forms.ComboBox(); this.txtUrlTitle = new System.Windows.Forms.TextBox(); this.lblUrlTitle = new System.Windows.Forms.Label(); this.txtUrlTempl = new System.Windows.Forms.TextBox(); this.lblUrlTemplate = new System.Windows.Forms.Label(); this.lblSource = new System.Windows.Forms.Label(); this.tcBugzillaData = new System.Windows.Forms.TabControl(); this.tpGeneral = new System.Windows.Forms.TabPage(); this.tpMappings = new System.Windows.Forms.TabPage(); this.grpPriorityMappings = new System.Windows.Forms.GroupBox(); this.btnDeletePriorityMapping = new System.Windows.Forms.Button(); this.grdPriorityMappings = new System.Windows.Forms.DataGridView(); this.colVersionOnePriority = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.colBugzillaPriority = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.grpProjectMappings = new System.Windows.Forms.GroupBox(); this.btnDeleteProjectMapping = new System.Windows.Forms.Button(); this.grdProjectMappings = new System.Windows.Forms.DataGridView(); this.colVersionOneProject = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.colBugzillaProductName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.bsProjectMappings = new System.Windows.Forms.BindingSource(this.components); this.bsPriorityMappings = new System.Windows.Forms.BindingSource(this.components); this.grpConnection.SuspendLayout(); this.grpSearch.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nmdInterval)).BeginInit(); this.grpUpdateBugs.SuspendLayout(); this.grpVersionOne.SuspendLayout(); this.tcBugzillaData.SuspendLayout(); this.tpGeneral.SuspendLayout(); this.tpMappings.SuspendLayout(); this.grpPriorityMappings.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.grdPriorityMappings)).BeginInit(); this.grpProjectMappings.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.grdProjectMappings)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bsProjectMappings)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bsPriorityMappings)).BeginInit(); this.SuspendLayout(); // // grpConnection // this.grpConnection.Controls.Add(this.chkIgnoreCertificate); this.grpConnection.Controls.Add(this.lblConnectionValidation); this.grpConnection.Controls.Add(this.btnVerify); this.grpConnection.Controls.Add(this.txtPassword); this.grpConnection.Controls.Add(this.lblPassword); this.grpConnection.Controls.Add(this.txtUserName); this.grpConnection.Controls.Add(this.lblUserName); this.grpConnection.Controls.Add(this.txtUrl); this.grpConnection.Controls.Add(this.lblUrl); this.grpConnection.Location = new System.Drawing.Point(12, 10); this.grpConnection.Name = "grpConnection"; this.grpConnection.Size = new System.Drawing.Size(502, 109); this.grpConnection.TabIndex = 0; this.grpConnection.TabStop = false; this.grpConnection.Text = "Connection"; // // chkIgnoreCertificate // this.chkIgnoreCertificate.Location = new System.Drawing.Point(13, 75); this.chkIgnoreCertificate.Name = "chkIgnoreCertificate"; this.chkIgnoreCertificate.Size = new System.Drawing.Size(106, 17); this.chkIgnoreCertificate.TabIndex = 0; this.chkIgnoreCertificate.Text = "Ignore Certificate"; this.chkIgnoreCertificate.UseVisualStyleBackColor = true; // // lblConnectionValidation // this.lblConnectionValidation.AutoSize = true; this.lblConnectionValidation.Location = new System.Drawing.Point(175, 76); this.lblConnectionValidation.Name = "lblConnectionValidation"; this.lblConnectionValidation.Size = new System.Drawing.Size(81, 13); this.lblConnectionValidation.TabIndex = 6; this.lblConnectionValidation.Text = "Validation result"; this.lblConnectionValidation.Visible = false; // // btnVerify // this.btnVerify.Location = new System.Drawing.Point(366, 69); this.btnVerify.Name = "btnVerify"; this.btnVerify.Size = new System.Drawing.Size(87, 26); this.btnVerify.TabIndex = 7; this.btnVerify.Text = "Validate"; this.btnVerify.UseVisualStyleBackColor = true; // // txtPassword // this.txtPassword.Location = new System.Drawing.Point(334, 43); this.txtPassword.Name = "txtPassword"; this.txtPassword.Size = new System.Drawing.Size(119, 20); this.txtPassword.TabIndex = 5; // // lblPassword // this.lblPassword.AutoSize = true; this.lblPassword.Location = new System.Drawing.Point(265, 46); this.lblPassword.Name = "lblPassword"; this.lblPassword.Size = new System.Drawing.Size(53, 13); this.lblPassword.TabIndex = 4; this.lblPassword.Text = "Password"; // // txtUserName // this.txtUserName.Location = new System.Drawing.Point(89, 43); this.txtUserName.Name = "txtUserName"; this.txtUserName.Size = new System.Drawing.Size(121, 20); this.txtUserName.TabIndex = 3; // // lblUserName // this.lblUserName.AutoSize = true; this.lblUserName.Location = new System.Drawing.Point(10, 46); this.lblUserName.Name = "lblUserName"; this.lblUserName.Size = new System.Drawing.Size(55, 13); this.lblUserName.TabIndex = 2; this.lblUserName.Text = "Username"; // // txtUrl // this.txtUrl.Location = new System.Drawing.Point(89, 17); this.txtUrl.Name = "txtUrl"; this.txtUrl.Size = new System.Drawing.Size(364, 20); this.txtUrl.TabIndex = 1; // // lblUrl // this.lblUrl.AutoSize = true; this.lblUrl.Location = new System.Drawing.Point(10, 20); this.lblUrl.Name = "lblUrl"; this.lblUrl.Size = new System.Drawing.Size(68, 13); this.lblUrl.TabIndex = 0; this.lblUrl.Text = "Bugzilla URL"; // // grpSearch // this.grpSearch.Controls.Add(this.lblMin); this.grpSearch.Controls.Add(this.lblTimerInterval); this.grpSearch.Controls.Add(this.nmdInterval); this.grpSearch.Controls.Add(this.txtSearchName); this.grpSearch.Controls.Add(this.lblSearchName); this.grpSearch.Location = new System.Drawing.Point(12, 234); this.grpSearch.Name = "grpSearch"; this.grpSearch.Size = new System.Drawing.Size(502, 80); this.grpSearch.TabIndex = 2; this.grpSearch.TabStop = false; this.grpSearch.Text = "Find Bugzilla Bugs"; // // lblMin // this.lblMin.AutoSize = true; this.lblMin.Location = new System.Drawing.Point(213, 55); this.lblMin.Name = "lblMin"; this.lblMin.Size = new System.Drawing.Size(43, 13); this.lblMin.TabIndex = 4; this.lblMin.Text = "minutes"; // // lblTimerInterval // this.lblTimerInterval.AutoSize = true; this.lblTimerInterval.Location = new System.Drawing.Point(10, 52); this.lblTimerInterval.Name = "lblTimerInterval"; this.lblTimerInterval.Size = new System.Drawing.Size(62, 13); this.lblTimerInterval.TabIndex = 2; this.lblTimerInterval.Text = "Poll Interval"; // // nmdInterval // this.nmdInterval.Location = new System.Drawing.Point(152, 52); this.nmdInterval.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.nmdInterval.Name = "nmdInterval"; this.nmdInterval.Size = new System.Drawing.Size(52, 20); this.nmdInterval.TabIndex = 3; this.nmdInterval.Value = new decimal(new int[] { 5, 0, 0, 0}); // // txtSearchName // this.txtSearchName.Location = new System.Drawing.Point(152, 19); this.txtSearchName.Name = "txtSearchName"; this.txtSearchName.Size = new System.Drawing.Size(301, 20); this.txtSearchName.TabIndex = 1; // // lblSearchName // this.lblSearchName.AutoSize = true; this.lblSearchName.Location = new System.Drawing.Point(10, 22); this.lblSearchName.Name = "lblSearchName"; this.lblSearchName.Size = new System.Drawing.Size(72, 13); this.lblSearchName.TabIndex = 0; this.lblSearchName.Text = "Search Query"; // // txtDefectLinkFieldId // this.txtDefectLinkFieldId.Location = new System.Drawing.Point(152, 19); this.txtDefectLinkFieldId.Name = "txtDefectLinkFieldId"; this.txtDefectLinkFieldId.Size = new System.Drawing.Size(301, 20); this.txtDefectLinkFieldId.TabIndex = 1; // // lblDefectLinkFieldId // this.lblDefectLinkFieldId.AutoSize = true; this.lblDefectLinkFieldId.Location = new System.Drawing.Point(10, 22); this.lblDefectLinkFieldId.Name = "lblDefectLinkFieldId"; this.lblDefectLinkFieldId.Size = new System.Drawing.Size(136, 13); this.lblDefectLinkFieldId.TabIndex = 0; this.lblDefectLinkFieldId.Text = "Link to VersionOne Field ID"; // // chkDisable // this.chkDisable.AutoSize = true; this.chkDisable.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.chkDisable.Location = new System.Drawing.Point(402, 3); this.chkDisable.Name = "chkDisable"; this.chkDisable.Size = new System.Drawing.Size(67, 17); this.chkDisable.TabIndex = 0; this.chkDisable.Text = "Disabled"; this.chkDisable.UseVisualStyleBackColor = true; // // rbTag // this.rbTag.AutoSize = true; this.rbTag.Location = new System.Drawing.Point(152, 124); this.rbTag.Name = "rbTag"; this.rbTag.Size = new System.Drawing.Size(152, 17); this.rbTag.TabIndex = 9; this.rbTag.TabStop = true; this.rbTag.Text = "Tag defects by field values"; this.rbTag.UseVisualStyleBackColor = true; // // rbAssign // this.rbAssign.AutoSize = true; this.rbAssign.Location = new System.Drawing.Point(13, 124); this.rbAssign.Name = "rbAssign"; this.rbAssign.Size = new System.Drawing.Size(129, 17); this.rbAssign.TabIndex = 8; this.rbAssign.TabStop = true; this.rbAssign.Text = "Assign defects to user"; this.rbAssign.UseVisualStyleBackColor = true; // // pnlTagOrAssign // this.pnlTagOrAssign.Location = new System.Drawing.Point(6, 147); this.pnlTagOrAssign.Name = "pnlTagOrAssign"; this.pnlTagOrAssign.Size = new System.Drawing.Size(496, 123); this.pnlTagOrAssign.TabIndex = 10; // // grpUpdateBugs // this.grpUpdateBugs.Controls.Add(this.chkCloseAccept); this.grpUpdateBugs.Controls.Add(this.rbAssign); this.grpUpdateBugs.Controls.Add(this.txtCreateResolveValue); this.grpUpdateBugs.Controls.Add(this.lblCreateResolveValue); this.grpUpdateBugs.Controls.Add(this.rbTag); this.grpUpdateBugs.Controls.Add(this.txtCloseResolveValue); this.grpUpdateBugs.Controls.Add(this.pnlTagOrAssign); this.grpUpdateBugs.Controls.Add(this.txtDefectLinkFieldId); this.grpUpdateBugs.Controls.Add(this.lblCloseResolveValue); this.grpUpdateBugs.Controls.Add(this.lblDefectLinkFieldId); this.grpUpdateBugs.Location = new System.Drawing.Point(12, 320); this.grpUpdateBugs.Name = "grpUpdateBugs"; this.grpUpdateBugs.Size = new System.Drawing.Size(502, 275); this.grpUpdateBugs.TabIndex = 3; this.grpUpdateBugs.TabStop = false; this.grpUpdateBugs.Text = "Update Bugzilla Bugs"; // // txtCreateResolveValue // this.txtCreateResolveValue.Location = new System.Drawing.Point(152, 47); this.txtCreateResolveValue.Name = "txtCreateResolveValue"; this.txtCreateResolveValue.Size = new System.Drawing.Size(301, 20); this.txtCreateResolveValue.TabIndex = 5; // // lblCreateResolveValue // this.lblCreateResolveValue.AutoSize = true; this.lblCreateResolveValue.Location = new System.Drawing.Point(10, 50); this.lblCreateResolveValue.Name = "lblCreateResolveValue"; this.lblCreateResolveValue.Size = new System.Drawing.Size(110, 13); this.lblCreateResolveValue.TabIndex = 4; this.lblCreateResolveValue.Text = "Create Resolve Value"; // // chkCloseAccept // this.chkCloseAccept.AutoSize = true; this.chkCloseAccept.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.chkCloseAccept.Location = new System.Drawing.Point(9, 75); this.chkCloseAccept.Name = "chkCloseAccept"; this.chkCloseAccept.Size = new System.Drawing.Size(121, 17); this.chkCloseAccept.TabIndex = 3; this.chkCloseAccept.Text = "Close Accept "; this.chkCloseAccept.UseVisualStyleBackColor = true; // // txtCloseResolveValue // this.txtCloseResolveValue.Location = new System.Drawing.Point(152, 96); this.txtCloseResolveValue.Name = "txtCloseResolveValue"; this.txtCloseResolveValue.Size = new System.Drawing.Size(301, 20); this.txtCloseResolveValue.TabIndex = 7; // // lblCloseResolveValue // this.lblCloseResolveValue.AutoSize = true; this.lblCloseResolveValue.Location = new System.Drawing.Point(10, 99); this.lblCloseResolveValue.Name = "lblCloseResolveValue"; this.lblCloseResolveValue.Size = new System.Drawing.Size(105, 13); this.lblCloseResolveValue.TabIndex = 6; this.lblCloseResolveValue.Text = "Close Resolve Value"; // // grpVersionOne // this.grpVersionOne.Controls.Add(this.cboSourceFieldValue); this.grpVersionOne.Controls.Add(this.txtUrlTitle); this.grpVersionOne.Controls.Add(this.lblUrlTitle); this.grpVersionOne.Controls.Add(this.txtUrlTempl); this.grpVersionOne.Controls.Add(this.lblUrlTemplate); this.grpVersionOne.Controls.Add(this.lblSource); this.grpVersionOne.Location = new System.Drawing.Point(12, 124); this.grpVersionOne.Name = "grpVersionOne"; this.grpVersionOne.Size = new System.Drawing.Size(502, 105); this.grpVersionOne.TabIndex = 1; this.grpVersionOne.TabStop = false; this.grpVersionOne.Text = "VersionOne Defect Attributes"; // // cboSourceFieldValue // this.cboSourceFieldValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSourceFieldValue.FormattingEnabled = true; this.cboSourceFieldValue.Location = new System.Drawing.Point(152, 19); this.cboSourceFieldValue.Name = "cboSourceFieldValue"; this.cboSourceFieldValue.Size = new System.Drawing.Size(301, 21); this.cboSourceFieldValue.TabIndex = 1; // // txtUrlTitle // this.txtUrlTitle.Location = new System.Drawing.Point(152, 72); this.txtUrlTitle.Name = "txtUrlTitle"; this.txtUrlTitle.Size = new System.Drawing.Size(301, 20); this.txtUrlTitle.TabIndex = 5; // // lblUrlTitle // this.lblUrlTitle.AutoSize = true; this.lblUrlTitle.Location = new System.Drawing.Point(10, 75); this.lblUrlTitle.Name = "lblUrlTitle"; this.lblUrlTitle.Size = new System.Drawing.Size(52, 13); this.lblUrlTitle.TabIndex = 4; this.lblUrlTitle.Text = "URL Title"; // // txtUrlTempl // this.txtUrlTempl.Location = new System.Drawing.Point(152, 46); this.txtUrlTempl.Name = "txtUrlTempl"; this.txtUrlTempl.Size = new System.Drawing.Size(301, 20); this.txtUrlTempl.TabIndex = 3; // // lblUrlTemplate // this.lblUrlTemplate.AutoSize = true; this.lblUrlTemplate.Location = new System.Drawing.Point(10, 49); this.lblUrlTemplate.Name = "lblUrlTemplate"; this.lblUrlTemplate.Size = new System.Drawing.Size(76, 13); this.lblUrlTemplate.TabIndex = 2; this.lblUrlTemplate.Text = "URL Template"; // // lblSource // this.lblSource.AutoSize = true; this.lblSource.Location = new System.Drawing.Point(10, 22); this.lblSource.Name = "lblSource"; this.lblSource.Size = new System.Drawing.Size(41, 13); this.lblSource.TabIndex = 0; this.lblSource.Text = "Source"; // // tcBugzillaData // this.tcBugzillaData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tcBugzillaData.Controls.Add(this.tpGeneral); this.tcBugzillaData.Controls.Add(this.tpMappings); this.tcBugzillaData.Location = new System.Drawing.Point(0, 20); this.tcBugzillaData.Name = "tcBugzillaData"; this.tcBugzillaData.SelectedIndex = 0; this.tcBugzillaData.Size = new System.Drawing.Size(540, 643); this.tcBugzillaData.TabIndex = 1; // // tpGeneral // this.tpGeneral.Controls.Add(this.grpConnection); this.tpGeneral.Controls.Add(this.grpUpdateBugs); this.tpGeneral.Controls.Add(this.grpVersionOne); this.tpGeneral.Controls.Add(this.grpSearch); this.tpGeneral.Location = new System.Drawing.Point(4, 22); this.tpGeneral.Name = "tpGeneral"; this.tpGeneral.Padding = new System.Windows.Forms.Padding(3); this.tpGeneral.Size = new System.Drawing.Size(532, 617); this.tpGeneral.TabIndex = 0; this.tpGeneral.Text = "Bugzilla Service Settings"; this.tpGeneral.UseVisualStyleBackColor = true; // // tpMappings // this.tpMappings.Controls.Add(this.grpPriorityMappings); this.tpMappings.Controls.Add(this.grpProjectMappings); this.tpMappings.Location = new System.Drawing.Point(4, 22); this.tpMappings.Name = "tpMappings"; this.tpMappings.Padding = new System.Windows.Forms.Padding(3); this.tpMappings.Size = new System.Drawing.Size(532, 617); this.tpMappings.TabIndex = 1; this.tpMappings.Text = "Project and Priority Mappings"; this.tpMappings.UseVisualStyleBackColor = true; // // grpPriorityMappings // this.grpPriorityMappings.Controls.Add(this.btnDeletePriorityMapping); this.grpPriorityMappings.Controls.Add(this.grdPriorityMappings); this.grpPriorityMappings.Location = new System.Drawing.Point(12, 251); this.grpPriorityMappings.Name = "grpPriorityMappings"; this.grpPriorityMappings.Size = new System.Drawing.Size(502, 228); this.grpPriorityMappings.TabIndex = 2; this.grpPriorityMappings.TabStop = false; this.grpPriorityMappings.Text = "Priority Mappings"; // // btnDeletePriorityMapping // this.btnDeletePriorityMapping.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.DeleteIcon; this.btnDeletePriorityMapping.Location = new System.Drawing.Point(334, 187); this.btnDeletePriorityMapping.Name = "btnDeletePriorityMapping"; this.btnDeletePriorityMapping.Size = new System.Drawing.Size(119, 30); this.btnDeletePriorityMapping.TabIndex = 1; this.btnDeletePriorityMapping.Text = "Delete current row"; this.btnDeletePriorityMapping.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnDeletePriorityMapping.UseVisualStyleBackColor = true; // // grdPriorityMappings // this.grdPriorityMappings.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.grdPriorityMappings.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colVersionOnePriority, this.colBugzillaPriority}); this.grdPriorityMappings.Location = new System.Drawing.Point(12, 20); this.grdPriorityMappings.Name = "grdPriorityMappings"; this.grdPriorityMappings.Size = new System.Drawing.Size(441, 161); this.grdPriorityMappings.TabIndex = 0; // // colVersionOnePriority // this.colVersionOnePriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colVersionOnePriority.DataPropertyName = "VersionOnePriorityId"; this.colVersionOnePriority.HeaderText = "VersionOne Priority"; this.colVersionOnePriority.MinimumWidth = 100; this.colVersionOnePriority.Name = "colVersionOnePriority"; // // colBugzillaPriority // this.colBugzillaPriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colBugzillaPriority.DataPropertyName = "BugzillaPriorityName"; this.colBugzillaPriority.HeaderText = "Bugzilla Priority"; this.colBugzillaPriority.MinimumWidth = 100; this.colBugzillaPriority.Name = "colBugzillaPriority"; // // grpProjectMappings // this.grpProjectMappings.Controls.Add(this.btnDeleteProjectMapping); this.grpProjectMappings.Controls.Add(this.grdProjectMappings); this.grpProjectMappings.Location = new System.Drawing.Point(12, 17); this.grpProjectMappings.Name = "grpProjectMappings"; this.grpProjectMappings.Size = new System.Drawing.Size(502, 228); this.grpProjectMappings.TabIndex = 0; this.grpProjectMappings.TabStop = false; this.grpProjectMappings.Text = "Project Mappings"; // // btnDeleteProjectMapping // this.btnDeleteProjectMapping.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.DeleteIcon; this.btnDeleteProjectMapping.Location = new System.Drawing.Point(334, 187); this.btnDeleteProjectMapping.Name = "btnDeleteProjectMapping"; this.btnDeleteProjectMapping.Size = new System.Drawing.Size(119, 30); this.btnDeleteProjectMapping.TabIndex = 1; this.btnDeleteProjectMapping.Text = "Delete current row"; this.btnDeleteProjectMapping.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnDeleteProjectMapping.UseVisualStyleBackColor = true; // // grdProjectMappings // this.grdProjectMappings.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.grdProjectMappings.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colVersionOneProject, this.colBugzillaProductName}); this.grdProjectMappings.Location = new System.Drawing.Point(15, 20); this.grdProjectMappings.Name = "grdProjectMappings"; this.grdProjectMappings.Size = new System.Drawing.Size(438, 161); this.grdProjectMappings.TabIndex = 0; // // colVersionOneProject // this.colVersionOneProject.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colVersionOneProject.DataPropertyName = "VersionOneProjectToken"; this.colVersionOneProject.HeaderText = "VersionOne Project"; this.colVersionOneProject.MinimumWidth = 100; this.colVersionOneProject.Name = "colVersionOneProject"; // // colBugzillaProductName // this.colBugzillaProductName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.colBugzillaProductName.DataPropertyName = "BugzillaProjectName"; this.colBugzillaProductName.HeaderText = "Bugzilla Product Name"; this.colBugzillaProductName.MinimumWidth = 100; this.colBugzillaProductName.Name = "colBugzillaProductName"; // // BugzillaPageControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.Controls.Add(this.tcBugzillaData); this.Controls.Add(this.chkDisable); this.Name = "BugzillaPageControl"; this.Size = new System.Drawing.Size(540, 663); this.grpConnection.ResumeLayout(false); this.grpConnection.PerformLayout(); this.grpSearch.ResumeLayout(false); this.grpSearch.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nmdInterval)).EndInit(); this.grpUpdateBugs.ResumeLayout(false); this.grpUpdateBugs.PerformLayout(); this.grpVersionOne.ResumeLayout(false); this.grpVersionOne.PerformLayout(); this.tcBugzillaData.ResumeLayout(false); this.tpGeneral.ResumeLayout(false); this.tpMappings.ResumeLayout(false); this.grpPriorityMappings.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.grdPriorityMappings)).EndInit(); this.grpProjectMappings.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.grdProjectMappings)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bsProjectMappings)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bsPriorityMappings)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox grpConnection; private System.Windows.Forms.Button btnVerify; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.Label lblPassword; private System.Windows.Forms.TextBox txtUserName; private System.Windows.Forms.Label lblUserName; private System.Windows.Forms.TextBox txtUrl; private System.Windows.Forms.Label lblUrl; private System.Windows.Forms.GroupBox grpSearch; private System.Windows.Forms.TextBox txtSearchName; private System.Windows.Forms.Label lblSearchName; private System.Windows.Forms.TextBox txtDefectLinkFieldId; private System.Windows.Forms.Label lblDefectLinkFieldId; private System.Windows.Forms.CheckBox chkDisable; private System.Windows.Forms.Label lblTimerInterval; private System.Windows.Forms.NumericUpDown nmdInterval; private System.Windows.Forms.Label lblConnectionValidation; private System.Windows.Forms.Label lblMin; private System.Windows.Forms.RadioButton rbTag; private System.Windows.Forms.RadioButton rbAssign; private System.Windows.Forms.Panel pnlTagOrAssign; private System.Windows.Forms.GroupBox grpUpdateBugs; private System.Windows.Forms.TextBox txtCreateResolveValue; private System.Windows.Forms.Label lblCreateResolveValue; private System.Windows.Forms.TextBox txtCloseResolveValue; private System.Windows.Forms.Label lblCloseResolveValue; private System.Windows.Forms.CheckBox chkCloseAccept; private System.Windows.Forms.GroupBox grpVersionOne; private System.Windows.Forms.ComboBox cboSourceFieldValue; private System.Windows.Forms.TextBox txtUrlTitle; private System.Windows.Forms.Label lblUrlTitle; private System.Windows.Forms.TextBox txtUrlTempl; private System.Windows.Forms.Label lblUrlTemplate; private System.Windows.Forms.Label lblSource; private System.Windows.Forms.TabControl tcBugzillaData; private System.Windows.Forms.TabPage tpGeneral; private System.Windows.Forms.TabPage tpMappings; private System.Windows.Forms.GroupBox grpProjectMappings; private System.Windows.Forms.DataGridView grdProjectMappings; private System.Windows.Forms.Button btnDeleteProjectMapping; private System.Windows.Forms.BindingSource bsProjectMappings; private System.Windows.Forms.BindingSource bsPriorityMappings; private System.Windows.Forms.GroupBox grpPriorityMappings; private System.Windows.Forms.Button btnDeletePriorityMapping; private System.Windows.Forms.DataGridView grdPriorityMappings; private System.Windows.Forms.DataGridViewComboBoxColumn colVersionOnePriority; private System.Windows.Forms.DataGridViewTextBoxColumn colBugzillaPriority; private System.Windows.Forms.DataGridViewComboBoxColumn colVersionOneProject; private System.Windows.Forms.DataGridViewTextBoxColumn colBugzillaProductName; private System.Windows.Forms.CheckBox chkIgnoreCertificate; } }
using System; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.SharePoint.Client; namespace Core.ListRatingSettings { public enum VotingExperience { Ratings, Likes } public class RatingsEnabler { private readonly ILogger _logger; private readonly ClientContext _context; private List _library; public RatingsEnabler(ClientContext context) : this(context, new ConsoleLogger()) { } public RatingsEnabler(ClientContext context, ILogger logger) { if (context == null) throw new ArgumentNullException("context"); if (logger == null) throw new ArgumentNullException("logger"); _context = context; _logger = logger; } #region Rating Field private readonly Guid RatingsFieldGuid_AverageRating = new Guid("5a14d1ab-1513-48c7-97b3-657a5ba6c742"); private readonly Guid RatingsFieldGuid_RatingCount = new Guid("b1996002-9167-45e5-a4df-b2c41c6723c7"); private readonly Guid RatingsFieldGuid_RatedBy = new Guid("4D64B067-08C3-43DC-A87B-8B8E01673313"); private readonly Guid RatingsFieldGuid_Ratings = new Guid("434F51FB-FFD2-4A0E-A03B-CA3131AC67BA"); private readonly Guid LikeFieldGuid_LikedBy = new Guid("2cdcd5eb-846d-4f4d-9aaf-73e8e73c7312"); private readonly Guid LikeFieldGuid_LikeCount = new Guid("6e4d832b-f610-41a8-b3e0-239608efda41"); #endregion /// <summary> /// Enable Social Settings Likes/Ratings on given list /// </summary> /// <param name="listName">List Name</param> /// <param name="experience">Likes/Ratings</param> public void Enable(string listName,VotingExperience experience) { /* Get root Web * Validate if current web is publishing web * Find List/Library library * Add property to RootFolder of List/Library : key: Ratings_VotingExperience value:Likes * Add rating fields * Add fields to default view * */ var web = _context.Site.RootWeb; _context.Load(_context.Site.RootWeb, p => p.Url); _context.ExecuteQuery(); try { _logger.WriteInfo("Processing: " + web.Url); EnsureReputation(web, listName,experience); } catch (Exception e) { _logger.WriteException(string.Format("Error: {0} \nMessage: {1} \nStack: {2}", web.Url, e.Message, e.StackTrace)); } } private void EnsureReputation(Web web,string listName,VotingExperience experience) { // only process publishing web if (!IsPublishingWeb(web)) { _logger.WriteWarning("Is publishing site : No"); return; } _logger.WriteInfo("Is publishing site : Yes"); SetCulture(GetWebCulture(web)); // Fetch Library try { _library = web.Lists.GetByTitle(listName); _context.Load(_library); _context.ExecuteQuery(); _logger.WriteSuccess("Found list/library : " + _library.Title); } catch (ServerException e) { _logger.WriteException(string.Format("Error: {0} \nMessage: {1} \nStack: {2}", web.Url, e.Message, e.StackTrace)); return; } // Add to property Root Folder of Pages Library AddProperty(experience); AddListFields(); AddViewFields(experience); _logger.WriteSuccess(string.Format("Enabled {0} on list/library {1}", experience,_library.Title)); } /// <summary> /// Checks if the web is Publishing Web /// </summary> /// <param name="web"></param> /// <returns></returns> private bool IsPublishingWeb(Web web) { _context.Load(web, p => p.AllProperties); _context.ExecuteQuery(); return web.AllProperties.FieldValues.ContainsKey("__PublishingFeatureActivated"); } /// <summary> /// Add Ratings/Likes related fields to List /// </summary> private void AddListFields() { //NOTE: The method returns the field, which can be used if required, for the sake of simplicity i removed it EnsureField(_library, RatingsFieldGuid_RatingCount); EnsureField(_library, RatingsFieldGuid_RatedBy); EnsureField(_library, RatingsFieldGuid_Ratings); EnsureField(_library, RatingsFieldGuid_AverageRating); EnsureField(_library, LikeFieldGuid_LikedBy); EnsureField(_library, LikeFieldGuid_LikeCount); _library.Update(); _context.ExecuteQuery(); _logger.WriteSuccess("Ensured fields in library."); } /// <summary> /// Add/Remove Ratings/Likes field in default view depending on exerpeince selected /// </summary> /// <param name="experience"></param> private void AddViewFields(VotingExperience experience) { // Add LikesCount and LikeBy (Explicit) to view fields _context.Load(_library.DefaultView, p => p.ViewFields); _context.ExecuteQuery(); var defaultView = _library.DefaultView; switch (experience) { case VotingExperience.Ratings: // Remove Likes Fields if(defaultView.ViewFields.Contains("LikesCount")) defaultView.ViewFields.Remove("LikesCount"); defaultView.ViewFields.Add("AverageRating"); // Add Ratings related field break; case VotingExperience.Likes: // Remove Ratings Fields // Add Likes related field if (defaultView.ViewFields.Contains("AverageRating")) defaultView.ViewFields.Remove("AverageRating"); defaultView.ViewFields.Add("LikesCount"); break; default: throw new ArgumentOutOfRangeException("experience"); } defaultView.Update(); _context.ExecuteQuery(); _logger.WriteSuccess("Ensured view-field."); } /// <summary> /// Check for Ratings/Likes field and add to ListField if doesn't exists. /// </summary> /// <param name="list">List</param> /// <param name="fieldId">Field Id</param> /// <returns></returns> private Field EnsureField(List list, Guid fieldId) { FieldCollection fields = list.Fields; FieldCollection availableFields = list.ParentWeb.AvailableFields; Field field = availableFields.GetById(fieldId); _context.Load(fields); _context.Load(field, p => p.SchemaXmlWithResourceTokens, p => p.Id, p => p.InternalName, p => p.StaticName); _context.ExecuteQuery(); if (!fields.Any(p => p.Id == fieldId)) { var newField = fields.AddFieldAsXml(field.SchemaXmlWithResourceTokens, false, AddFieldOptions.AddFieldInternalNameHint | AddFieldOptions.AddToAllContentTypes); return newField; } return field; } /// <summary> /// Add required key/value settings on List Root-Folder /// </summary> /// <param name="experience"></param> private void AddProperty(VotingExperience experience) { _context.Load(_library.RootFolder, p => p.Properties); _context.ExecuteQuery(); _library.RootFolder.Properties["Ratings_VotingExperience"] = experience.ToString(); _library.RootFolder.Update(); _context.ExecuteQuery(); _logger.WriteSuccess(string.Format("Ensured {0} Property.",experience)); } private uint GetWebCulture(Web web) { _context.Load(web, p => p.Language); _context.ExecuteQuery(); return web.Language; } private void SetCulture(uint culture) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CultureInfo.GetCultureInfo((int)culture).ToString()); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(CultureInfo.GetCultureInfo((int)culture).ToString()); } } }
// // Copyright (C) 2012-2014 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.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cassandra.Tasks; using Cassandra.Compression; using Cassandra.Requests; using Cassandra.Responses; using Cassandra.Serialization; using Microsoft.IO; namespace Cassandra { /// <summary> /// Represents a TCP connection to a Cassandra Node /// </summary> internal class Connection : IDisposable { private static readonly Logger Logger = new Logger(typeof(Connection)); private readonly Serializer _serializer; private readonly TcpSocket _tcpSocket; private int _disposed; /// <summary> /// Determines that the connection canceled pending operations. /// It could be because its being closed or there was a socket error. /// </summary> private volatile bool _isCanceled; private readonly object _cancelLock = new object(); private readonly Timer _idleTimer; private AutoResetEvent _pendingWaitHandle; private int _timedOutOperations; /// <summary> /// Stores the available stream ids. /// </summary> private ConcurrentStack<short> _freeOperations; /// <summary> Contains the requests that were sent through the wire and that hasn't been received yet.</summary> private ConcurrentDictionary<short, OperationState> _pendingOperations; /// <summary> It contains the requests that could not be written due to streamIds not available</summary> private ConcurrentQueue<OperationState> _writeQueue; /// <summary> /// Small buffer (less than 8 bytes) that is used when the next received message is smaller than 8 bytes, /// and it is not possible to read the header. /// </summary> private volatile byte[] _minimalBuffer; private volatile string _keyspace; private readonly SemaphoreSlim _keyspaceSwitchSemaphore = new SemaphoreSlim(1); private volatile Task<bool> _keyspaceSwitchTask; private volatile byte _frameHeaderSize; private MemoryStream _readStream; private int _isWriteQueueRuning; private int _inFlight; /// <summary> /// The event that represents a event RESPONSE from a Cassandra node /// </summary> public event CassandraEventHandler CassandraEventResponse; /// <summary> /// Event raised when there is an error when executing the request to prevent idle disconnects /// </summary> public event Action<Exception> OnIdleRequestException; /// <summary> /// Event that gets raised when a write has been completed. Testing purposes only. /// </summary> public event Action WriteCompleted; private const string IdleQuery = "SELECT key from system.local"; private const long CoalescingThreshold = 8000; public IFrameCompressor Compressor { get; set; } public IPEndPoint Address { get { return _tcpSocket.IPEndPoint; } } /// <summary> /// Determines the amount of operations that are not finished. /// </summary> public virtual int InFlight { get { return Thread.VolatileRead(ref _inFlight); } } /// <summary> /// Gets the amount of operations that timed out and didn't get a response /// </summary> public virtual int TimedOutOperations { get { return Thread.VolatileRead(ref _timedOutOperations); } } /// <summary> /// Determine if the Connection is closed /// </summary> public bool IsClosed { //if the connection attempted to cancel pending operations get { return _isCanceled; } } /// <summary> /// Determine if the Connection has been explicitly disposed /// </summary> public bool IsDisposed { get { return Thread.VolatileRead(ref _disposed) > 0; } } /// <summary> /// Gets the current keyspace. /// </summary> public string Keyspace { get { return _keyspace; } } /// <summary> /// Gets the amount of concurrent requests depending on the protocol version /// </summary> public int MaxConcurrentRequests { get { if (_serializer.ProtocolVersion < 3) { return 128; } //Protocol 3 supports up to 32K concurrent request without waiting a response //Allowing larger amounts of concurrent requests will cause large memory consumption //Limit to 2K per connection sounds reasonable. return 2048; } } public ProtocolOptions Options { get { return Configuration.ProtocolOptions; } } public Configuration Configuration { get; set; } public Connection(Serializer serializer, IPEndPoint endpoint, Configuration configuration) { if (serializer == null) { throw new ArgumentNullException("serializer"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } if (configuration.BufferPool == null) { throw new ArgumentNullException(null, "BufferPool can not be null"); } _serializer = serializer; Configuration = configuration; _tcpSocket = new TcpSocket(endpoint, configuration.SocketOptions, configuration.ProtocolOptions.SslOptions); _idleTimer = new Timer(IdleTimeoutHandler, null, Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Starts the authentication flow /// </summary> /// <param name="name">Authenticator name from server.</param> /// <exception cref="AuthenticationException" /> private Task<Response> StartAuthenticationFlow(string name) { //Determine which authentication flow to use. //Check if its using a C* 1.2 with authentication patched version (like DSE 3.1) var protocolVersion = _serializer.ProtocolVersion; var isPatchedVersion = protocolVersion == 1 && !(Configuration.AuthProvider is NoneAuthProvider) && Configuration.AuthInfoProvider == null; if (protocolVersion < 2 && !isPatchedVersion) { //Use protocol v1 authentication flow if (Configuration.AuthInfoProvider == null) { throw new AuthenticationException( String.Format("Host {0} requires authentication, but no credentials provided in Cluster configuration", Address), Address); } var credentialsProvider = Configuration.AuthInfoProvider; var credentials = credentialsProvider.GetAuthInfos(Address); var request = new CredentialsRequest(credentials); return Send(request) .ContinueSync(response => { if (!(response is ReadyResponse)) { //If Cassandra replied with a auth response error //The task already is faulted and the exception was already thrown. throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name); } return response; }); } //Use protocol v2+ authentication flow if (Configuration.AuthProvider is IAuthProviderNamed) { //Provide name when required ((IAuthProviderNamed) Configuration.AuthProvider).SetName(name); } //NewAuthenticator will throw AuthenticationException when NoneAuthProvider var authenticator = Configuration.AuthProvider.NewAuthenticator(Address); var initialResponse = authenticator.InitialResponse() ?? new byte[0]; return Authenticate(initialResponse, authenticator); } /// <exception cref="AuthenticationException" /> private Task<Response> Authenticate(byte[] token, IAuthenticator authenticator) { var request = new AuthResponseRequest(token); return Send(request) .Then(response => { if (response is AuthSuccessResponse) { //It is now authenticated // ReSharper disable once SuspiciousTypeConversion.Global var disposableAuthenticator = authenticator as IDisposable; if (disposableAuthenticator != null) { disposableAuthenticator.Dispose(); } return TaskHelper.ToTask(response); } if (response is AuthChallengeResponse) { token = authenticator.EvaluateChallenge(((AuthChallengeResponse)response).Token); if (token == null) { // If we get a null response, then authentication has completed //return without sending a further response back to the server. return TaskHelper.ToTask(response); } return Authenticate(token, authenticator); } throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name); }); } /// <summary> /// It callbacks all operations already sent / or to be written, that do not have a response. /// </summary> internal void CancelPending(Exception ex, SocketError? socketError = null) { //Multiple IO worker threads may been notifying that the socket is closing/in error lock (_cancelLock) { _isCanceled = true; Logger.Info("Canceling pending operations {0} and write queue {1}", Thread.VolatileRead(ref _inFlight), _writeQueue.Count); if (socketError != null) { Logger.Verbose("The socket status received was {0}", socketError.Value); } if (_pendingOperations.IsEmpty && _writeQueue.IsEmpty) { if (_pendingWaitHandle != null) { _pendingWaitHandle.Set(); } return; } if (ex == null || ex is ObjectDisposedException) { if (socketError != null) { ex = new SocketException((int)socketError.Value); } else { //It is closing ex = new SocketException((int)SocketError.NotConnected); } } //Callback all the items in the write queue OperationState state; while (_writeQueue.TryDequeue(out state)) { state.InvokeCallback(ex); } //Callback for every pending operation foreach (var item in _pendingOperations) { item.Value.InvokeCallback(ex); } _pendingOperations.Clear(); Interlocked.Exchange(ref _inFlight, 0); if (_pendingWaitHandle != null) { _pendingWaitHandle.Set(); } } } public virtual void Dispose() { if (Interlocked.Increment(ref _disposed) != 1) { //Only dispose once return; } _idleTimer.Dispose(); _tcpSocket.Dispose(); _keyspaceSwitchSemaphore.Dispose(); var readStream = Interlocked.Exchange(ref _readStream, null); if (readStream != null) { readStream.Close(); } } private void EventHandler(Exception ex, Response response) { if (!(response is EventResponse)) { Logger.Error("Unexpected response type for event: " + response.GetType().Name); return; } if (CassandraEventResponse != null) { CassandraEventResponse(this, ((EventResponse) response).CassandraEventArgs); } } /// <summary> /// Gets executed once the idle timeout has passed /// </summary> private void IdleTimeoutHandler(object state) { //Ensure there are no more idle timeouts until the query finished sending if (_isCanceled) { if (!IsDisposed) { //If it was not manually disposed Logger.Warning("Can not issue an heartbeat request as connection is closed"); if (OnIdleRequestException != null) { OnIdleRequestException(new SocketException((int)SocketError.NotConnected)); } } return; } Logger.Verbose("Connection idling, issuing a Request to prevent idle disconnects"); var request = new QueryRequest(_serializer.ProtocolVersion, IdleQuery, false, QueryProtocolOptions.Default); Send(request, (ex, response) => { if (ex == null) { //The send succeeded //There is a valid response but we don't care about the response return; } Logger.Warning("Received heartbeat request exception " + ex.ToString()); if (ex is SocketException && OnIdleRequestException != null) { OnIdleRequestException(ex); } }); } /// <summary> /// Initializes the connection. /// </summary> /// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception> /// <exception cref="AuthenticationException" /> /// <exception cref="UnsupportedProtocolVersionException"></exception> public Task<Response> Open() { _freeOperations = new ConcurrentStack<short>(Enumerable.Range(0, MaxConcurrentRequests).Select(s => (short)s).Reverse()); _pendingOperations = new ConcurrentDictionary<short, OperationState>(); _writeQueue = new ConcurrentQueue<OperationState>(); if (Options.CustomCompressor != null) { Compressor = Options.CustomCompressor; } else if (Options.Compression == CompressionType.LZ4) { Compressor = new LZ4Compressor(); } else if (Options.Compression == CompressionType.Snappy) { Compressor = new SnappyCompressor(); } //Init TcpSocket _tcpSocket.Init(); _tcpSocket.Error += CancelPending; _tcpSocket.Closing += () => CancelPending(null, null); //Read and write event handlers are going to be invoked using IO Threads _tcpSocket.Read += ReadHandler; _tcpSocket.WriteCompleted += WriteCompletedHandler; return _tcpSocket .Connect() .Then(_ => Startup()) .ContinueWith(t => { if (t.IsFaulted && t.Exception != null) { //Adapt the inner exception and rethrow var ex = t.Exception.InnerException; var protocolVersion = _serializer.ProtocolVersion; if (ex is ProtocolErrorException) { //As we are starting up, check for protocol version errors //There is no other way than checking the error message from Cassandra if (ex.Message.Contains("Invalid or unsupported protocol version")) { throw new UnsupportedProtocolVersionException(protocolVersion, ex); } } if (ex is ServerErrorException && protocolVersion >= 3 && ex.Message.Contains("ProtocolException: Invalid or unsupported protocol version")) { //For some versions of Cassandra, the error is wrapped into a server error //See CASSANDRA-9451 throw new UnsupportedProtocolVersionException(protocolVersion, ex); } throw ex; } return t.Result; }, TaskContinuationOptions.ExecuteSynchronously) .Then(response => { if (response is AuthenticateResponse) { return StartAuthenticationFlow(((AuthenticateResponse)response).Authenticator); } if (response is ReadyResponse) { return TaskHelper.ToTask(response); } throw new DriverInternalError("Expected READY or AUTHENTICATE, obtained " + response.GetType().Name); }); } /// <summary> /// Silently kill the connection, for testing purposes only /// </summary> internal void Kill() { _tcpSocket.Kill(); } private void ReadHandler(byte[] buffer, int bytesReceived) { if (_isCanceled) { //All pending operations have been canceled, there is no point in reading from the wire. return; } //We are currently using an IO Thread //Parse the data received var streamIdAvailable = ReadParse(buffer, bytesReceived); if (!streamIdAvailable) { return; } if (_pendingWaitHandle != null && _pendingOperations.IsEmpty && _writeQueue.IsEmpty) { _pendingWaitHandle.Set(); } //Process a next item in the queue if possible. //Maybe there are there items in the write queue that were waiting on a fresh streamId RunWriteQueue(); } private volatile FrameHeader _receivingHeader; /// <summary> /// Parses the bytes received into a frame. Uses the internal operation state to do the callbacks. /// Returns true if a full operation (streamId) has been processed and there is one available. /// </summary> /// <returns>True if a full operation (streamId) has been processed.</returns> internal bool ReadParse(byte[] buffer, int length) { if (length <= 0) { return false; } byte protocolVersion; if (_frameHeaderSize == 0) { //The server replies the first message with the max protocol version supported protocolVersion = FrameHeader.GetProtocolVersion(buffer); _serializer.ProtocolVersion = protocolVersion; _frameHeaderSize = FrameHeader.GetSize(protocolVersion); } else { protocolVersion = _serializer.ProtocolVersion; } //Use _readStream to buffer between messages, under low pressure, it should be null most of the times var stream = Interlocked.Exchange(ref _readStream, null); var operationCallbacks = new LinkedList<Action<MemoryStream>>(); var offset = 0; if (_minimalBuffer != null) { //use a negative offset to identify that there is a previous header buffer offset = -1 * _minimalBuffer.Length; } while (offset < length) { FrameHeader header; //The remaining body length to read from this buffer int remainingBodyLength; if (_receivingHeader == null) { if (length - offset < _frameHeaderSize) { _minimalBuffer = offset >= 0 ? Utils.SliceBuffer(buffer, offset, length - offset) : //it should almost never be the case there isn't enough bytes to read the header more than once // ReSharper disable once PossibleNullReferenceException Utils.JoinBuffers(_minimalBuffer, 0, _minimalBuffer.Length, buffer, 0, length); break; } if (offset >= 0) { header = FrameHeader.ParseResponseHeader(protocolVersion, buffer, offset); } else { header = FrameHeader.ParseResponseHeader(protocolVersion, _minimalBuffer, buffer); _minimalBuffer = null; } Logger.Verbose("Received #{0} from {1}", header.StreamId, Address); offset += _frameHeaderSize; remainingBodyLength = header.BodyLength; } else { header = _receivingHeader; remainingBodyLength = header.BodyLength - (int) stream.Length; _receivingHeader = null; } if (remainingBodyLength > length - offset) { //the buffer does not contains the body for this frame, buffer for later MemoryStream nextMessageStream; if (operationCallbacks.Count == 0 && stream != null) { //There hasn't been any operations completed with this buffer //And there is a previous stream: reuse it nextMessageStream = stream; } else { nextMessageStream = Configuration.BufferPool.GetStream(typeof(Connection) + "/Read"); } nextMessageStream.Write(buffer, offset, length - offset); Interlocked.Exchange(ref _readStream, nextMessageStream); _receivingHeader = header; break; } stream = stream ?? Configuration.BufferPool.GetStream(typeof (Connection) + "/Read"); OperationState state; if (header.Opcode != EventResponse.OpCode) { state = RemoveFromPending(header.StreamId); } else { //Its an event state = new OperationState(EventHandler); } stream.Write(buffer, offset, remainingBodyLength); var callback = state.SetCompleted(); operationCallbacks.AddLast(CreateResponseAction(header, callback)); offset += remainingBodyLength; } return InvokeReadCallbacks(stream, operationCallbacks); } /// <summary> /// Returns an action that capture the parameters closure /// </summary> private Action<MemoryStream> CreateResponseAction(FrameHeader header, Action<Exception, Response> callback) { var compressor = Compressor; return delegate(MemoryStream stream) { Response response = null; Exception ex = null; var nextPosition = stream.Position + header.BodyLength; try { Stream plainTextStream = stream; if (header.Flags.HasFlag(FrameHeader.HeaderFlag.Compression)) { plainTextStream = compressor.Decompress(new WrappedStream(stream, header.BodyLength)); plainTextStream.Position = 0; } response = FrameParser.Parse(new Frame(header, plainTextStream, _serializer)); } catch (Exception catchedException) { ex = catchedException; } if (response is ErrorResponse) { //Create an exception from the response error ex = ((ErrorResponse) response).Output.CreateException(); response = null; } //We must advance the position of the stream manually in case it was not correctly parsed stream.Position = nextPosition; callback(ex, response); }; } /// <summary> /// Invokes the callbacks using the default TaskScheduler. /// </summary> /// <returns>Returns true if one or more callback has been invoked.</returns> private static bool InvokeReadCallbacks(MemoryStream stream, ICollection<Action<MemoryStream>> operationCallbacks) { if (operationCallbacks.Count == 0) { //Not enough data to read a frame return false; } //Invoke all callbacks using the default TaskScheduler Task.Factory.StartNew(() => { stream.Position = 0; foreach (var cb in operationCallbacks) { cb(stream); } stream.Dispose(); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return true; } /// <summary> /// Sends a protocol STARTUP message /// </summary> private Task<Response> Startup() { var startupOptions = new Dictionary<string, string>(); startupOptions.Add("CQL_VERSION", "3.0.0"); if (Options.Compression == CompressionType.LZ4) { startupOptions.Add("COMPRESSION", "lz4"); } else if (Options.Compression == CompressionType.Snappy) { startupOptions.Add("COMPRESSION", "snappy"); } return Send(new StartupRequest(startupOptions)); } /// <summary> /// Sends a new request if possible. If it is not possible it queues it up. /// </summary> public Task<Response> Send(IRequest request) { var tcs = new TaskCompletionSource<Response>(); Send(request, tcs.TrySet); return tcs.Task; } /// <summary> /// Sends a new request if possible and executes the callback when the response is parsed. If it is not possible it queues it up. /// </summary> public OperationState Send(IRequest request, Action<Exception, Response> callback, int timeoutMillis = Timeout.Infinite) { if (_isCanceled) { callback(new SocketException((int)SocketError.NotConnected), null); return null; } var state = new OperationState(callback) { Request = request, TimeoutMillis = timeoutMillis > 0 ? timeoutMillis : Configuration.SocketOptions.ReadTimeoutMillis }; _writeQueue.Enqueue(state); RunWriteQueue(); return state; } private void RunWriteQueue() { var isAlreadyRunning = Interlocked.CompareExchange(ref _isWriteQueueRuning, 1, 0) == 1; if (isAlreadyRunning) { //there is another thread writing to the wire return; } //Start a new task using the TaskScheduler for writing Task.Factory.StartNew(RunWriteQueueAction, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private void RunWriteQueueAction() { //Dequeue all items until threshold is passed long totalLength = 0; RecyclableMemoryStream stream = null; var streamIdsAvailable = true; while (totalLength < CoalescingThreshold) { OperationState state; if (!_writeQueue.TryDequeue(out state)) { //No more items in the write queue break; } short streamId; if (!_freeOperations.TryPop(out streamId)) { streamIdsAvailable = false; //Queue it up for later. _writeQueue.Enqueue(state); //When receiving the next complete message, we can process it. Logger.Info("Enqueued, no streamIds available. If this message is recurrent consider configuring more connections per host or lower the pressure"); break; } Logger.Verbose("Sending #{0} for {1} to {2}", streamId, state.Request.GetType().Name, Address); _pendingOperations.AddOrUpdate(streamId, state, (k, oldValue) => state); Interlocked.Increment(ref _inFlight); int frameLength; try { //lazy initialize the stream stream = stream ?? (RecyclableMemoryStream) Configuration.BufferPool.GetStream(GetType().Name + "/SendStream"); frameLength = state.Request.WriteFrame(streamId, stream, _serializer); if (state.TimeoutMillis > 0 && Configuration.Timer != null) { state.Timeout = Configuration.Timer.NewTimeout(OnTimeout, streamId, state.TimeoutMillis); } } catch (Exception ex) { //There was an error while serializing or begin sending Logger.Error(ex); //The request was not written, clear it from pending operations RemoveFromPending(streamId); //Callback with the Exception state.InvokeCallback(ex); break; } //We will not use the request any more, stop reference it. state.Request = null; totalLength += frameLength; } if (totalLength == 0L) { //nothing to write Interlocked.Exchange(ref _isWriteQueueRuning, 0); if (streamIdsAvailable && !_writeQueue.IsEmpty) { //The write queue is not empty //An item was added to the queue but we were running: try to launch a new queue RunWriteQueue(); } if (stream != null) { //The stream instance could be created if there was an exception while generating the frame stream.Dispose(); } return; } //Write and close the stream when flushed // ReSharper disable once PossibleNullReferenceException : if totalLength > 0 the stream is initialized _tcpSocket.Write(stream, () => stream.Dispose()); } /// <summary> /// Removes an operation from pending and frees the stream id /// </summary> /// <param name="streamId"></param> internal protected virtual OperationState RemoveFromPending(short streamId) { OperationState state; if (_pendingOperations.TryRemove(streamId, out state)) { Interlocked.Decrement(ref _inFlight); } //Set the streamId as available _freeOperations.Push(streamId); return state; } /// <summary> /// Sets the keyspace of the connection. /// If the keyspace is different from the current value, it sends a Query request to change it /// </summary> public Task<bool> SetKeyspace(string value) { if (String.IsNullOrEmpty(value) || _keyspace == value) { //No need to switch return TaskHelper.Completed; } Task<bool> keyspaceSwitch; try { if (!_keyspaceSwitchSemaphore.Wait(0)) { //Could not enter semaphore //It is very likely that the connection is already switching keyspace keyspaceSwitch = _keyspaceSwitchTask; if (keyspaceSwitch != null) { return keyspaceSwitch.Then(_ => { //validate if the new keyspace is the expected if (_keyspace != value) { //multiple concurrent switches to different keyspace return SetKeyspace(value); } return TaskHelper.Completed; }); } _keyspaceSwitchSemaphore.Wait(); } } catch (ObjectDisposedException) { //The semaphore was disposed, this connection is closed return TaskHelper.FromException<bool>(new SocketException((int) SocketError.NotConnected)); } //Semaphore entered if (_keyspace == value) { //While waiting to enter the semaphore, the connection switched keyspace try { _keyspaceSwitchSemaphore.Release(); } catch (ObjectDisposedException) { //this connection is now closed but the switch completed successfully } return TaskHelper.Completed; } var request = new QueryRequest(_serializer.ProtocolVersion, string.Format("USE \"{0}\"", value), false, QueryProtocolOptions.Default); Logger.Info("Connection to host {0} switching to keyspace {1}", Address, value); keyspaceSwitch = _keyspaceSwitchTask = Send(request).ContinueSync(r => { _keyspace = value; try { _keyspaceSwitchSemaphore.Release(); } catch (ObjectDisposedException) { //this connection is now closed but the switch completed successfully } _keyspaceSwitchTask = null; return true; }); return keyspaceSwitch; } private void OnTimeout(object stateObj) { var streamId = (short)stateObj; OperationState state; if (!_pendingOperations.TryGetValue(streamId, out state)) { return; } var ex = new OperationTimedOutException(Address, state.TimeoutMillis); //Invoke if it hasn't been invoked yet //Once the response is obtained, we decrement the timed out counter var timedout = state.SetTimedOut(ex, () => Interlocked.Decrement(ref _timedOutOperations) ); if (!timedout) { //The response was obtained since the timer elapsed, move on return; } //Increase timed-out counter Interlocked.Increment(ref _timedOutOperations); } /// <summary> /// Method that gets executed when a write request has been completed. /// </summary> protected virtual void WriteCompletedHandler() { //This handler is invoked by IO threads //Make it quick if (WriteCompleted != null) { WriteCompleted(); } //There is no need for synchronization here //Only 1 thread can be here at the same time. //Set the idle timeout to avoid idle disconnects var heartBeatInterval = Configuration.PoolingOptions != null ? Configuration.PoolingOptions.GetHeartBeatInterval() : null; if (heartBeatInterval > 0 && !_isCanceled) { try { _idleTimer.Change(heartBeatInterval.Value, Timeout.Infinite); } catch (ObjectDisposedException) { //This connection is being disposed //Don't mind } } Interlocked.Exchange(ref _isWriteQueueRuning, 0); //Send the next request, if exists //It will use a new thread RunWriteQueue(); } internal WaitHandle WaitPending() { if (_pendingWaitHandle == null) { _pendingWaitHandle = new AutoResetEvent(false); } if (_pendingOperations.IsEmpty && _writeQueue.IsEmpty) { _pendingWaitHandle.Set(); } return _pendingWaitHandle; } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.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 MindTouch.Dream; namespace MindTouch.Xml { /// <summary> /// Provides an a base Xml document abstraction based on <see cref="XDoc"/> with additional methods to ease creating Atom documents. /// </summary> public abstract class XAtomBase : XDoc { //--- Constants --- /// <summary> /// Atom xml namespace /// </summary> public const string ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"; //--- Types --- /// <summary> /// Atom link rel attribute enumeration. /// </summary> public enum LinkRelation { /// <summary> /// Signifies a link that points to an alternate version of the current resource. /// </summary> Alternate, /// <summary> /// Signifies a link that points to a resource that is related to the current content. /// </summary> Related, /// <summary> /// Signifies a link to a resource that is the equivalent of the current content. /// </summary> Self, /// <summary> /// Signifies a link to a related resource that may be large in size or requires special handling. /// </summary> Enclosure, /// <summary> /// Signifies a link to a resource that is the source of the materail of the current content. /// </summary> Via, /// <summary> /// Signifies a link to the resource that allows editing of the current content. /// </summary> Edit, /// <summary> /// Signifies a link to furthest preceeding resource in a series of resources. /// </summary> First, /// <summary> /// Signifies a link to furthest following resource in a series of resources. /// </summary> Last, /// <summary> /// Signifies a link to immediately following resource in a series of resources. /// </summary> Next, /// <summary> /// Signifies a link to immediately preceeding resource in a series of resources. /// </summary> Previous } //--- Constructors --- /// <summary> /// Create a new Atom document from an existing document. /// </summary> /// <param name="doc">The source document.</param> public XAtomBase(XDoc doc) : base(doc) { } /// <summary> /// Creates an Atom document with a given root tag and updated date. /// </summary> /// <param name="tag">Root tag.</param> /// <param name="updated">Date the document was last updated.</param> public XAtomBase(string tag, DateTime updated) : base(tag, ATOM_NAMESPACE) { Start("generator").Attr("version", DreamUtil.DreamVersion).Value("MindTouch Dream XAtom").End(); Start("updated").Value(updated).End(); } //--- Properties --- /// <summary> /// Atom Id uri. /// </summary> public XUri Id { get { return this["id"].AsUri; } set { if(value == null) { this["id"].Remove(); } else if(this["id"].IsEmpty) { Elem("id", value); } else { this["id"].ReplaceValue(value); } } } //--- Methods --- /// <summary> /// Add an author to the document. /// </summary> /// <param name="name">Author name.</param> /// <param name="uri">Uri to Author resource.</param> /// <param name="email">Author email.</param> /// <returns>Returns the current document instance.</returns> public XAtomBase AddAuthor(string name, XUri uri, string email) { return AddPerson("author", name, uri, email); } /// <summary> /// Add a contributor to the document. /// </summary> /// <param name="name">Contributor name.</param> /// <param name="uri">Uri to Contributor resource.</param> /// <param name="email">Contributor email.</param> /// <returns>Returns the current document instance.</returns> public XAtomBase AddContributor(string name, XUri uri, string email) { return AddPerson("contributor", name, uri, email); } /// <summary> /// Add a category to the document. /// </summary> /// <param name="term">Category term.</param> /// <param name="scheme">Category scheme.</param> /// <param name="label">Category label.</param> /// <returns>Returns the current document instance.</returns> public XAtomBase AddCategory(string term, XUri scheme, string label) { if(string.IsNullOrEmpty(term)) { throw new ArgumentNullException("term"); } Start("category"); Attr("term", term); if(scheme != null) { Attr("scheme", scheme); } if(!string.IsNullOrEmpty(label)) { Attr("label", label); } End(); return this; } /// <summary> /// Add a link to the document. /// </summary> /// <param name="href">Uri to the linked resource.</param> /// <param name="relation">Relationship of the linked resource to the current document.</param> /// <param name="type">Type of resource being linked.</param> /// <param name="length">Size in bytes.</param> /// <param name="title">Title of the linked resource.</param> /// <returns>Returns the current document instance.</returns> public XAtomBase AddLink(XUri href, LinkRelation relation, MimeType type, long? length, string title) { Start("link"); Attr("href", href); Attr("rel", relation.ToString().ToLowerInvariant()); if(type != null) { Attr("type", type.FullType); } if(length != null) { Attr("length", length ?? 0); } if(!string.IsNullOrEmpty(title)) { Attr("title", title); } End(); return this; } /// <summary> /// Add text to the document. /// </summary> /// <param name="tag">Enclosing tag for the text.</param> /// <param name="type">Type attribute for the enclosed.</param> /// <param name="text">Text content to add.</param> /// <returns>Returns the current document instance.</returns> public XAtomBase AddText(string tag, string type, string text) { Start(tag).Attr("type", type).Value(text).End(); return this; } /// <summary> /// Add text to the document. /// </summary> /// <param name="tag">Enclosing tag for the text.</param> /// <param name="mime">Mime type of the enclosed text.</param> /// <param name="data">The text body as a byte array.</param> /// <returns>Returns the current document instance.</returns> public XAtomBase AddText(string tag, MimeType mime, byte[] data) { Start(tag).Attr("type", mime.FullType).Value(data).End(); return this; } /// <summary> /// Add text to the document. /// </summary> /// <param name="tag">Enclosing tag for the text.</param> /// <param name="mime">Mime type of the enclosed text.</param> /// <param name="xml">The body document to add.</param> /// <returns>Returns the current document instance.</returns> public XAtomBase AddText(string tag, MimeType mime, XDoc xml) { if(mime.Match(MimeType.XHTML)) { Start(tag).Attr("type", "xhtml"); // add content and normalize the root node XDoc added = xml.Clone().Rename("div"); if(added["@xmlns"].IsEmpty) { added.Attr("xmlns", "http://www.w3.org/1999/xhtml"); } Add(added); } else if(mime.Match(MimeType.HTML)) { Start(tag).Attr("type", "html"); // embed HTML as text Value(xml.ToInnerXHtml()); } else { Start(tag).Attr("type", mime.FullType); Add(xml); } // close element End(); return this; } /// <summary> /// Add a person reference to the document. /// </summary> /// <param name="tag">Enclosing tag for the person entry.</param> /// <param name="name">Person name.</param> /// <param name="uri">Uri to Person resource.</param> /// <param name="email">Person email.</param> /// <returns>Returns the current document instance.</returns> public XAtomBase AddPerson(string tag, string name, XUri uri, string email) { Start(tag); Elem("name", name ?? string.Empty); if(uri != null) { Elem("uri", uri); } if(!string.IsNullOrEmpty(email)) { Elem("email", email); } End(); return this; } } /// <summary> /// Provides a Atom feed document abstraction based on <see cref="XDoc"/>. /// </summary> public class XAtomFeed : XAtomBase { //--- Constructors --- /// <summary> /// Parse an existing Atom feed into the <see cref="XAtomFeed"/> representation. /// </summary> /// <param name="doc">The document to parse as an atom feed.</param> public XAtomFeed(XDoc doc) : base(doc) { if(doc.Name != "feed") { throw new ArgumentException("doc"); } UsePrefix("georss", "http://www.georss.org/georss"); UsePrefix("gml", "http://www.opengis.net/gml"); } /// <summary> /// Create a new Atom feed. /// </summary> /// <param name="title">Title of the feed.</param> /// <param name="link">Canonical uri to the feed resource.</param> /// <param name="updated">Last time the feed was updated.</param> public XAtomFeed(string title, XUri link, DateTime updated) : base("feed", updated) { if(string.IsNullOrEmpty(title)) { throw new ArgumentNullException("title"); } if(link == null) { throw new ArgumentNullException("link"); } // feed elements Start("title").Attr("type", "text").Value(title).End(); Start("link").Attr("rel", "self").Attr("href", link).End(); } //--- Properties --- /// <summary> /// Get an array of all entries in the feed. /// </summary> public XAtomEntry[] Entries { get { return Array.ConvertAll<XDoc, XAtomEntry>(Root["_:entry"].ToList().ToArray(), delegate(XDoc entry) { return new XAtomEntry(entry);}); } } //--- Methods --- /// <summary> /// Start a new entry block. /// </summary> /// <remarks>Behaves like the normal <see cref="XDoc.Start(string)"/> and sets the cursor to the new entry until a matching /// <see cref="XDoc.End()"/> is encountered.</remarks> /// <param name="title">Entry title.</param> /// <param name="published">Entry publication date.</param> /// <param name="updated">Last time the entry was updated.</param> /// <returns>A new <see cref="XAtomEntry"/> as a node in the current document.</returns> public XAtomEntry StartEntry(string title, DateTime published, DateTime updated) { Start("entry"); AddText("title", "text", title); Elem("published", published); Elem("updated", updated); return new XAtomEntry(this); } } /// <summary> /// Provides a Atom feed entry document abstraction based on <see cref="XDoc"/>. /// </summary> public class XAtomEntry : XAtomBase { //--- Constructors --- /// <summary> /// Parse an existing Atom feed entry into the <see cref="XAtomEntry"/> representation. /// </summary> /// <param name="doc">Document in the Atom feed entry format.</param> public XAtomEntry(XDoc doc) : base(doc) { if(doc.Name != "entry") { throw new ArgumentException("doc"); } UsePrefix("georss", "http://www.georss.org/georss"); UsePrefix("gml", "http://www.opengis.net/gml"); } /// <summary> /// Create a new Atom feed entry document. /// </summary> /// <param name="title">Entry title.</param> /// <param name="published">Entry publication date.</param> /// <param name="updated">Last time the entry was updated.</param> public XAtomEntry(string title, DateTime published, DateTime updated) : base("entry", updated) { Attr("xmlns:georss", "http://www.georss.org/georss"); UsePrefix("georss", "http://www.georss.org/georss"); Attr("xmlns:gml", "http://www.opengis.net/gml"); UsePrefix("gml", "http://www.opengis.net/gml"); AddText("title", "text", title); Start("published").Value(published).End(); } //--- Properties --- /// <summary> /// Entry Geo Rss Tag. /// </summary> public Tuplet<double, double> Where { get { XDoc where = Root["georss:where/gml:Point/gml:pos"]; if(where.IsEmpty) { return null; } string[] coords = where.Contents.Split(new char[] { ' ', ',' }, 2, StringSplitOptions.RemoveEmptyEntries); if(coords.Length != 2) { return null; } double x; double y; if(!double.TryParse(coords[0], out x) || !double.TryParse(coords[1], out y)) { return null; } return new Tuplet<double, double>(x, y); } set { this["georss:where"].Remove(); if(value != null) { Root.Start("georss:where").Start("gml:Point").Elem("gml:pos", string.Format("{0} {1}", value.Item1, value.Item2)).End().End(); } } } //--- Methods --- /// <summary> /// Add content to the entry. /// </summary> /// <param name="text">Text body to add.</param> /// <returns>Returns the current document instance.</returns> public XAtomEntry AddContent(string text) { AddText("content", "text", text); return this; } /// <summary> /// Add a subdocument as content to the entry. /// </summary> /// <param name="mime">Mime type of the document to be added.</param> /// <param name="xml">Document to add.</param> /// <returns>Returns the current document instance.</returns> public XAtomEntry AddContent(MimeType mime, XDoc xml) { AddText("content", mime, xml); return this; } /// <summary> /// Add content to the entry. /// </summary> /// <param name="mime">Mime type of the content to be added.</param> /// <param name="data">Content as byte array.</param> /// <returns>Returns the current document instance.</returns> public XAtomEntry AddContent(MimeType mime, byte[] data) { AddText("content", mime, data); return this; } /// <summary> /// Add an entry summary. /// </summary> /// <param name="text">Summary text.</param> /// <returns>Returns the current document instance.</returns> public XAtomEntry AddSummary(string text) { AddText("summary", "text", text); return this; } /// <summary> /// Add an entry summary document. /// </summary> /// <param name="mime">Mime type of the summary document to be added.</param> /// <param name="xml">Summary document.</param> /// <returns>Returns the current document instance.</returns> public XAtomEntry AddSummary(MimeType mime, XDoc xml) { AddText("summary", mime, xml); return this; } } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; // Used for file and directory // manipulation using System.IO; using System.Text; // Start VS with admin rights by // right clicking it and run as // administrator namespace CSharpTutA.cs { class Program { static void Main(string[] args) { // ----- MESSING WITH DIRECTORIES ----- // Get access to the current directory DirectoryInfo currDir = new DirectoryInfo("."); // Get access to a directory with a path DirectoryInfo dereksDir = new DirectoryInfo(@"C:\Users\derekbanas"); // Get the directory path Console.WriteLine(dereksDir.FullName); // Get the directory name Console.WriteLine(dereksDir.Name); // Get the parent directory Console.WriteLine(dereksDir.Parent); // What type is it Console.WriteLine(dereksDir.Attributes); // When was it created Console.WriteLine(dereksDir.CreationTime); // Create a directory DirectoryInfo dataDir = new DirectoryInfo(@"C:\Users\derekbanas\C#Data"); dataDir.Create(); // Delete a directory // Directory.Delete(@"C:\Users\derekbanas\C#Data"); // ----- SIMPLE FILE READING & WRITING ----- // Write a string array to a text file string[] customers = { "Bob Smith", "Sally Smith", "Robert Smith" }; string textFilePath = @"C:\Users\derekbanas\C#Data\testfile1.txt"; ; // Write the array File.WriteAllLines(textFilePath, customers); // Read strings from array foreach (string cust in File.ReadAllLines(textFilePath)) { Console.WriteLine($"Customer : {cust}"); } // ----- GETTING FILE DATA ----- DirectoryInfo myDataDir = new DirectoryInfo(@"C:\Users\derekbanas\C#Data"); // Get all txt files FileInfo[] txtFiles = myDataDir.GetFiles("*.txt", SearchOption.AllDirectories); // Number of matches Console.WriteLine("Matches : {0}", txtFiles.Length); foreach (FileInfo file in txtFiles) { // Get file name Console.WriteLine(file.Name); // Get bytes in file Console.WriteLine(file.Length); } // ----- FILESTREAMS ----- // FileStream is used to read and write a byte // or an array of bytes. string textFilePath2 = @"C:\Users\derekbanas\C#Data\testfile2.txt"; // Create and open a file FileStream fs = File.Open(textFilePath2, FileMode.Create); string randString = "This is a random string"; // Convert to a byte array byte[] rsByteArray = Encoding.Default.GetBytes(randString); // Write to file by defining the byte array, // the index to start writing from and length fs.Write(rsByteArray, 0, rsByteArray.Length); // Move back to the beginning of the file fs.Position = 0; // Create byte array to hold file data byte[] fileByteArray = new byte[rsByteArray.Length]; // Put bytes in array for(int i = 0; i < rsByteArray.Length; i++) { fileByteArray[i] = (byte)fs.ReadByte(); } // Convert from bytes to string and output Console.WriteLine(Encoding.Default.GetString(fileByteArray)); // Close the FileStream fs.Close(); // ----- STREAMWRITER / STREAMREADER ----- // These are best for reading and writing strings string textFilePath3 = @"C:\Users\derekbanas\C#Data\testfile3.txt"; // Create a text file StreamWriter sw = File.CreateText(textFilePath3); // Write to a file without a newline sw.Write("This is a random "); // Write to a file with a newline sw.WriteLine("sentence."); // Write another sw.WriteLine("This is another sentence."); // Close the StreamWriter sw.Close(); // Open the file for reading StreamReader sr = File.OpenText(textFilePath3); // Peek returns the next character as a unicode // number. Use Convert to change to a character Console.WriteLine("Peek : {0}", Convert.ToChar(sr.Peek())); // Read to a newline Console.WriteLine("1st String : {0}", sr.ReadLine()); // Read to the end of the file starting // where you left off reading Console.WriteLine("Everything : {0}", sr.ReadToEnd()); sr.Close(); // ----- BINARYWRITER / BINARYREADER ----- // Used to read and write data types string textFilePath4 = @"C:\Users\derekbanas\C#Data\testfile4.dat"; // Get the file FileInfo datFile = new FileInfo(textFilePath4); // Open the file BinaryWriter bw = new BinaryWriter(datFile.OpenWrite()); // Data to save to the file string randText = "Random Text"; int myAge = 42; double height = 6.25; // Write data to a file bw.Write(randText); bw.Write(myAge); bw.Write(height); bw.Close(); // Open file for reading BinaryReader br = new BinaryReader(datFile.OpenRead()); // Output data Console.WriteLine(br.ReadString()); Console.WriteLine(br.ReadInt32()); Console.WriteLine(br.ReadDouble()); br.Close(); Console.ReadLine(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // zlib.h -- interface of the 'zlib' general purpose compression library // version 1.2.1, November 17th, 2003 // // Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler // // 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. // // // ==--== // Compression engine namespace System.IO.Compression2 { using System.Diagnostics; internal class Deflater { private const int MinBlockSize = 256; private const int MaxHeaderFooterGoo = 120; private const int CleanCopySize = DeflateStream.DefaultBufferSize - MaxHeaderFooterGoo; private const double BadCompressionThreshold = 1.0; private FastEncoder deflateEncoder; private CopyEncoder copyEncoder; private DeflateInput input; private OutputBuffer output; private DeflaterState processingState; private DeflateInput inputFromHistory; public Deflater() { deflateEncoder = new FastEncoder(); copyEncoder = new CopyEncoder(); input = new DeflateInput(); output = new OutputBuffer(); processingState = DeflaterState.NotStarted; } public bool NeedsInput() { return input.Count == 0 && deflateEncoder.BytesInHistory == 0; } // Sets the input to compress. The only buffer copy occurs when the input is copied // to the FastEncoderWindow public void SetInput(byte[] inputBuffer, int startIndex, int count) { Debug.Assert(input.Count == 0, "We have something left in previous input!"); input.Buffer = inputBuffer; input.Count = count; input.StartIndex = startIndex; if (count > 0 && count < MinBlockSize) { // user is writing small buffers. If buffer size is below MinBlockSize, we // need to switch to a small data mode, to avoid block headers and footers // dominating the output. switch (processingState) { case DeflaterState.NotStarted: case DeflaterState.CheckingForIncompressible: // clean states, needs a block header first processingState = DeflaterState.StartingSmallData; break; case DeflaterState.CompressThenCheck: // already has correct block header processingState = DeflaterState.HandlingSmallData; break; } } } public int GetDeflateOutput(byte[] outputBuffer) { Debug.Assert(outputBuffer != null, "Can't pass in a null output buffer!"); Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input"); output.UpdateBuffer(outputBuffer); switch (processingState) { case DeflaterState.NotStarted: { // first call. Try to compress but if we get bad compression ratio, switch to uncompressed blocks. Debug.Assert(deflateEncoder.BytesInHistory == 0, "have leftover bytes in window"); // save these in case we need to switch to uncompressed format DeflateInput.InputState initialInputState = input.DumpState(); OutputBuffer.BufferState initialOutputState = output.DumpState(); deflateEncoder.GetBlockHeader(output); deflateEncoder.GetCompressedData(input, output); if (!UseCompressed(deflateEncoder.LastCompressionRatio)) { // we're expanding; restore state and switch to uncompressed input.RestoreState(initialInputState); output.RestoreState(initialOutputState); copyEncoder.GetBlock(input, output, false); FlushInputWindows(); processingState = DeflaterState.CheckingForIncompressible; } else { processingState = DeflaterState.CompressThenCheck; } break; } case DeflaterState.CompressThenCheck: { // continue assuming data is compressible. If we reach data that indicates otherwise // finish off remaining data in history and decide whether to compress on a // block-by-block basis deflateEncoder.GetCompressedData(input, output); if (!UseCompressed(deflateEncoder.LastCompressionRatio)) { processingState = DeflaterState.SlowDownForIncompressible1; inputFromHistory = deflateEncoder.UnprocessedInput; } break; } case DeflaterState.SlowDownForIncompressible1: { // finish off previous compressed block deflateEncoder.GetBlockFooter(output); processingState = DeflaterState.SlowDownForIncompressible2; goto case DeflaterState.SlowDownForIncompressible2; // yeah I know, but there's no fallthrough } case DeflaterState.SlowDownForIncompressible2: { // clear out data from history, but add them as uncompressed blocks if (inputFromHistory.Count > 0) { copyEncoder.GetBlock(inputFromHistory, output, false); } if (inputFromHistory.Count == 0) { // now we're clean deflateEncoder.FlushInput(); processingState = DeflaterState.CheckingForIncompressible; } break; } case DeflaterState.CheckingForIncompressible: { // decide whether to compress on a block-by-block basis Debug.Assert(deflateEncoder.BytesInHistory == 0, "have leftover bytes in window"); // save these in case we need to store as uncompressed DeflateInput.InputState initialInputState = input.DumpState(); OutputBuffer.BufferState initialOutputState = output.DumpState(); // enforce max so we can ensure state between calls deflateEncoder.GetBlock(input, output, CleanCopySize); if (!UseCompressed(deflateEncoder.LastCompressionRatio)) { // we're expanding; restore state and switch to uncompressed input.RestoreState(initialInputState); output.RestoreState(initialOutputState); copyEncoder.GetBlock(input, output, false); FlushInputWindows(); } break; } case DeflaterState.StartingSmallData: { // add compressed header and data, but not footer. Subsequent calls will keep // adding compressed data (no header and no footer). We're doing this to // avoid overhead of header and footer size relative to compressed payload. deflateEncoder.GetBlockHeader(output); processingState = DeflaterState.HandlingSmallData; goto case DeflaterState.HandlingSmallData; // yeah I know, but there's no fallthrough } case DeflaterState.HandlingSmallData: { // continue adding compressed data deflateEncoder.GetCompressedData(input, output); break; } } return output.BytesWritten; } public int Finish(byte[] outputBuffer) { Debug.Assert(outputBuffer != null, "Can't pass in a null output buffer!"); Debug.Assert(processingState == DeflaterState.NotStarted || processingState == DeflaterState.CheckingForIncompressible || processingState == DeflaterState.HandlingSmallData || processingState == DeflaterState.CompressThenCheck || processingState == DeflaterState.SlowDownForIncompressible1, "got unexpected processing state = " + processingState); Debug.Assert(NeedsInput()); // no need to add end of block info if we didn't write anything if (processingState == DeflaterState.NotStarted) { return 0; } output.UpdateBuffer(outputBuffer); if (processingState == DeflaterState.CompressThenCheck || processingState == DeflaterState.HandlingSmallData || processingState == DeflaterState.SlowDownForIncompressible1) { // need to finish off block deflateEncoder.GetBlockFooter(output); } // write final block WriteFinal(); return output.BytesWritten; } // Is compression ratio under threshold? private bool UseCompressed(double ratio) { return (ratio <= BadCompressionThreshold); } private void FlushInputWindows() { deflateEncoder.FlushInput(); } private void WriteFinal() { copyEncoder.GetBlock(null, output, true); } // These states allow us to assume that data is compressible and keep compression ratios at least // as good as historical values, but switch to different handling if that approach may increase the // data. If we detect we're getting a bad compression ratio, we switch to CheckingForIncompressible // state and decide to compress on a block by block basis. // // If we're getting small data buffers, we want to avoid overhead of excessive header and footer // info, so we add one header and keep adding blocks as compressed. This means that if the user uses // small buffers, they won't get the "don't increase size" improvements. // // An earlier iteration of this fix handled that data separately by buffering this data until it // reached a reasonable size, but given that Flush is not implemented on DeflateStream, this meant // data could be flushed only on Dispose. In the future, it would be reasonable to revisit this, in // case this isn't breaking. // // NotStarted -> CheckingForIncompressible, CompressThenCheck, StartingSmallData // CompressThenCheck -> SlowDownForIncompressible1 // SlowDownForIncompressible1 -> SlowDownForIncompressible2 // SlowDownForIncompressible2 -> CheckingForIncompressible // StartingSmallData -> HandlingSmallData internal enum DeflaterState { // no bytes to write yet NotStarted, // transient states SlowDownForIncompressible1, SlowDownForIncompressible2, StartingSmallData, // stable state: may transition to CheckingForIncompressible (via transient states) if it // appears we're expanding data CompressThenCheck, // sink states CheckingForIncompressible, HandlingSmallData } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Net; using System.Reflection; using Aurora.Simulation.Base; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Services { public class AgentHandler { private readonly ISimulationService m_SimulationService; protected bool m_Proxy; protected IRegistryCore m_registry; protected bool m_secure = true; public AgentHandler() { } public AgentHandler(ISimulationService sim, IRegistryCore registry, bool secure) { m_registry = registry; m_SimulationService = sim; m_secure = secure; } public Hashtable Handler(Hashtable request) { //MainConsole.Instance.Debug("[CONNECTION DEBUGGING]: AgentHandler Called"); //MainConsole.Instance.Debug("---------------------------"); //MainConsole.Instance.Debug(" >> uri=" + request["uri"]); //MainConsole.Instance.Debug(" >> content-type=" + request["content-type"]); //MainConsole.Instance.Debug(" >> http-method=" + request["http-method"]); //MainConsole.Instance.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; responsedata["keepalive"] = false; responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = ""; UUID agentID; UUID regionID; string action; string other; string uri = ((string) request["uri"]); if (m_secure) uri = uri.Remove(0, 37); //Remove the secure UUID from the uri if (!WebUtils.GetParams(uri, out agentID, out regionID, out action, out other)) { MainConsole.Instance.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]); responsedata["int_response_code"] = 404; responsedata["str_response_string"] = "false"; return responsedata; } // Next, let's parse the verb string method = (string) request["http-method"]; if (method.Equals("PUT")) { DoAgentPut(request, responsedata); return responsedata; } else if (method.Equals("POST")) { OSDMap map = null; try { string data = request["body"].ToString(); map = (OSDMap) OSDParser.DeserializeJson(data); } catch { if (request["content-type"].ToString() == "application/x-gzip") { System.IO.Stream inputStream = new System.IO.Compression.GZipStream(new System.IO.MemoryStream(Utils.StringToBytes(request["body"].ToString())), System.IO.Compression.CompressionMode.Decompress); System.IO.StreamReader reader = new System.IO.StreamReader(inputStream, System.Text.Encoding.UTF8); string requestBody = reader.ReadToEnd(); map = (OSDMap)OSDParser.DeserializeJson(requestBody); } } if (map != null) { if (map["Method"] == "MakeChildAgent") DoMakeChildAgent(agentID, map["LeavingRegion"].AsUUID(), regionID, map["MarkAgentAsLeaving"].AsBoolean()); else if (map["Method"] == "FailedToMoveAgentIntoNewRegion") FailedToMoveAgentIntoNewRegion(agentID, regionID); else DoAgentPost(request, responsedata, agentID); } return responsedata; } else if (method.Equals("GET")) { DoAgentGet(request, responsedata, agentID, regionID, bool.Parse(action)); return responsedata; } else if (method.Equals("DELETE")) { if(m_secure) DoAgentDelete(request, responsedata, agentID, action, regionID); return responsedata; } else if (method.Equals("QUERYACCESS")) { responsedata["int_response_code"] = HttpStatusCode.OK; OSDMap resp = new OSDMap(2); resp["success"] = OSD.FromBoolean(true); resp["reason"] = OSD.FromString(""); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); return responsedata; } else { MainConsole.Instance.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method); responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["str_response_string"] = "Method not allowed"; return responsedata; } } private void DoMakeChildAgent(UUID agentID, UUID leavingRegion, UUID regionID, bool markAgentAsLeaving) { m_SimulationService.MakeChildAgent(agentID, leavingRegion, new GridRegion { RegionID = regionID }, markAgentAsLeaving); } public bool FailedToMoveAgentIntoNewRegion(UUID AgentID, UUID RegionID) { return m_SimulationService.FailedToMoveAgentIntoNewRegion(AgentID, RegionID); } protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id) { OSDMap args = WebUtils.GetOSDMap((string) request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; uint teleportFlags = 0; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); else MainConsole.Instance.WarnFormat(" -- request didn't have destination_x"); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); else MainConsole.Instance.WarnFormat(" -- request didn't have destination_y"); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null) teleportFlags = args["teleport_flags"].AsUInteger(); AgentData agent = null; if (args.ContainsKey("agent_data") && args["agent_data"] != null) { try { OSDMap agentDataMap = (OSDMap) args["agent_data"]; agent = new AgentData(); agent.Unpack(agentDataMap); } catch (Exception ex) { MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex); } } GridRegion destination = new GridRegion {RegionID = uuid, RegionLocX = x, RegionLocY = y, RegionName = regionname}; AgentCircuitData aCircuit = new AgentCircuitData(); try { aCircuit.UnpackAgentCircuitData(args); } catch (Exception ex) { MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } OSDMap resp = new OSDMap(3); string reason = String.Empty; int requestedUDPPort = 0; // This is the meaning of POST agent bool result = CreateAgent(destination, aCircuit, teleportFlags, agent, out requestedUDPPort, out reason); resp["reason"] = reason; resp["requestedUDPPort"] = requestedUDPPort; resp["success"] = OSD.FromBoolean(result); // Let's also send out the IP address of the caller back to the caller (HG 1.5) resp["your_ip"] = OSD.FromString(GetCallerIP(request)); // TODO: add reason if not String.Empty? responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } private string GetCallerIP(Hashtable request) { if (!m_Proxy) return NetworkUtils.GetCallerIP(request); // We're behind a proxy Hashtable headers = (Hashtable) request["headers"]; if (headers.ContainsKey("X-Forwarded-For") && headers["X-Forwarded-For"] != null) { IPEndPoint ep = NetworkUtils.GetClientIPFromXFF((string) headers["X-Forwarded-For"]); if (ep != null) return ep.Address.ToString(); } // Oops return NetworkUtils.GetCallerIP(request); } // subclasses can override this protected virtual bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, AgentData agent, out int requestedUDPPort, out string reason) { return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, agent, out requestedUDPPort, out reason); } protected void DoAgentPut(Hashtable request, Hashtable responsedata) { OSDMap args = WebUtils.GetOSDMap((string) request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); GridRegion destination = new GridRegion {RegionID = uuid, RegionLocX = x, RegionLocY = y, RegionName = regionname}; string messageType; if (args["message_type"] != null) messageType = args["message_type"].AsString(); else { MainConsole.Instance.Warn("[AGENT HANDLER]: Agent Put Message Type not found. "); messageType = "AgentData"; } bool result = true; if ("AgentData".Equals(messageType)) { AgentData agent = new AgentData(); try { agent.Unpack(args); } catch (Exception ex) { MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } //agent.Dump(); // This is one of the meanings of PUT agent result = UpdateAgent(destination, agent); } else if ("AgentPosition".Equals(messageType)) { AgentPosition agent = new AgentPosition(); try { agent.Unpack(args); } catch (Exception ex) { MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex); return; } //agent.Dump(); // This is one of the meanings of PUT agent result = m_SimulationService.UpdateAgent(destination, agent); } OSDMap resp = new OSDMap(); resp["Updated"] = result; responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } // subclasses can override this protected virtual bool UpdateAgent(GridRegion destination, AgentData agent) { return m_SimulationService.UpdateAgent(destination, agent); } protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID, bool agentIsLeaving) { if (m_SimulationService == null) { MainConsole.Instance.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless."); responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.NotImplemented; responsedata["str_response_string"] = string.Empty; return; } GridRegion destination = new GridRegion {RegionID = regionID}; AgentData agent = null; AgentCircuitData circuitData; bool result = m_SimulationService.RetrieveAgent(destination, id, agentIsLeaving, out agent, out circuitData); OSDMap map = new OSDMap(); string strBuffer = ""; if (result) { if (agent != null) // just to make sure { map["AgentData"] = agent.Pack(); map["CircuitData"] = circuitData.PackAgentCircuitData(); try { strBuffer = OSDParser.SerializeJsonString(map); } catch (Exception e) { MainConsole.Instance.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e); responsedata["int_response_code"] = HttpStatusCode.InternalServerError; // ignore. buffer will be empty, caller should check. } } else { map = new OSDMap(); map["Result"] = "Internal error"; } } else { map = new OSDMap(); map["Result"] = "Not Found"; } strBuffer = OSDParser.SerializeJsonString(map); responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = strBuffer; } protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID) { MainConsole.Instance.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID); GridRegion destination = new GridRegion {RegionID = regionID}; if (action.Equals("release")) { object[] o = new object[2]; o[0] = id; o[1] = destination; //This is an OpenSim event... fire an event so that the OpenSim compat handlers can grab it m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler( "ReleaseAgent", o); } else m_SimulationService.CloseAgent(destination, id); responsedata["int_response_code"] = HttpStatusCode.OK; OSDMap map = new OSDMap(); map["Agent"] = id; responsedata["str_response_string"] = OSDParser.SerializeJsonString(map); MainConsole.Instance.Debug("[AGENT HANDLER]: Agent Released/Deleted."); } } }
using System; using System.IO; using UnityEditor.Rendering; using UnityEngine; using UnityEngine.Experimental.Rendering; using UnityEngine.Experimental.Rendering.HDPipeline; using UnityEngine.SceneManagement; using UnityEditor.SceneManagement; using UnityEngine.Rendering; namespace UnityEditor.Experimental.Rendering.HDPipeline { using UnityObject = UnityEngine.Object; public class HDRenderPipelineMenuItems { // Function used only to check performance of data with and without tessellation [MenuItem("Internal/HDRP/Test/Remove tessellation materials (not reversible)")] static void RemoveTessellationMaterials() { var materials = Resources.FindObjectsOfTypeAll<Material>(); var litShader = Shader.Find("HDRP/Lit"); var layeredLitShader = Shader.Find("HDRP/LayeredLit"); foreach (var mat in materials) { if (mat.shader.name == "HDRP/LitTessellation") { mat.shader = litShader; // We remove all keyword already present CoreEditorUtils.RemoveMaterialKeywords(mat); LitGUI.SetupMaterialKeywordsAndPass(mat); EditorUtility.SetDirty(mat); } else if (mat.shader.name == "HDRP/LayeredLitTessellation") { mat.shader = layeredLitShader; // We remove all keyword already present CoreEditorUtils.RemoveMaterialKeywords(mat); LayeredLitGUI.SetupMaterialKeywordsAndPass(mat); EditorUtility.SetDirty(mat); } } } [MenuItem("Edit/Render Pipeline/Export Sky to Image", priority = CoreUtils.editMenuPriority3)] static void ExportSkyToImage() { var renderpipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline; if (renderpipeline == null) { Debug.LogError("HDRenderPipeline is not instantiated."); return; } var result = renderpipeline.ExportSkyToTexture(); if (result == null) return; // Encode texture into PNG byte[] bytes = result.EncodeToEXR(Texture2D.EXRFlags.CompressZIP); UnityObject.DestroyImmediate(result); string assetPath = EditorUtility.SaveFilePanel("Export Sky", "Assets", "SkyExport", "exr"); if (!string.IsNullOrEmpty(assetPath)) { File.WriteAllBytes(assetPath, bytes); AssetDatabase.Refresh(); } } [MenuItem("GameObject/Rendering/Scene Settings", priority = CoreUtils.gameObjectMenuPriority)] static void CreateSceneSettingsGameObject(MenuCommand menuCommand) { var parent = menuCommand.context as GameObject; var sceneSettings = CoreEditorUtils.CreateGameObject(parent, "Scene Settings"); GameObjectUtility.SetParentAndAlign(sceneSettings, menuCommand.context as GameObject); Undo.RegisterCreatedObjectUndo(sceneSettings, "Create " + sceneSettings.name); Selection.activeObject = sceneSettings; var profile = VolumeProfileFactory.CreateVolumeProfile(sceneSettings.scene, "Scene Settings"); VolumeProfileFactory.CreateVolumeComponent<HDShadowSettings>(profile, true, false); var visualEnv = VolumeProfileFactory.CreateVolumeComponent<VisualEnvironment>(profile, true, false); visualEnv.skyType.value = SkySettings.GetUniqueID<ProceduralSky>(); visualEnv.fogType.value = FogType.Exponential; VolumeProfileFactory.CreateVolumeComponent<ProceduralSky>(profile, true, false); VolumeProfileFactory.CreateVolumeComponent<ExponentialFog>(profile, true, true); var volume = sceneSettings.AddComponent<Volume>(); volume.isGlobal = true; volume.sharedProfile = profile; var staticLightingSky = sceneSettings.AddComponent<StaticLightingSky>(); staticLightingSky.profile = volume.sharedProfile; staticLightingSky.staticLightingSkyUniqueID = SkySettings.GetUniqueID<ProceduralSky>(); } #if ENABLE_RAYTRACING [MenuItem("GameObject/Rendering/Raytracing Environment", priority = CoreUtils.gameObjectMenuPriority)] static void CreateRaytracingEnvironmentGameObject(MenuCommand menuCommand) { var parent = menuCommand.context as GameObject; var raytracingEnvGameObject = CoreEditorUtils.CreateGameObject(parent, "Raytracing Environment"); raytracingEnvGameObject.AddComponent<HDRaytracingEnvironment>(); } #endif class DoCreateNewAsset<TAssetType> : ProjectWindowCallback.EndNameEditAction where TAssetType : ScriptableObject { public override void Action(int instanceId, string pathName, string resourceFile) { var newAsset = CreateInstance<TAssetType>(); newAsset.name = Path.GetFileName(pathName); AssetDatabase.CreateAsset(newAsset, pathName); ProjectWindowUtil.ShowCreatedAsset(newAsset); } } class DoCreateNewAssetDiffusionProfileSettings : DoCreateNewAsset<DiffusionProfileSettings> { } [MenuItem("Assets/Create/Rendering/Diffusion Profile", priority = CoreUtils.assetCreateMenuPriority2)] static void MenuCreateDiffusionProfile() { var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon"); ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetDiffusionProfileSettings>(), "New Diffusion Profile.asset", icon, null); } [MenuItem("Internal/HDRP/Add \"Additional Light-shadow Data\" (if not present)")] static void AddAdditionalLightData() { var lights = UnityObject.FindObjectsOfType(typeof(Light)) as Light[]; foreach (var light in lights) { // Do not add a component if there already is one. if (light.GetComponent<HDAdditionalLightData>() == null) light.gameObject.AddComponent<HDAdditionalLightData>(); if (light.GetComponent<AdditionalShadowData>() == null) { AdditionalShadowData shadowData = light.gameObject.AddComponent<AdditionalShadowData>(); HDAdditionalShadowData.InitDefaultHDAdditionalShadowData(shadowData); } } } [MenuItem("Internal/HDRP/Add \"Additional Camera Data\" (if not present)")] static void AddAdditionalCameraData() { var cameras = UnityObject.FindObjectsOfType(typeof(Camera)) as Camera[]; foreach (var camera in cameras) { // Do not add a component if there already is one. if (camera.GetComponent<HDAdditionalCameraData>() == null) camera.gameObject.AddComponent<HDAdditionalCameraData>(); } } // This script is a helper for the artists to re-synchronize all layered materials [MenuItem("Internal/HDRP/Synchronize all Layered materials")] static void SynchronizeAllLayeredMaterial() { var materials = Resources.FindObjectsOfTypeAll<Material>(); bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive); foreach (var mat in materials) { if (mat.shader.name == "HDRP/LayeredLit" || mat.shader.name == "HDRP/LayeredLitTessellation") { CoreEditorUtils.CheckOutFile(VCSEnabled, mat); LayeredLitGUI.SynchronizeAllLayers(mat); EditorUtility.SetDirty(mat); } } } // The goal of this script is to help maintenance of data that have already been produced but need to update to the latest shader code change. // In case the shader code have change and the inspector have been update with new kind of keywords we need to regenerate the set of keywords use by the material. // This script will remove all keyword of a material and trigger the inspector that will re-setup all the used keywords. // It require that the inspector of the material have a static function call that update all keyword based on material properties. [MenuItem("Edit/Render Pipeline/Reset All Loaded High Definition Materials Keywords", priority = CoreUtils.editMenuPriority3)] static void ResetAllMaterialKeywords() { try { ResetAllLoadedMaterialKeywords(string.Empty, 1, 0); } finally { EditorUtility.ClearProgressBar(); } } // Don't expose, ResetAllMaterialKeywordsInProjectAndScenes include it anyway //[MenuItem("Edit/Render Pipeline/Reset All Material Asset's Keywords (Materials in Project)", priority = CoreUtils.editMenuPriority3)] static void ResetAllMaterialAssetsKeywords() { try { ResetAllMaterialAssetsKeywords(1, 0); } finally { EditorUtility.ClearProgressBar(); } } [MenuItem("Edit/Render Pipeline/Reset All Project and Scene High Definition Materials Keywords", priority = CoreUtils.editMenuPriority3)] static void ResetAllMaterialKeywordsInProjectAndScenes() { var openedScenes = new string[EditorSceneManager.loadedSceneCount]; for (var i = 0; i < openedScenes.Length; ++i) openedScenes[i] = SceneManager.GetSceneAt(i).path; bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive); try { var scenes = AssetDatabase.FindAssets("t:Scene"); var scale = 1f / Mathf.Max(1, scenes.Length); for (var i = 0; i < scenes.Length; ++i) { var scenePath = AssetDatabase.GUIDToAssetPath(scenes[i]); var sceneAsset = AssetDatabase.LoadAssetAtPath<SceneAsset>(scenePath); CoreEditorUtils.CheckOutFile(VCSEnabled, sceneAsset); EditorSceneManager.OpenScene(scenePath); var sceneName = Path.GetFileNameWithoutExtension(scenePath); var description = string.Format("{0} {1}/{2} - ", sceneName, i + 1, scenes.Length); if (ResetAllLoadedMaterialKeywords(description, scale, scale * i)) { EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene()); } } ResetAllMaterialAssetsKeywords(scale, scale * (scenes.Length - 1)); } finally { EditorUtility.ClearProgressBar(); if (openedScenes.Length > 0) { EditorSceneManager.OpenScene(openedScenes[0]); for (var i = 1; i < openedScenes.Length; i++) EditorSceneManager.OpenScene(openedScenes[i], OpenSceneMode.Additive); } } } static void ResetAllMaterialAssetsKeywords(float progressScale, float progressOffset) { var matIds = AssetDatabase.FindAssets("t:Material"); bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive); for (int i = 0, length = matIds.Length; i < length; i++) { var path = AssetDatabase.GUIDToAssetPath(matIds[i]); var mat = AssetDatabase.LoadAssetAtPath<Material>(path); EditorUtility.DisplayProgressBar( "Setup material asset's Keywords...", string.Format("{0} / {1} materials cleaned.", i, length), (i / (float)(length - 1)) * progressScale + progressOffset); CoreEditorUtils.CheckOutFile(VCSEnabled, mat); var h = Debug.unityLogger.logHandler; Debug.unityLogger.logHandler = new UnityContextualLogHandler(mat); HDEditorUtils.ResetMaterialKeywords(mat); Debug.unityLogger.logHandler = h; } } static bool ResetAllLoadedMaterialKeywords(string descriptionPrefix, float progressScale, float progressOffset) { var materials = Resources.FindObjectsOfTypeAll<Material>(); bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive); bool anyMaterialDirty = false; // Will be true if any material is dirty. for (int i = 0, length = materials.Length; i < length; i++) { EditorUtility.DisplayProgressBar( "Setup materials Keywords...", string.Format("{0}{1} / {2} materials cleaned.", descriptionPrefix, i, length), (i / (float)(length - 1)) * progressScale + progressOffset); CoreEditorUtils.CheckOutFile(VCSEnabled, materials[i]); if (HDEditorUtils.ResetMaterialKeywords(materials[i])) { anyMaterialDirty = true; } } return anyMaterialDirty; } class UnityContextualLogHandler : ILogHandler { UnityObject m_Context; static readonly ILogHandler k_DefaultLogHandler = Debug.unityLogger.logHandler; public UnityContextualLogHandler(UnityObject context) { m_Context = context; } public void LogFormat(LogType logType, UnityObject context, string format, params object[] args) { k_DefaultLogHandler.LogFormat(LogType.Log, m_Context, "Context: {0} ({1})", m_Context, AssetDatabase.GetAssetPath(m_Context)); k_DefaultLogHandler.LogFormat(logType, context, format, args); } public void LogException(Exception exception, UnityObject context) { k_DefaultLogHandler.LogFormat(LogType.Log, m_Context, "Context: {0} ({1})", m_Context, AssetDatabase.GetAssetPath(m_Context)); k_DefaultLogHandler.LogException(exception, context); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; namespace StructureMap { internal static class ReflectionHelper { public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression) { MemberExpression memberExpression = getMemberExpression(expression); return (PropertyInfo) memberExpression.Member; } public static PropertyInfo GetProperty<TModel, T>(Expression<Func<TModel, T>> expression) { MemberExpression memberExpression = getMemberExpression(expression); return (PropertyInfo) memberExpression.Member; } public static MemberInfo GetMember<T>(Expression<Func<T, object>> expression) { MemberExpression memberExpression = getMemberExpression(expression); return memberExpression.Member; } public static MemberInfo GetMember<TModel, T>(Expression<Func<TModel, T>> expression) { MemberExpression memberExpression = getMemberExpression(expression); return memberExpression.Member; } private static MemberExpression getMemberExpression<TModel, T>(Expression<Func<TModel, T>> expression) { MemberExpression memberExpression = null; if (expression.Body.NodeType == ExpressionType.Convert) { var body = (UnaryExpression) expression.Body; memberExpression = body.Operand as MemberExpression; } else if (expression.Body.NodeType == ExpressionType.MemberAccess) { memberExpression = expression.Body as MemberExpression; } if (memberExpression == null) throw new ArgumentException("Not a member access", "member"); return memberExpression; } public static MethodInfo GetMethod<T>(Expression<Func<T, object>> expression) { MethodCallExpression methodCall = expression.Body is UnaryExpression ? (MethodCallExpression) ((UnaryExpression) expression.Body).Operand : (MethodCallExpression) expression.Body; return methodCall.Method; } public static MethodInfo GetMethod<T, U>(Expression<Func<T, U>> expression) { var methodCall = (MethodCallExpression) expression.Body; return methodCall.Method; } public static MethodInfo GetMethod<T, U, V>(Expression<Func<T, U, V>> expression) { var methodCall = (MethodCallExpression) expression.Body; return methodCall.Method; } } /// <summary> /// Provides virtual methods that can be used by subclasses to parse an expression tree. /// </summary> /// <remarks> /// This class actually already exists in the System.Core assembly...as an internal class. /// I can only speculate as to why it is internal, but it is obviously much too dangerous /// for anyone outside of Microsoft to be using... /// </remarks> [DebuggerStepThrough, DebuggerNonUserCode] public abstract class ExpressionVisitorBase { public virtual Expression Visit(Expression exp) { if (exp == null) return exp; switch (exp.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: return VisitUnary((UnaryExpression) exp); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return VisitBinary((BinaryExpression) exp); case ExpressionType.TypeIs: return VisitTypeIs((TypeBinaryExpression) exp); case ExpressionType.Conditional: return VisitConditional((ConditionalExpression) exp); case ExpressionType.Constant: return VisitConstant((ConstantExpression) exp); case ExpressionType.Parameter: return VisitParameter((ParameterExpression) exp); case ExpressionType.MemberAccess: return VisitMemberAccess((MemberExpression) exp); case ExpressionType.Call: return VisitMethodCall((MethodCallExpression) exp); case ExpressionType.Lambda: return VisitLambda((LambdaExpression) exp); case ExpressionType.New: return VisitNew((NewExpression) exp); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return VisitNewArray((NewArrayExpression) exp); case ExpressionType.Invoke: return VisitInvocation((InvocationExpression) exp); case ExpressionType.MemberInit: return VisitMemberInit((MemberInitExpression) exp); case ExpressionType.ListInit: return VisitListInit((ListInitExpression) exp); default: throw new NotSupportedException(String.Format("Unhandled expression type: '{0}'", exp.NodeType)); } } protected virtual MemberBinding VisitBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment((MemberAssignment) binding); case MemberBindingType.MemberBinding: return VisitMemberMemberBinding((MemberMemberBinding) binding); case MemberBindingType.ListBinding: return VisitMemberListBinding((MemberListBinding) binding); default: throw new NotSupportedException(string.Format("Unhandled binding type '{0}'", binding.BindingType)); } } protected virtual ElementInit VisitElementInitializer(ElementInit initializer) { ReadOnlyCollection<Expression> arguments = VisitList(initializer.Arguments); if (arguments != initializer.Arguments) { return Expression.ElementInit(initializer.AddMethod, arguments); } return initializer; } protected virtual Expression VisitUnary(UnaryExpression u) { Expression operand = Visit(u.Operand); if (operand != u.Operand) { return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); } return u; } protected virtual Expression VisitBinary(BinaryExpression b) { Expression left = Visit(b.Left); Expression right = Visit(b.Right); Expression conversion = Visit(b.Conversion); if (left != b.Left || right != b.Right || conversion != b.Conversion) { if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) return Expression.Coalesce(left, right, conversion as LambdaExpression); else return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } return b; } protected virtual Expression VisitTypeIs(TypeBinaryExpression b) { Expression expr = Visit(b.Expression); if (expr != b.Expression) { return Expression.TypeIs(expr, b.TypeOperand); } return b; } protected virtual Expression VisitConstant(ConstantExpression c) { return c; } protected virtual Expression VisitConditional(ConditionalExpression c) { Expression test = Visit(c.Test); Expression ifTrue = Visit(c.IfTrue); Expression ifFalse = Visit(c.IfFalse); if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return c; } protected virtual Expression VisitParameter(ParameterExpression p) { return p; } protected virtual Expression VisitMemberAccess(MemberExpression m) { Expression exp = Visit(m.Expression); if (exp != m.Expression) { return Expression.MakeMemberAccess(exp, m.Member); } return m; } protected virtual Expression VisitMethodCall(MethodCallExpression m) { Expression obj = Visit(m.Object); IEnumerable<Expression> args = VisitList(m.Arguments); if (obj != m.Object || args != m.Arguments) { return Expression.Call(obj, m.Method, args); } return m; } protected virtual ReadOnlyCollection<Expression> VisitList(ReadOnlyCollection<Expression> original) { List<Expression> list = null; for (int i = 0, n = original.Count; i < n; i++) { Expression p = Visit(original[i]); if (list != null) { list.Add(p); } else if (p != original[i]) { list = new List<Expression>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(p); } } if (list != null) return list.AsReadOnly(); return original; } protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { Expression e = Visit(assignment.Expression); if (e != assignment.Expression) { return Expression.Bind(assignment.Member, e); } return assignment; } protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { IEnumerable<MemberBinding> bindings = VisitBindingList(binding.Bindings); if (bindings != binding.Bindings) { return Expression.MemberBind(binding.Member, bindings); } return binding; } protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) { IEnumerable<ElementInit> initializers = VisitElementInitializerList(binding.Initializers); if (initializers != binding.Initializers) { return Expression.ListBind(binding.Member, initializers); } return binding; } protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) { List<MemberBinding> list = null; for (int i = 0, n = original.Count; i < n; i++) { MemberBinding b = VisitBinding(original[i]); if (list != null) { list.Add(b); } else if (b != original[i]) { list = new List<MemberBinding>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(b); } } if (list != null) return list; return original; } protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) { List<ElementInit> list = null; for (int i = 0, n = original.Count; i < n; i++) { ElementInit init = VisitElementInitializer(original[i]); if (list != null) { list.Add(init); } else if (init != original[i]) { list = new List<ElementInit>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(init); } } if (list != null) return list; return original; } protected virtual Expression VisitLambda(LambdaExpression lambda) { Expression body = Visit(lambda.Body); if (body != lambda.Body) { return Expression.Lambda(lambda.Type, body, lambda.Parameters); } return lambda; } protected virtual NewExpression VisitNew(NewExpression nex) { IEnumerable<Expression> args = VisitList(nex.Arguments); if (args != nex.Arguments) { if (nex.Members != null) return Expression.New(nex.Constructor, args, nex.Members); else return Expression.New(nex.Constructor, args); } return nex; } protected virtual Expression VisitMemberInit(MemberInitExpression init) { NewExpression n = VisitNew(init.NewExpression); IEnumerable<MemberBinding> bindings = VisitBindingList(init.Bindings); if (n != init.NewExpression || bindings != init.Bindings) { return Expression.MemberInit(n, bindings); } return init; } protected virtual Expression VisitListInit(ListInitExpression init) { NewExpression n = VisitNew(init.NewExpression); IEnumerable<ElementInit> initializers = VisitElementInitializerList(init.Initializers); if (n != init.NewExpression || initializers != init.Initializers) { return Expression.ListInit(n, initializers); } return init; } protected virtual Expression VisitNewArray(NewArrayExpression na) { IEnumerable<Expression> exprs = VisitList(na.Expressions); if (exprs != na.Expressions) { if (na.NodeType == ExpressionType.NewArrayInit) { return Expression.NewArrayInit(na.Type.GetElementType(), exprs); } else { return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); } } return na; } protected virtual Expression VisitInvocation(InvocationExpression iv) { IEnumerable<Expression> args = VisitList(iv.Arguments); Expression expr = Visit(iv.Expression); if (args != iv.Arguments || expr != iv.Expression) { return Expression.Invoke(expr, args); } return iv; } } internal class ConstructorFinderVisitor : ExpressionVisitorBase { private ConstructorInfo _constructor; public ConstructorInfo Constructor { get { return _constructor; } } protected override NewExpression VisitNew(NewExpression nex) { _constructor = nex.Constructor; return base.VisitNew(nex); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace System.Runtime.Analyzers.UnitTests { public class SpecifyIFormatProviderTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new SpecifyIFormatProviderAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new SpecifyIFormatProviderAnalyzer(); } [Fact] public void CA1305_StringReturningStringFormatOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static string SpecifyIFormatProvider1() { return string.Format(""Foo {0}"", ""bar""); } public static string SpecifyIFormatProvider2() { return string.Format(""Foo {0} {1}"", ""bar"", ""foo""); } public static string SpecifyIFormatProvider3() { return string.Format(""Foo {0} {1} {2}"", ""bar"", ""foo"", ""bar""); } public static string SpecifyIFormatProvider4() { return string.Format(""Foo {0} {1} {2} {3}"", ""bar"", ""foo"", ""bar"", """"); } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 16, "string.Format(string, object)", "IFormatProviderStringTest.SpecifyIFormatProvider1()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(15, 16, "string.Format(string, object, object)", "IFormatProviderStringTest.SpecifyIFormatProvider2()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(20, 16, "string.Format(string, object, object, object)", "IFormatProviderStringTest.SpecifyIFormatProvider3()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(25, 16, "string.Format(string, params object[])", "IFormatProviderStringTest.SpecifyIFormatProvider4()", "string.Format(IFormatProvider, string, params object[])")); } [Fact] public void CA1305_StringReturningUserMethodOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void SpecifyIFormatProvider() { IFormatProviderOverloads.LeadingIFormatProviderReturningString(""Bar""); IFormatProviderOverloads.TrailingIFormatProviderReturningString(""Bar""); IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(""Bar""); } } internal static class IFormatProviderOverloads { public static string LeadingIFormatProviderReturningString(string format) { return LeadingIFormatProviderReturningString(CultureInfo.CurrentCulture, format); } public static string LeadingIFormatProviderReturningString(IFormatProvider provider, string format) { return string.Format(provider, format); } public static string TrailingIFormatProviderReturningString(string format) { return TrailingIFormatProviderReturningString(format, CultureInfo.CurrentCulture); } public static string TrailingIFormatProviderReturningString(string format, IFormatProvider provider) { return string.Format(provider, format); } public static string TrailingIFormatProviderReturningString(IFormatProvider provider, string format) { return string.Format(provider, format); } public static string UserDefinedParamsMatchMethodOverload(string format, params object[] objects) { return null; } public static string UserDefinedParamsMatchMethodOverload(IFormatProvider provider, string format, params object[] objs) { return null; } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.LeadingIFormatProviderReturningString(string)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.LeadingIFormatProviderReturningString(IFormatProvider, string)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.TrailingIFormatProviderReturningString(string)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.TrailingIFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(string, params object[])", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(IFormatProvider, string, params object[])")); } [Fact] public void CA1305_StringReturningNoDiagnostics_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void SpecifyIFormatProvider6() { IFormatProviderOverloads.IFormatProviderAsDerivedTypeOverload(""Bar""); } public static void SpecifyIFormatProvider7() { IFormatProviderOverloads.UserDefinedParamsMismatchMethodOverload(""Bar""); } } internal static class IFormatProviderOverloads { public static string IFormatProviderAsDerivedTypeOverload(string format) { return null; } public static string IFormatProviderAsDerivedTypeOverload(DerivedClass provider, string format) { return null; } public static string UserDefinedParamsMismatchMethodOverload(string format) { return null; } public static string UserDefinedParamsMismatchMethodOverload(IFormatProvider provider, string format, params object[] objs) { return null; } } public class DerivedClass : IFormatProvider { public object GetFormat(Type formatType) { throw new NotImplementedException(); } }"); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; public static class IFormatProviderStringTest { public static void TestMethod() { int x = Convert.ToInt32(""1""); long y = Convert.ToInt64(""1""); IFormatProviderOverloads.LeadingIFormatProvider(""1""); IFormatProviderOverloads.TrailingIFormatProvider(""1""); } } internal static class IFormatProviderOverloads { public static void LeadingIFormatProvider(string format) { LeadingIFormatProvider(CultureInfo.CurrentCulture, format); } public static void LeadingIFormatProvider(IFormatProvider provider, string format) { Console.WriteLine(string.Format(provider, format)); } public static void TrailingIFormatProvider(string format) { TrailingIFormatProvider(format, CultureInfo.CurrentCulture); } public static void TrailingIFormatProvider(string format, IFormatProvider provider) { Console.WriteLine(string.Format(provider, format)); } }", GetIFormatProviderAlternateRuleCSharpResultAt(9, 17, "Convert.ToInt32(string)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt32(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(10, 18, "Convert.ToInt64(string)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt64(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.LeadingIFormatProvider(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.LeadingIFormatProvider(IFormatProvider, string)"), GetIFormatProviderAlternateRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.TrailingIFormatProvider(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TrailingIFormatProvider(string, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_TargetMethodNoGenerics_CSharp() { VerifyCSharp(@" using System; public static class IFormatProviderStringTest { public static void TestMethod() { IFormatProviderOverloads.TargetMethodIsNonGeneric(""1""); IFormatProviderOverloads.TargetMethodIsGeneric<int>(""1""); // No Diagnostics because the target method can be generic } } internal static class IFormatProviderOverloads { public static void TargetMethodIsNonGeneric(string format) { } public static void TargetMethodIsNonGeneric<T>(string format, IFormatProvider provider) { } public static void TargetMethodIsGeneric<T>(string format) { } public static void TargetMethodIsGeneric(string format, IFormatProvider provider) { } }", GetIFormatProviderAlternateRuleCSharpResultAt(8, 9, "IFormatProviderOverloads.TargetMethodIsNonGeneric(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TargetMethodIsNonGeneric<T>(string, IFormatProvider)")); } [Fact] public void CA1305_StringReturningUICultureIFormatProvider_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class UICultureAsIFormatProviderReturningStringTest { public static void TestMethod() { IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.InstalledUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture); } } internal static class IFormatProviderOverloads { public static string IFormatProviderReturningString(string format, IFormatProvider provider) { return null; } public static string IFormatProviderReturningString(string format, IFormatProvider provider, IFormatProvider provider2) { return null; } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(10, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(11, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(12, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningUICultureIFormatProvider_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class UICultureAsIFormatProviderReturningNonStringTest { public static void TestMethod() { IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.InstalledUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture); } } internal static class IFormatProviderOverloads { public static void IFormatProviderReturningNonString(string format, IFormatProvider provider) { } public static void IFormatProviderReturningNonString(string format, IFormatProvider provider, IFormatProvider provider2) { } }", GetIFormatProviderAlternateRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(10, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(11, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_AcceptNullForIFormatProvider_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class UICultureAsIFormatProviderReturningStringTest { public static void TestMethod() { IFormatProviderOverloads.IFormatProviderReturningString(""1"", null); } } internal static class IFormatProviderOverloads { public static string IFormatProviderReturningString(string format, IFormatProvider provider) { return null; } }"); } [Fact] public void CA1305_DoesNotRecommendObsoleteOverload_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class TestClass { public static void TestMethod() { IFormatProviderOverloads.TrailingObsoleteIFormatProvider(""1""); } } internal static class IFormatProviderOverloads { public static string TrailingObsoleteIFormatProvider(string format) { return null; } [Obsolete] public static string TrailingObsoleteIFormatProvider(string format, IFormatProvider provider) { return null; } }"); } [Fact] public void CA1305_RuleException_NoDiagnostics_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void TrailingThreadCurrentUICulture() { var s = new System.Resources.ResourceManager(null); Console.WriteLine(s.GetObject("""", Thread.CurrentThread.CurrentUICulture)); Console.WriteLine(s.GetStream("""", Thread.CurrentThread.CurrentUICulture)); Console.WriteLine(s.GetResourceSet(Thread.CurrentThread.CurrentUICulture, false, false)); var activator = Activator.CreateInstance(null, System.Reflection.BindingFlags.CreateInstance, null, null, Thread.CurrentThread.CurrentUICulture); Console.WriteLine(activator); } }"); } [Fact] public void CA1305_StringReturningStringFormatOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Function SpecifyIFormatProvider1() As String Return String.Format(""Foo {0}"", ""bar"") End Function Public Shared Function SpecifyIFormatProvider2() As String Return String.Format(""Foo {0} {1}"", ""bar"", ""foo"") End Function Public Shared Function SpecifyIFormatProvider3() As String Return String.Format(""Foo {0} {1} {2}"", ""bar"", ""foo"", ""bar"") End Function Public Shared Function SpecifyIFormatProvider4() As String Return String.Format(""Foo {0} {1} {2} {3}"", ""bar"", ""foo"", ""bar"", """") End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(11, 16, "String.Format(String, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider1()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(15, 16, "String.Format(String, Object, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider2()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(19, 16, "String.Format(String, Object, Object, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider3()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(23, 16, "String.Format(String, ParamArray Object())", "IFormatProviderStringTest.SpecifyIFormatProvider4()", "String.Format(IFormatProvider, String, ParamArray Object())")); } [Fact] public void CA1305_StringReturningUserMethodOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub SpecifyIFormatProvider() IFormatProviderOverloads.LeadingIFormatProviderReturningString(""Bar"") IFormatProviderOverloads.TrailingIFormatProviderReturningString(""Bar"") IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(""Bar"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function LeadingIFormatProviderReturningString(format As String) As String Return LeadingIFormatProviderReturningString(CultureInfo.CurrentCulture, format) End Function Public Shared Function LeadingIFormatProviderReturningString(provider As IFormatProvider, format As String) As String Return String.Format(provider, format) End Function Public Shared Function TrailingIFormatProviderReturningString(format As String) As String Return TrailingIFormatProviderReturningString(format, CultureInfo.CurrentCulture) End Function Public Shared Function TrailingIFormatProviderReturningString(format As String, provider As IFormatProvider) As String Return String.Format(provider, format) End Function Public Shared Function TrailingIFormatProviderReturningString(provider As IFormatProvider, format As String) As String Return String.Format(provider, format) End Function Public Shared Function UserDefinedParamsMatchMethodOverload(format As String, ParamArray objects As Object()) As String Return Nothing End Function Public Shared Function UserDefinedParamsMatchMethodOverload(provider As IFormatProvider, format As String, ParamArray objs As Object()) As String Return Nothing End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(10, 9, "IFormatProviderOverloads.LeadingIFormatProviderReturningString(String)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.LeadingIFormatProviderReturningString(IFormatProvider, String)"), GetIFormatProviderAlternateStringRuleBasicResultAt(11, 9, "IFormatProviderOverloads.TrailingIFormatProviderReturningString(String)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.TrailingIFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(12, 9, "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(String, ParamArray Object())", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(IFormatProvider, String, ParamArray Object())")); } [Fact] public void CA1305_StringReturningNoDiagnostics_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub SpecifyIFormatProvider6() IFormatProviderOverloads.IFormatProviderAsDerivedTypeOverload(""Bar"") End Sub Public Shared Sub SpecifyIFormatProvider7() IFormatProviderOverloads.UserDefinedParamsMismatchMethodOverload(""Bar"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function IFormatProviderAsDerivedTypeOverload(format As String) As String Return Nothing End Function Public Shared Function IFormatProviderAsDerivedTypeOverload(provider As DerivedClass, format As String) As String Return Nothing End Function Public Shared Function UserDefinedParamsMismatchMethodOverload(format As String) As String Return Nothing End Function Public Shared Function UserDefinedParamsMismatchMethodOverload(provider As IFormatProvider, format As String, ParamArray objs As Object()) As String Return Nothing End Function End Class Public Class DerivedClass Implements IFormatProvider Public Function GetFormat(formatType As Type) As Object Implements IFormatProvider.GetFormat Throw New NotImplementedException() End Function End Class"); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub TestMethod() Dim x As Integer = Convert.ToInt32(""1"") Dim y As Long = Convert.ToInt64(""1"") IFormatProviderOverloads.LeadingIFormatProvider(""1"") IFormatProviderOverloads.TrailingIFormatProvider(""1"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub LeadingIFormatProvider(format As String) LeadingIFormatProvider(CultureInfo.CurrentCulture, format) End Sub Public Shared Sub LeadingIFormatProvider(provider As IFormatProvider, format As String) Console.WriteLine(String.Format(provider, format)) End Sub Public Shared Sub TrailingIFormatProvider(format As String) TrailingIFormatProvider(format, CultureInfo.CurrentCulture) End Sub Public Shared Sub TrailingIFormatProvider(format As String, provider As IFormatProvider) Console.WriteLine(String.Format(provider, format)) End Sub End Class", GetIFormatProviderAlternateRuleBasicResultAt(10, 28, "Convert.ToInt32(String)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt32(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(11, 25, "Convert.ToInt64(String)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt64(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(12, 9, "IFormatProviderOverloads.LeadingIFormatProvider(String)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.LeadingIFormatProvider(IFormatProvider, String)"), GetIFormatProviderAlternateRuleBasicResultAt(13, 9, "IFormatProviderOverloads.TrailingIFormatProvider(String)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TrailingIFormatProvider(String, IFormatProvider)")); } [Fact] public void CA1305_StringReturningUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class UICultureAsIFormatProviderReturningStringTest Private Sub New() End Sub Public Shared Sub TestMethod() IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.InstalledUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function IFormatProviderReturningString(format As String, provider As IFormatProvider) As String Return Nothing End Function Public Shared Function IFormatProviderReturningString(format As String, provider As IFormatProvider, provider2 As IFormatProvider) As String Return Nothing End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(10, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(11, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class UICultureAsIFormatProviderReturningNonStringTest Private Sub New() End Sub Public Shared Sub TestMethod() IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.InstalledUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider) End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider, provider2 As IFormatProvider) End Sub End Class", GetIFormatProviderAlternateRuleBasicResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(10, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(11, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningComputerInfoInstalledUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Imports Microsoft.VisualBasic.Devices Public NotInheritable Class UICultureAsIFormatProviderReturningNonStringTest Private Sub New() End Sub Public Shared Sub TestMethod() Dim computerInfo As New Microsoft.VisualBasic.Devices.ComputerInfo() IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", computerInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider) End Sub End Class", GetIFormatProviderUICultureRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "ComputerInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)")); } [Fact] public void CA1305_RuleException_NoDiagnostics_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub TrailingThreadCurrentUICulture() Dim s = New System.Resources.ResourceManager(Nothing) Console.WriteLine(s.GetObject("""", Thread.CurrentThread.CurrentUICulture)) Console.WriteLine(s.GetStream("""", Thread.CurrentThread.CurrentUICulture)) Console.WriteLine(s.GetResourceSet(Thread.CurrentThread.CurrentUICulture, False, False)) Dim activator__1 = Activator.CreateInstance(Nothing, System.Reflection.BindingFlags.CreateInstance, Nothing, Nothing, Thread.CurrentThread.CurrentUICulture) Console.WriteLine(activator__1) End Sub End Class"); } private DiagnosticResult GetIFormatProviderAlternateStringRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureStringRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateStringRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureStringRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureRule, arg1, arg2, arg3); } } }
// 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.Logging; using Avalonia.Threading; namespace Avalonia.Layout { /// <summary> /// Manages measuring and arranging of controls. /// </summary> public class LayoutManager : ILayoutManager { private readonly Queue<ILayoutable> _toMeasure = new Queue<ILayoutable>(); private readonly Queue<ILayoutable> _toArrange = new Queue<ILayoutable>(); private bool _queued; private bool _running; /// <summary> /// Gets the layout manager. /// </summary> public static ILayoutManager Instance => AvaloniaLocator.Current.GetService<ILayoutManager>(); /// <inheritdoc/> public void InvalidateMeasure(ILayoutable control) { Contract.Requires<ArgumentNullException>(control != null); Dispatcher.UIThread.VerifyAccess(); if (!control.IsAttachedToVisualTree) { #if DEBUG throw new AvaloniaInternalException( "LayoutManager.InvalidateMeasure called on a control that is detached from the visual tree."); #else return; #endif } _toMeasure.Enqueue(control); _toArrange.Enqueue(control); QueueLayoutPass(); } /// <inheritdoc/> public void InvalidateArrange(ILayoutable control) { Contract.Requires<ArgumentNullException>(control != null); Dispatcher.UIThread.VerifyAccess(); if (!control.IsAttachedToVisualTree) { #if DEBUG throw new AvaloniaInternalException( "LayoutManager.InvalidateArrange called on a control that is detached from the visual tree."); #else return; #endif } _toArrange.Enqueue(control); QueueLayoutPass(); } /// <inheritdoc/> public void ExecuteLayoutPass() { const int MaxPasses = 3; Dispatcher.UIThread.VerifyAccess(); if (!_running) { _running = true; Logger.Information( LogArea.Layout, this, "Started layout pass. To measure: {Measure} To arrange: {Arrange}", _toMeasure.Count, _toArrange.Count); var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); try { for (var pass = 0; pass < MaxPasses; ++pass) { ExecuteMeasurePass(); ExecuteArrangePass(); if (_toMeasure.Count == 0) { break; } } } finally { _running = false; } stopwatch.Stop(); Logger.Information(LogArea.Layout, this, "Layout pass finised in {Time}", stopwatch.Elapsed); } _queued = false; } /// <inheritdoc/> public void ExecuteInitialLayoutPass(ILayoutRoot root) { Measure(root); Arrange(root); // Running the initial layout pass may have caused some control to be invalidated // so run a full layout pass now (this usually due to scrollbars; its not known // whether they will need to be shown until the layout pass has run and if the // first guess was incorrect the layout will need to be updated). ExecuteLayoutPass(); } private void ExecuteMeasurePass() { while (_toMeasure.Count > 0) { var control = _toMeasure.Dequeue(); if (!control.IsMeasureValid && control.IsAttachedToVisualTree) { Measure(control); } } } private void ExecuteArrangePass() { while (_toArrange.Count > 0 && _toMeasure.Count == 0) { var control = _toArrange.Dequeue(); if (!control.IsArrangeValid && control.IsAttachedToVisualTree) { Arrange(control); } } } private void Measure(ILayoutable control) { // Controls closest to the visual root need to be arranged first. We don't try to store // ordered invalidation lists, instead we traverse the tree upwards, measuring the // controls closest to the root first. This has been shown by benchmarks to be the // fastest and most memory-efficent algorithm. if (control.VisualParent is ILayoutable parent) { Measure(parent); } // If the control being measured has IsMeasureValid == true here then its measure was // handed by an ancestor and can be ignored. The measure may have also caused the // control to be removed. if (!control.IsMeasureValid && control.IsAttachedToVisualTree) { if (control is ILayoutRoot root) { root.Measure(Size.Infinity); } else { control.Measure(control.PreviousMeasure.Value); } } } private void Arrange(ILayoutable control) { if (control.VisualParent is ILayoutable parent) { Arrange(parent); } if (!control.IsArrangeValid && control.IsAttachedToVisualTree) { if (control is IEmbeddedLayoutRoot embeddedRoot) control.Arrange(new Rect(embeddedRoot.AllocatedSize)); else if (control is ILayoutRoot root) control.Arrange(new Rect(root.DesiredSize)); else if (control.PreviousArrange != null) { // Has been observed that PreviousArrange sometimes is null, probably a bug somewhere else. // Condition observed: control.VisualParent is Scrollbar, control is Border. control.Arrange(control.PreviousArrange.Value); } } } private void QueueLayoutPass() { if (!_queued && !_running) { Dispatcher.UIThread.Post(ExecuteLayoutPass, DispatcherPriority.Layout); _queued = true; } } } }
using System; using SubSonic.Schema; using SubSonic.DataProviders; using System.Data; namespace Solution.DataAccess.DataModel { /// <summary> /// Table: RoomMoment /// Primary Key: Id /// </summary> public class RoomMomentStructs: DatabaseTable { public RoomMomentStructs(IDataProvider provider):base("RoomMoment",provider){ ClassName = "RoomMoment"; SchemaName = "dbo"; Columns.Add(new DatabaseColumn("Id", this) { IsPrimaryKey = true, DataType = DbType.Int64, IsNullable = false, AutoIncrement = true, IsForeignKey = false, MaxLength = 0, PropertyName = "Id" }); Columns.Add(new DatabaseColumn("MeetingRoom_Code", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 16, PropertyName = "MeetingRoom_Code" }); Columns.Add(new DatabaseColumn("MeetingRoom_Name", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "MeetingRoom_Name" }); Columns.Add(new DatabaseColumn("RoomDate", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "RoomDate" }); Columns.Add(new DatabaseColumn("T0800", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T0800" }); Columns.Add(new DatabaseColumn("T0830", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T0830" }); Columns.Add(new DatabaseColumn("T0900", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T0900" }); Columns.Add(new DatabaseColumn("T0930", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T0930" }); Columns.Add(new DatabaseColumn("T1000", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1000" }); Columns.Add(new DatabaseColumn("T1030", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1030" }); Columns.Add(new DatabaseColumn("T1100", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1100" }); Columns.Add(new DatabaseColumn("T1130", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1130" }); Columns.Add(new DatabaseColumn("T1200", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1200" }); Columns.Add(new DatabaseColumn("T1230", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1230" }); Columns.Add(new DatabaseColumn("T1300", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1300" }); Columns.Add(new DatabaseColumn("T1330", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1330" }); Columns.Add(new DatabaseColumn("T1400", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1400" }); Columns.Add(new DatabaseColumn("T1430", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1430" }); Columns.Add(new DatabaseColumn("T1500", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1500" }); Columns.Add(new DatabaseColumn("T1530", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1530" }); Columns.Add(new DatabaseColumn("T1600", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1600" }); Columns.Add(new DatabaseColumn("T1630", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1630" }); Columns.Add(new DatabaseColumn("T1700", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1700" }); Columns.Add(new DatabaseColumn("T1730", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1730" }); Columns.Add(new DatabaseColumn("T1800", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1800" }); Columns.Add(new DatabaseColumn("T1830", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1830" }); Columns.Add(new DatabaseColumn("T1900", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1900" }); Columns.Add(new DatabaseColumn("T1930", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T1930" }); Columns.Add(new DatabaseColumn("T2000", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T2000" }); Columns.Add(new DatabaseColumn("T2030", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T2030" }); Columns.Add(new DatabaseColumn("T2100", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T2100" }); Columns.Add(new DatabaseColumn("T2130", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "T2130" }); } public IColumn Id{ get{ return this.GetColumn("Id"); } } public IColumn MeetingRoom_Code{ get{ return this.GetColumn("MeetingRoom_Code"); } } public IColumn MeetingRoom_Name{ get{ return this.GetColumn("MeetingRoom_Name"); } } public IColumn RoomDate{ get{ return this.GetColumn("RoomDate"); } } public IColumn T0800{ get{ return this.GetColumn("T0800"); } } public IColumn T0830{ get{ return this.GetColumn("T0830"); } } public IColumn T0900{ get{ return this.GetColumn("T0900"); } } public IColumn T0930{ get{ return this.GetColumn("T0930"); } } public IColumn T1000{ get{ return this.GetColumn("T1000"); } } public IColumn T1030{ get{ return this.GetColumn("T1030"); } } public IColumn T1100{ get{ return this.GetColumn("T1100"); } } public IColumn T1130{ get{ return this.GetColumn("T1130"); } } public IColumn T1200{ get{ return this.GetColumn("T1200"); } } public IColumn T1230{ get{ return this.GetColumn("T1230"); } } public IColumn T1300{ get{ return this.GetColumn("T1300"); } } public IColumn T1330{ get{ return this.GetColumn("T1330"); } } public IColumn T1400{ get{ return this.GetColumn("T1400"); } } public IColumn T1430{ get{ return this.GetColumn("T1430"); } } public IColumn T1500{ get{ return this.GetColumn("T1500"); } } public IColumn T1530{ get{ return this.GetColumn("T1530"); } } public IColumn T1600{ get{ return this.GetColumn("T1600"); } } public IColumn T1630{ get{ return this.GetColumn("T1630"); } } public IColumn T1700{ get{ return this.GetColumn("T1700"); } } public IColumn T1730{ get{ return this.GetColumn("T1730"); } } public IColumn T1800{ get{ return this.GetColumn("T1800"); } } public IColumn T1830{ get{ return this.GetColumn("T1830"); } } public IColumn T1900{ get{ return this.GetColumn("T1900"); } } public IColumn T1930{ get{ return this.GetColumn("T1930"); } } public IColumn T2000{ get{ return this.GetColumn("T2000"); } } public IColumn T2030{ get{ return this.GetColumn("T2030"); } } public IColumn T2100{ get{ return this.GetColumn("T2100"); } } public IColumn T2130{ get{ return this.GetColumn("T2130"); } } } }
// 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.Relay { 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> /// WCFRelaysOperations operations. /// </summary> public partial interface IWCFRelaysOperations { /// <summary> /// Lists the WCFRelays within the namespace. /// </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="ErrorResponseException"> /// 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<WcfRelay>>> ListByNamespaceWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or Updates a WCFRelay. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='parameters'> /// Parameters supplied to create a WCFRelays. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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<WcfRelay>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string relayName, WcfRelay parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a WCFRelays . /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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 relayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the description for the specified WCFRelays. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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<WcfRelay>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string relayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Authorization rules for a WCFRelays. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay 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<AuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string relayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or Updates an authorization rule for a WCFRelays /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// The authorization rule parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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<AuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, AuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a WCFRelays authorization rule /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay 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="ErrorResponseException"> /// 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 relayName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get authorizationRule for a WCFRelays by name. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay 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="ErrorResponseException"> /// 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<AuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Primary and Secondary ConnectionStrings to the WCFRelays. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay 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="ErrorResponseException"> /// 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<AuthorizationRuleKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the Primary or Secondary ConnectionStrings to the /// WCFRelays /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace Name /// </param> /// <param name='relayName'> /// The relay name /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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<AuthorizationRuleKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string relayName, string authorizationRuleName, RegenerateKeysParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the WCFRelays within the namespace. /// </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="ErrorResponseException"> /// 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<WcfRelay>>> ListByNamespaceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Authorization rules for a WCFRelays. /// </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<AuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.Pagination { public sealed class PaginationWithTotalCountTests : IClassFixture<IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext>> { private const string HostPrefix = "http://localhost"; private const int DefaultPageSize = 5; private readonly IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> _testContext; private readonly QueryStringFakers _fakers = new(); public PaginationWithTotalCountTests(IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> testContext) { _testContext = testContext; testContext.UseController<BlogPostsController>(); testContext.UseController<BlogsController>(); testContext.UseController<WebAccountsController>(); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.IncludeTotalResourceCount = true; options.DefaultPageSize = new PageSize(DefaultPageSize); options.MaximumPageSize = null; options.MaximumPageNumber = null; options.AllowUnknownQueryStringParameters = true; options.DisableTopPagination = false; options.DisableChildrenPagination = false; } [Fact] public async Task Can_paginate_in_primary_resources() { // Arrange List<BlogPost> posts = _fakers.BlogPost.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BlogPost>(); dbContext.Posts.AddRange(posts); await dbContext.SaveChangesAsync(); }); const string route = "/blogPosts?page[number]=2&page[size]=1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(posts[1].StringId); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().Be($"{HostPrefix}/blogPosts?page[size]=1"); responseDocument.Links.Last.Should().Be(responseDocument.Links.Self); responseDocument.Links.Prev.Should().Be(responseDocument.Links.First); responseDocument.Links.Next.Should().BeNull(); } [Fact] public async Task Cannot_paginate_in_single_primary_endpoint() { // Arrange BlogPost post = _fakers.BlogPost.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Posts.Add(post); await dbContext.SaveChangesAsync(); }); string route = $"/blogPosts/{post.StringId}?page[number]=2"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("The specified paging is invalid."); error.Detail.Should().Be("This query string parameter can only be used on a collection of resources (not on a single resource)."); error.Source.Parameter.Should().Be("page[number]"); } [Fact] public async Task Can_paginate_in_secondary_resources() { // Arrange Blog blog = _fakers.Blog.Generate(); blog.Posts = _fakers.BlogPost.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Blogs.Add(blog); await dbContext.SaveChangesAsync(); }); string route = $"/blogs/{blog.StringId}/posts?page[number]=2&page[size]=1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(blog.Posts[1].StringId); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().Be($"{HostPrefix}/blogs/{blog.StringId}/posts?page[size]=1"); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().Be(responseDocument.Links.First); responseDocument.Links.Next.Should().Be($"{HostPrefix}/blogs/{blog.StringId}/posts?page[number]=3&page[size]=1"); } [Fact] public async Task Cannot_paginate_in_single_secondary_endpoint() { // Arrange BlogPost post = _fakers.BlogPost.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Posts.Add(post); await dbContext.SaveChangesAsync(); }); string route = $"/blogPosts/{post.StringId}/author?page[size]=5"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("The specified paging is invalid."); error.Detail.Should().Be("This query string parameter can only be used on a collection of resources (not on a single resource)."); error.Source.Parameter.Should().Be("page[size]"); } [Fact] public async Task Can_paginate_in_scope_of_OneToMany_relationship() { // Arrange List<Blog> blogs = _fakers.Blog.Generate(3); blogs[0].Posts = _fakers.BlogPost.Generate(2); blogs[1].Posts = _fakers.BlogPost.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Blog>(); dbContext.Blogs.AddRange(blogs); await dbContext.SaveChangesAsync(); }); const string route = "/blogs?include=posts&page[number]=posts:2&page[size]=2,posts:1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Included.Should().HaveCount(2); responseDocument.Included[0].Id.Should().Be(blogs[0].Posts[1].StringId); responseDocument.Included[1].Id.Should().Be(blogs[1].Posts[1].StringId); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().Be($"{HostPrefix}/blogs?include=posts&page[size]=2,posts:1"); responseDocument.Links.Last.Should().Be($"{HostPrefix}/blogs?include=posts&page[number]=2&page[size]=2,posts:1"); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().Be(responseDocument.Links.Last); } [Fact] public async Task Can_paginate_in_scope_of_OneToMany_relationship_on_secondary_endpoint() { // Arrange Blog blog = _fakers.Blog.Generate(); blog.Owner = _fakers.WebAccount.Generate(); blog.Owner.Posts = _fakers.BlogPost.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Blogs.Add(blog); await dbContext.SaveChangesAsync(); }); string route = $"/blogs/{blog.StringId}/owner?include=posts&page[number]=posts:2&page[size]=posts:1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Id.Should().Be(blog.Owner.Posts[1].StringId); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().BeNull(); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); } [Fact] public async Task Can_paginate_OneToMany_relationship_on_relationship_endpoint() { // Arrange Blog blog = _fakers.Blog.Generate(); blog.Posts = _fakers.BlogPost.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Blogs.Add(blog); await dbContext.SaveChangesAsync(); }); string route = $"/blogs/{blog.StringId}/relationships/posts?page[number]=2&page[size]=1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(blog.Posts[1].StringId); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().Be($"{HostPrefix}/blogs/{blog.StringId}/relationships/posts?page[size]=1"); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().Be(responseDocument.Links.First); responseDocument.Links.Next.Should().BeNull(); } [Fact] public async Task Can_paginate_in_scope_of_ManyToMany_relationship() { // Arrange List<BlogPost> posts = _fakers.BlogPost.Generate(2); posts[0].Labels = _fakers.Label.Generate(2).ToHashSet(); posts[1].Labels = _fakers.Label.Generate(2).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BlogPost>(); dbContext.Posts.AddRange(posts); await dbContext.SaveChangesAsync(); }); // Workaround for https://github.com/dotnet/efcore/issues/21026 var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.DisableTopPagination = true; options.DisableChildrenPagination = false; const string route = "/blogPosts?include=labels&page[number]=labels:2&page[size]=labels:1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Included.Should().HaveCount(2); responseDocument.Included[0].Id.Should().Be(posts[0].Labels.ElementAt(1).StringId); responseDocument.Included[1].Id.Should().Be(posts[1].Labels.ElementAt(1).StringId); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().Be($"{HostPrefix}/blogPosts?include=labels&page[size]=labels:1"); responseDocument.Links.Last.Should().Be(responseDocument.Links.First); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); } [Fact] public async Task Can_paginate_ManyToMany_relationship_on_relationship_endpoint() { // Arrange BlogPost post = _fakers.BlogPost.Generate(); post.Labels = _fakers.Label.Generate(2).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BlogPost>(); dbContext.Posts.Add(post); await dbContext.SaveChangesAsync(); }); string route = $"/blogPosts/{post.StringId}/relationships/labels?page[number]=2&page[size]=1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(post.Labels.ElementAt(1).StringId); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().Be($"{HostPrefix}/blogPosts/{post.StringId}/relationships/labels?page[size]=1"); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().Be(responseDocument.Links.First); responseDocument.Links.Next.Should().BeNull(); } [Fact] public async Task Can_paginate_in_multiple_scopes() { // Arrange List<Blog> blogs = _fakers.Blog.Generate(2); blogs[1].Owner = _fakers.WebAccount.Generate(); blogs[1].Owner.Posts = _fakers.BlogPost.Generate(2); blogs[1].Owner.Posts[1].Comments = _fakers.Comment.Generate(2).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Blog>(); dbContext.Blogs.AddRange(blogs); await dbContext.SaveChangesAsync(); }); const string route = "/blogs?include=owner.posts.comments&page[size]=1,owner.posts:1,owner.posts.comments:1&" + "page[number]=2,owner.posts:2,owner.posts.comments:2"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(blogs[1].StringId); responseDocument.Included.Should().HaveCount(3); responseDocument.Included[0].Id.Should().Be(blogs[1].Owner.StringId); responseDocument.Included[1].Id.Should().Be(blogs[1].Owner.Posts[1].StringId); responseDocument.Included[2].Id.Should().Be(blogs[1].Owner.Posts[1].Comments.ElementAt(1).StringId); string linkPrefix = $"{HostPrefix}/blogs?include=owner.posts.comments"; responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().Be($"{linkPrefix}&page[size]=1,owner.posts:1,owner.posts.comments:1"); responseDocument.Links.Last.Should().Be($"{linkPrefix}&page[size]=1,owner.posts:1,owner.posts.comments:1&page[number]=2"); responseDocument.Links.Prev.Should().Be(responseDocument.Links.First); responseDocument.Links.Next.Should().BeNull(); } [Fact] public async Task Cannot_paginate_in_unknown_scope() { // Arrange string route = $"/webAccounts?page[number]={Unknown.Relationship}:1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("The specified paging is invalid."); error.Detail.Should().Be($"Relationship '{Unknown.Relationship}' does not exist on resource 'webAccounts'."); error.Source.Parameter.Should().Be("page[number]"); } [Fact] public async Task Cannot_paginate_in_unknown_nested_scope() { // Arrange string route = $"/webAccounts?page[size]=posts.{Unknown.Relationship}:1"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("The specified paging is invalid."); error.Detail.Should().Be($"Relationship '{Unknown.Relationship}' in 'posts.{Unknown.Relationship}' does not exist on resource 'blogPosts'."); error.Source.Parameter.Should().Be("page[size]"); } [Fact] public async Task Uses_default_page_number_and_size() { // Arrange var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.DefaultPageSize = new PageSize(2); Blog blog = _fakers.Blog.Generate(); blog.Posts = _fakers.BlogPost.Generate(3); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Blogs.Add(blog); await dbContext.SaveChangesAsync(); }); string route = $"/blogs/{blog.StringId}/posts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(blog.Posts[0].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(blog.Posts[1].StringId); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().Be(responseDocument.Links.Self); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().Be($"{HostPrefix}/blogs/{blog.StringId}/posts?page[number]=2"); } [Fact] public async Task Returns_all_resources_when_paging_is_disabled() { // Arrange var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.DefaultPageSize = null; Blog blog = _fakers.Blog.Generate(); blog.Posts = _fakers.BlogPost.Generate(25); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Blogs.Add(blog); await dbContext.SaveChangesAsync(); }); string route = $"/blogs/{blog.StringId}/posts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(25); responseDocument.Links.Should().NotBeNull(); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); responseDocument.Links.First.Should().BeNull(); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); } [Theory] [InlineData(1, 1, 4, null, 2)] [InlineData(2, 1, 4, 1, 3)] [InlineData(3, 1, 4, 2, 4)] [InlineData(4, 1, 4, 3, null)] public async Task Renders_correct_top_level_links_for_page_number(int pageNumber, int? firstLink, int? lastLink, int? prevLink, int? nextLink) { // Arrange WebAccount account = _fakers.WebAccount.Generate(); account.UserName = $"&{account.UserName}"; const int totalCount = 3 * DefaultPageSize + 3; List<BlogPost> posts = _fakers.BlogPost.Generate(totalCount); foreach (BlogPost post in posts) { post.Author = account; } await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BlogPost>(); dbContext.Posts.AddRange(posts); await dbContext.SaveChangesAsync(); }); string routePrefix = $"/blogPosts?filter=equals(author.userName,'{WebUtility.UrlEncode(account.UserName)}')" + "&fields[webAccounts]=userName&include=author&sort=id&foo=bar,baz"; string route = $"{routePrefix}&page[number]={pageNumber}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}"); if (firstLink != null) { string expected = $"{HostPrefix}{SetPageNumberInUrl(routePrefix, firstLink.Value)}"; responseDocument.Links.First.Should().Be(expected); } else { responseDocument.Links.First.Should().BeNull(); } if (prevLink != null) { string expected = $"{HostPrefix}{SetPageNumberInUrl(routePrefix, prevLink.Value)}"; responseDocument.Links.Prev.Should().Be(expected); } else { responseDocument.Links.Prev.Should().BeNull(); } if (nextLink != null) { string expected = $"{HostPrefix}{SetPageNumberInUrl(routePrefix, nextLink.Value)}"; responseDocument.Links.Next.Should().Be(expected); } else { responseDocument.Links.Next.Should().BeNull(); } if (lastLink != null) { string expected = $"{HostPrefix}{SetPageNumberInUrl(routePrefix, lastLink.Value)}"; responseDocument.Links.Last.Should().Be(expected); } else { responseDocument.Links.Last.Should().BeNull(); } static string SetPageNumberInUrl(string url, int pageNumber) { return pageNumber != 1 ? $"{url}&page[number]={pageNumber}" : url; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using System.Threading; using NUnit.Framework; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Development; using osu.Framework.Threading; namespace osu.Framework.Tests.Audio { [TestFixture] public class TrackVirtualTest { private TrackVirtual track; [SetUp] public void Setup() { track = new TrackVirtual(60000); updateTrack(); } [Test] public void TestStart() { track.Start(); updateTrack(); Thread.Sleep(50); updateTrack(); Assert.IsTrue(track.IsRunning); Assert.Greater(track.CurrentTime, 0); } [Test] public void TestStartZeroLength() { // override default with custom length track = new TrackVirtual(0); track.Start(); updateTrack(); Thread.Sleep(50); Assert.IsTrue(!track.IsRunning); Assert.AreEqual(0, track.CurrentTime); } [Test] public void TestStop() { track.Start(); track.Stop(); updateTrack(); Assert.IsFalse(track.IsRunning); double expectedTime = track.CurrentTime; Thread.Sleep(50); Assert.AreEqual(expectedTime, track.CurrentTime); } [Test] public void TestStopAtEnd() { startPlaybackAt(track.Length - 1); Thread.Sleep(50); updateTrack(); track.Stop(); updateTrack(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(track.Length, track.CurrentTime); } [Test] public void TestStopWhenDisposed() { startPlaybackAt(0); Thread.Sleep(50); updateTrack(); Assert.IsTrue(track.IsAlive); Assert.IsTrue(track.IsRunning); track.Dispose(); updateTrack(); Assert.IsFalse(track.IsAlive); Assert.IsFalse(track.IsRunning); double expectedTime = track.CurrentTime; Thread.Sleep(50); Assert.AreEqual(expectedTime, track.CurrentTime); } [Test] public void TestSeek() { track.Seek(1000); updateTrack(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(1000, track.CurrentTime); } [Test] public void TestSeekWhileRunning() { track.Start(); track.Seek(1000); updateTrack(); Assert.IsTrue(track.IsRunning); Assert.GreaterOrEqual(track.CurrentTime, 1000); } [Test] public void TestSeekBackToSamePosition() { track.Seek(1000); track.Seek(0); updateTrack(); Thread.Sleep(50); updateTrack(); Assert.GreaterOrEqual(track.CurrentTime, 0); Assert.Less(track.CurrentTime, 1000); } [Test] public void TestPlaybackToEnd() { startPlaybackAt(track.Length - 1); Thread.Sleep(50); updateTrack(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(track.Length, track.CurrentTime); } /// <summary> /// Bass restarts the track from the beginning if Start is called when the track has been completed. /// This is blocked locally in <see cref="TrackVirtual"/>, so this test expects the track to not restart. /// </summary> [Test] public void TestStartFromEndDoesNotRestart() { startPlaybackAt(track.Length - 1); Thread.Sleep(50); updateTrack(); track.Start(); updateTrack(); Assert.AreEqual(track.Length, track.CurrentTime); } [Test] public void TestRestart() { startPlaybackAt(1000); Thread.Sleep(50); updateTrack(); restartTrack(); Assert.IsTrue(track.IsRunning); Assert.Less(track.CurrentTime, 1000); } [Test] public void TestRestartAtEnd() { startPlaybackAt(track.Length - 1); Thread.Sleep(50); updateTrack(); restartTrack(); Assert.IsTrue(track.IsRunning); Assert.LessOrEqual(track.CurrentTime, 1000); } [Test] public void TestRestartFromRestartPoint() { track.RestartPoint = 1000; startPlaybackAt(3000); restartTrack(); Assert.IsTrue(track.IsRunning); Assert.GreaterOrEqual(track.CurrentTime, 1000); Assert.Less(track.CurrentTime, 3000); } [Test] public void TestLoopingRestart() { track.Looping = true; startPlaybackAt(track.Length - 1); Thread.Sleep(50); // The first update brings the track to its end time and restarts it updateTrack(); // The second update updates the IsRunning state updateTrack(); // In a perfect world the track will be running after the update above, but during testing it's possible that the track is in // a stalled state due to updates running on Bass' own thread, so we'll loop until the track starts running again // Todo: This should be fixed in the future if/when we invoke Bass.Update() ourselves int loopCount = 0; while (++loopCount < 50 && !track.IsRunning) { updateTrack(); Thread.Sleep(10); } if (loopCount == 50) throw new TimeoutException("Track failed to start in time."); Assert.LessOrEqual(track.CurrentTime, 1000); } [Test] public void TestSetTempoNegative() { Assert.IsFalse(track.IsReversed); track.Tempo.Value = 0.05f; Assert.IsFalse(track.IsReversed); Assert.AreEqual(0.05f, track.Tempo.Value); } [Test] public void TestRateWithAggregateTempoAdjustments() { track.AddAdjustment(AdjustableProperty.Tempo, new BindableDouble(1.5f)); Assert.AreEqual(1.5, track.Rate); testPlaybackRate(1.5); } [Test] public void TestRateWithAggregateFrequencyAdjustments() { track.AddAdjustment(AdjustableProperty.Frequency, new BindableDouble(1.5f)); Assert.AreEqual(1.5, track.Rate); testPlaybackRate(1.5); } [Test] public void TestCurrentTimeUpdatedAfterInlineSeek() { track.Start(); updateTrack(); RunOnAudioThread(() => track.Seek(20000)); Assert.That(track.CurrentTime, Is.EqualTo(20000).Within(100)); } [Test] public void TestSeekToCurrentTime() { track.Seek(5000); bool seekSucceeded = false; RunOnAudioThread(() => seekSucceeded = track.Seek(track.CurrentTime)); Assert.That(seekSucceeded, Is.True); Assert.That(track.CurrentTime, Is.EqualTo(5000)); } [Test] public void TestSeekBeyondStartTime() { bool seekSucceeded = false; RunOnAudioThread(() => seekSucceeded = track.Seek(-1000)); Assert.That(seekSucceeded, Is.False); Assert.That(track.CurrentTime, Is.EqualTo(0)); } [Test] public void TestSeekBeyondEndTime() { bool seekSucceeded = false; RunOnAudioThread(() => seekSucceeded = track.Seek(track.Length + 1000)); Assert.That(seekSucceeded, Is.False); Assert.That(track.CurrentTime, Is.EqualTo(track.Length)); } private void testPlaybackRate(double expectedRate) { const double play_time = 1000; const double fudge = play_time * 0.1; track.Start(); var sw = new Stopwatch(); sw.Start(); while (sw.ElapsedMilliseconds < play_time) { Thread.Sleep(50); track.Update(); } sw.Stop(); Assert.GreaterOrEqual(track.CurrentTime, sw.ElapsedMilliseconds * expectedRate - fudge); Assert.LessOrEqual(track.CurrentTime, sw.ElapsedMilliseconds * expectedRate + fudge); } private void startPlaybackAt(double time) { track.Seek(time); track.Start(); updateTrack(); } private void updateTrack() => RunOnAudioThread(() => track.Update()); private void restartTrack() { RunOnAudioThread(() => { track.Restart(); track.Update(); }); } /// <summary> /// Certain actions are invoked on the audio thread. /// Here we simulate this process on a correctly named thread to avoid endless blocking. /// </summary> /// <param name="action">The action to perform.</param> public static void RunOnAudioThread(Action action) { var resetEvent = new ManualResetEvent(false); new Thread(() => { ThreadSafety.IsAudioThread = true; action(); resetEvent.Set(); }) { Name = GameThread.PrefixedThreadNameFor("Audio") }.Start(); if (!resetEvent.WaitOne(TimeSpan.FromSeconds(10))) throw new TimeoutException(); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: client/conf_test_enum.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace UF.Config { /// <summary>Holder for reflection information generated from client/conf_test_enum.proto</summary> public static partial class ConfTestEnumReflection { #region Descriptor /// <summary>File descriptor for client/conf_test_enum.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ConfTestEnumReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChtjbGllbnQvY29uZl90ZXN0X2VudW0ucHJvdG8SBmNsaWVudBoZY29tbW9u", "L2VudW1fbW9kdWxlcy5wcm90byJ+CgxDb25mVGVzdEVudW0SDwoHaW50ZWdl", "chgBIAEoBRIOCgZhcnJheXMYAiADKAUSJQoMbW9kdWxlc0VudW1zGAMgAygO", "Mg8uY29tbW9uLk1vZHVsZXMSJgoNbW9kdWVsc0VudW1zMhgEIAMoDjIPLmNv", "bW1vbi5Nb2R1bGVzQgyqAglVRi5Db25maWdiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::UF.Config.EnumModulesReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UF.Config.ConfTestEnum), global::UF.Config.ConfTestEnum.Parser, new[]{ "Integer", "Arrays", "ModulesEnums", "ModuelsEnums2" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ConfTestEnum : pb::IMessage<ConfTestEnum> { private static readonly pb::MessageParser<ConfTestEnum> _parser = new pb::MessageParser<ConfTestEnum>(() => new ConfTestEnum()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConfTestEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::UF.Config.ConfTestEnumReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConfTestEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConfTestEnum(ConfTestEnum other) : this() { integer_ = other.integer_; arrays_ = other.arrays_.Clone(); modulesEnums_ = other.modulesEnums_.Clone(); moduelsEnums2_ = other.moduelsEnums2_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConfTestEnum Clone() { return new ConfTestEnum(this); } /// <summary>Field number for the "integer" field.</summary> public const int IntegerFieldNumber = 1; private int integer_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Integer { get { return integer_; } set { integer_ = value; } } /// <summary>Field number for the "arrays" field.</summary> public const int ArraysFieldNumber = 2; private static readonly pb::FieldCodec<int> _repeated_arrays_codec = pb::FieldCodec.ForInt32(18); private readonly pbc::RepeatedField<int> arrays_ = new pbc::RepeatedField<int>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<int> Arrays { get { return arrays_; } } /// <summary>Field number for the "modulesEnums" field.</summary> public const int ModulesEnumsFieldNumber = 3; private static readonly pb::FieldCodec<global::UF.Config.Modules> _repeated_modulesEnums_codec = pb::FieldCodec.ForEnum(26, x => (int) x, x => (global::UF.Config.Modules) x); private readonly pbc::RepeatedField<global::UF.Config.Modules> modulesEnums_ = new pbc::RepeatedField<global::UF.Config.Modules>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::UF.Config.Modules> ModulesEnums { get { return modulesEnums_; } } /// <summary>Field number for the "moduelsEnums2" field.</summary> public const int ModuelsEnums2FieldNumber = 4; private static readonly pb::FieldCodec<global::UF.Config.Modules> _repeated_moduelsEnums2_codec = pb::FieldCodec.ForEnum(34, x => (int) x, x => (global::UF.Config.Modules) x); private readonly pbc::RepeatedField<global::UF.Config.Modules> moduelsEnums2_ = new pbc::RepeatedField<global::UF.Config.Modules>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::UF.Config.Modules> ModuelsEnums2 { get { return moduelsEnums2_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConfTestEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConfTestEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Integer != other.Integer) return false; if(!arrays_.Equals(other.arrays_)) return false; if(!modulesEnums_.Equals(other.modulesEnums_)) return false; if(!moduelsEnums2_.Equals(other.moduelsEnums2_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Integer != 0) hash ^= Integer.GetHashCode(); hash ^= arrays_.GetHashCode(); hash ^= modulesEnums_.GetHashCode(); hash ^= moduelsEnums2_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Integer != 0) { output.WriteRawTag(8); output.WriteInt32(Integer); } arrays_.WriteTo(output, _repeated_arrays_codec); modulesEnums_.WriteTo(output, _repeated_modulesEnums_codec); moduelsEnums2_.WriteTo(output, _repeated_moduelsEnums2_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Integer != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Integer); } size += arrays_.CalculateSize(_repeated_arrays_codec); size += modulesEnums_.CalculateSize(_repeated_modulesEnums_codec); size += moduelsEnums2_.CalculateSize(_repeated_moduelsEnums2_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConfTestEnum other) { if (other == null) { return; } if (other.Integer != 0) { Integer = other.Integer; } arrays_.Add(other.arrays_); modulesEnums_.Add(other.modulesEnums_); moduelsEnums2_.Add(other.moduelsEnums2_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Integer = input.ReadInt32(); break; } case 18: case 16: { arrays_.AddEntriesFrom(input, _repeated_arrays_codec); break; } case 26: case 24: { modulesEnums_.AddEntriesFrom(input, _repeated_modulesEnums_codec); break; } case 34: case 32: { moduelsEnums2_.AddEntriesFrom(input, _repeated_moduelsEnums2_codec); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Graph.RBAC.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Graph.RBAC.Fluent.ActiveDirectoryApplication.Definition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.ActiveDirectoryApplication.Update; using Microsoft.Azure.Management.Graph.RBAC.Fluent.CertificateCredential.Definition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.CertificateCredential.UpdateDefinition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.PasswordCredential.Definition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.PasswordCredential.UpdateDefinition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using System.Collections.Generic; public partial class ActiveDirectoryApplicationImpl { /// <summary> /// Removes a reply URL. /// </summary> /// <param name="replyUrl">The reply URL to remove.</param> /// <return>The next stage in application update.</return> ActiveDirectoryApplication.Update.IUpdate ActiveDirectoryApplication.Update.IWithReplyUrl.WithoutReplyUrl(string replyUrl) { return this.WithoutReplyUrl(replyUrl); } /// <summary> /// Adds a reply URL to the application. /// </summary> /// <param name="replyUrl">URIs to which Azure AD will redirect in response to an OAuth 2.0 request.</param> /// <return>The next stage in application update.</return> ActiveDirectoryApplication.Update.IUpdate ActiveDirectoryApplication.Update.IWithReplyUrl.WithReplyUrl(string replyUrl) { return this.WithReplyUrl(replyUrl); } /// <summary> /// Adds a reply URL to the application. /// </summary> /// <param name="replyUrl">URIs to which Azure AD will redirect in response to an OAuth 2.0 request.</param> /// <return>The next stage in application definition.</return> ActiveDirectoryApplication.Definition.IWithCreate ActiveDirectoryApplication.Definition.IWithReplyUrl.WithReplyUrl(string replyUrl) { return this.WithReplyUrl(replyUrl); } /// <summary> /// Specifies if the application can be used in multiple tenants. /// </summary> /// <param name="availableToOtherTenants">True if this application is available in other tenants.</param> /// <return>The next stage in application update.</return> ActiveDirectoryApplication.Update.IUpdate ActiveDirectoryApplication.Update.IWithMultiTenant.WithAvailableToOtherTenants(bool availableToOtherTenants) { return this.WithAvailableToOtherTenants(availableToOtherTenants); } /// <summary> /// Specifies if the application can be used in multiple tenants. /// </summary> /// <param name="availableToOtherTenants">True if this application is available in other tenants.</param> /// <return>The next stage in application definition.</return> ActiveDirectoryApplication.Definition.IWithCreate ActiveDirectoryApplication.Definition.IWithMultiTenant.WithAvailableToOtherTenants(bool availableToOtherTenants) { return this.WithAvailableToOtherTenants(availableToOtherTenants); } /// <summary> /// Specifies the sign on URL. /// </summary> /// <param name="signOnUrl">The URL where users can sign in and use this app.</param> /// <return>The next stage in application update.</return> ActiveDirectoryApplication.Update.IUpdate ActiveDirectoryApplication.Update.IWithSignOnUrl.WithSignOnUrl(string signOnUrl) { return this.WithSignOnUrl(signOnUrl); } /// <summary> /// Specifies the sign on URL. /// </summary> /// <param name="signOnUrl">The URL where users can sign in and use this app.</param> /// <return>The next stage in application definition.</return> ActiveDirectoryApplication.Definition.IWithCreate ActiveDirectoryApplication.Definition.IWithSignOnUrl.WithSignOnUrl(string signOnUrl) { return this.WithSignOnUrl(signOnUrl); } /// <summary> /// Attach a credential to this model. /// </summary> /// <param name="credential">The credential to attach to.</param> /// <return>The interface itself.</return> IWithCreate Microsoft.Azure.Management.Graph.RBAC.Fluent.IHasCredential<IWithCreate>.WithCertificateCredential(CertificateCredentialImpl<IWithCreate> credential) { return this.WithCertificateCredential(credential); } /// <summary> /// Attach a credential to this model. /// </summary> /// <param name="credential">The credential to attach to.</param> /// <return>The interface itself.</return> IUpdate Microsoft.Azure.Management.Graph.RBAC.Fluent.IHasCredential<IUpdate>.WithCertificateCredential(CertificateCredentialImpl<IUpdate> credential) { return this.WithCertificateCredential(credential); } /// <summary> /// Attach a credential to this model. /// </summary> /// <param name="credential">The credential to attach to.</param> /// <return>The interface itself.</return> IWithCreate Microsoft.Azure.Management.Graph.RBAC.Fluent.IHasCredential<IWithCreate>.WithPasswordCredential(PasswordCredentialImpl<IWithCreate> credential) { return this.WithPasswordCredential(credential); } /// <summary> /// Attach a credential to this model. /// </summary> /// <param name="credential">The credential to attach to.</param> /// <return>The interface itself.</return> IUpdate Microsoft.Azure.Management.Graph.RBAC.Fluent.IHasCredential<IUpdate>.WithPasswordCredential(PasswordCredentialImpl<IUpdate> credential) { return this.WithPasswordCredential(credential); } /// <summary> /// Starts the definition of a certificate credential. /// </summary> /// <param name="name">The descriptive name of the certificate credential.</param> /// <return>The first stage in certificate credential definition.</return> CertificateCredential.UpdateDefinition.IBlank<ActiveDirectoryApplication.Update.IUpdate> ActiveDirectoryApplication.Update.IWithCredential.DefineCertificateCredential(string name) { return this.DefineCertificateCredential<IUpdate>(name); } /// <summary> /// Removes a key. /// </summary> /// <param name="name">The name of the key.</param> /// <return>The next stage of the application update.</return> ActiveDirectoryApplication.Update.IUpdate ActiveDirectoryApplication.Update.IWithCredential.WithoutCredential(string name) { return this.WithoutCredential(name); } /// <summary> /// Starts the definition of a password credential. /// </summary> /// <param name="name">The descriptive name of the password credential.</param> /// <return>The first stage in password credential definition.</return> PasswordCredential.UpdateDefinition.IBlank<ActiveDirectoryApplication.Update.IUpdate> ActiveDirectoryApplication.Update.IWithCredential.DefinePasswordCredential(string name) { return this.DefinePasswordCredential<IUpdate>(name); } /// <summary> /// Starts the definition of a certificate credential. /// </summary> /// <param name="name">The descriptive name of the certificate credential.</param> /// <return>The first stage in certificate credential definition.</return> CertificateCredential.Definition.IBlank<ActiveDirectoryApplication.Definition.IWithCreate> ActiveDirectoryApplication.Definition.IWithCredential.DefineCertificateCredential(string name) { return this.DefineCertificateCredential<IWithCreate>(name); } /// <summary> /// Starts the definition of a password credential. /// </summary> /// <param name="name">The descriptive name of the password credential.</param> /// <return>The first stage in password credential definition.</return> PasswordCredential.Definition.IBlank<ActiveDirectoryApplication.Definition.IWithCreate> ActiveDirectoryApplication.Definition.IWithCredential.DefinePasswordCredential(string name) { return this.DefinePasswordCredential<IWithCreate>(name); } /// <summary> /// Adds an identifier URL to the application. /// </summary> /// <param name="identifierUrl">Unique URI that Azure AD can use for this app.</param> /// <return>The next stage in application update.</return> ActiveDirectoryApplication.Update.IUpdate ActiveDirectoryApplication.Update.IWithIdentifierUrl.WithIdentifierUrl(string identifierUrl) { return this.WithIdentifierUrl(identifierUrl); } /// <summary> /// Removes an identifier URL from the application. /// </summary> /// <param name="identifierUrl">Identifier URI to remove.</param> /// <return>The next stage in application update.</return> ActiveDirectoryApplication.Update.IUpdate ActiveDirectoryApplication.Update.IWithIdentifierUrl.WithoutIdentifierUrl(string identifierUrl) { return this.WithoutIdentifierUrl(identifierUrl); } /// <summary> /// Adds an identifier URL to the application. /// </summary> /// <param name="identifierUrl">Unique URI that Azure AD can use for this app.</param> /// <return>The next stage in application definition.</return> ActiveDirectoryApplication.Definition.IWithCreate ActiveDirectoryApplication.Definition.IWithIdentifierUrl.WithIdentifierUrl(string identifierUrl) { return this.WithIdentifierUrl(identifierUrl); } /// <summary> /// Gets the application permissions. /// </summary> System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication.ApplicationPermissions { get { return this.ApplicationPermissions(); } } /// <summary> /// Gets a collection of URIs for the application. /// </summary> System.Collections.Generic.ISet<string> Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication.IdentifierUris { get { return this.IdentifierUris(); } } /// <summary> /// Gets the application ID. /// </summary> string Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication.ApplicationId { get { return this.ApplicationId(); } } /// <summary> /// Gets the mapping of certificate credentials from their names. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, Microsoft.Azure.Management.Graph.RBAC.Fluent.ICertificateCredential> Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication.CertificateCredentials { get { return this.CertificateCredentials(); } } /// <summary> /// Gets a collection of reply URLs for the application. /// </summary> System.Collections.Generic.ISet<string> Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication.ReplyUrls { get { return this.ReplyUrls(); } } /// <summary> /// Gets whether the application is be available to other tenants. /// </summary> bool Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication.AvailableToOtherTenants { get { return this.AvailableToOtherTenants(); } } /// <summary> /// Gets the home page of the application. /// </summary> System.Uri Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication.SignOnUrl { get { return this.SignOnUrl(); } } /// <summary> /// Gets the mapping of password credentials from their names. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, Microsoft.Azure.Management.Graph.RBAC.Fluent.IPasswordCredential> Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication.PasswordCredentials { get { return this.PasswordCredentials(); } } } }
/* * Copyright 2012 JetBrains * * 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 EnvDTE; using JetBrains.Application.Components; using JetBrains.DataFlow; using JetBrains.ProjectModel; using JetBrains.Threading; using JetBrains.Util; #if RESHARPER_8 using JetBrains.Util.Logging; #endif using JetBrains.VsIntegration.ProjectModel; using Microsoft.VisualStudio.ComponentModelHost; using NuGet.VisualStudio; using System.Linq; namespace JetBrains.ReSharper.Plugins.NuGet { // We depend on IComponentModel, which lives in a VS assembly, so tell ReSharper // that we can only load as part of a VS addin [SolutionComponent(ProgramConfigurations.VS_ADDIN)] public class NuGetApi { private readonly ISolution solution; private readonly IThreading threading; private readonly ProjectModelSynchronizer projectModelSynchronizer; private readonly IVsPackageInstallerServices vsPackageInstallerServices; private readonly IVsPackageInstaller vsPackageInstaller; private readonly IVsPackageInstallerEvents vsPackageInstallerEvents; private readonly object syncObject = new object(); private ILookup<string, FileSystemPath> installedPackages; // there can be several versions of one package (different versions) private static readonly ILookup<string, FileSystemPath> emptyLookup = ToLookup(EmptyList<IVsPackageMetadata>.InstanceList); public NuGetApi(ISolution solution, Lifetime lifetime, IComponentModel componentModel, IThreading threading, ProjectModelSynchronizer projectModelSynchronizer) { this.solution = solution; this.threading = threading; this.projectModelSynchronizer = projectModelSynchronizer; try { vsPackageInstallerServices = componentModel.GetExtensions<IVsPackageInstallerServices>().SingleOrDefault(); vsPackageInstaller = componentModel.GetExtensions<IVsPackageInstaller>().SingleOrDefault(); vsPackageInstallerEvents = componentModel.GetExtensions<IVsPackageInstallerEvents>().SingleOrDefault(); } catch (Exception e) { Logger.LogException("Unable to get NuGet interfaces.", e); } if (!IsNuGetAvailable) { Logger.LogMessage(LoggingLevel.VERBOSE, "[NUGET PLUGIN] Unable to get NuGet interfaces. No exception thrown"); return; } lifetime.AddBracket( () => vsPackageInstallerEvents.PackageInstalled += RecalcInstalledPackages, () => vsPackageInstallerEvents.PackageInstalled -= RecalcInstalledPackages); lifetime.AddBracket( () => vsPackageInstallerEvents.PackageUninstalled += RecalcInstalledPackages, () => vsPackageInstallerEvents.PackageUninstalled -= RecalcInstalledPackages); RecalcInstalledPackages(null); } private static ILookup<string, FileSystemPath> ToLookup(IEnumerable<IVsPackageMetadata> packages) { return packages.ToLookup(_ => _.Id, _ => new FileSystemPath(_.InstallPath), StringComparer.OrdinalIgnoreCase); } private void RecalcInstalledPackages(IVsPackageMetadata metadata) { if (!IsNuGetAvailable || solution.IsTemporary) { lock (syncObject) { installedPackages = emptyLookup; } return; } try { lock (syncObject) { installedPackages = ToLookup(vsPackageInstallerServices.GetInstalledPackages()); } } catch (Exception ex) { installedPackages = emptyLookup; Logger.LogException("RecalcInstalledPackages", ex); } } private bool IsNuGetAvailable { get { return vsPackageInstallerServices != null && vsPackageInstaller != null && vsPackageInstallerEvents!= null; } } public bool AreAnyAssemblyFilesNuGetPackages(IList<FileSystemPath> fileLocations) { if (!IsNuGetAvailable || fileLocations.Count == 0) return false; FileSystemPath installedLocation; var hasPackageAssembly = GetPackageFromAssemblyLocations(fileLocations, out installedLocation) != null; if (!hasPackageAssembly) LogNoPackageFound(fileLocations); return hasPackageAssembly; } // Yeah, that's an out parameter. Bite me. public bool InstallNuGetPackageFromAssemblyFiles(IList<FileSystemPath> assemblyLocations, IProject project, out FileSystemPath installedLocation) { installedLocation = FileSystemPath.Empty; if (!IsNuGetAvailable || assemblyLocations.Count == 0) return false; // We're talking to NuGet via COM. Make sure we're on the UI thread var location = FileSystemPath.Empty; var handled = false; threading.Dispatcher.Invoke("NuGet", () => { handled = DoInstallAssemblyAsNuGetPackage(assemblyLocations, project, out location); }); installedLocation = location; return handled; } private bool DoInstallAssemblyAsNuGetPackage(IList<FileSystemPath> assemblyLocations, IProject project, out FileSystemPath installedLocation) { var handled = false; installedLocation = FileSystemPath.Empty; try { var vsProject = GetVsProject(project); if (vsProject != null) handled = DoInstallAssemblyAsNuGetPackage(assemblyLocations, vsProject, out installedLocation); } catch (Exception e) { // Something went wrong while trying to install a NuGet package. Don't // let the default module referencers add a file reference, so tell // ReSharper that we handled it Logger.LogException("Failed to install NuGet package", e); handled = true; } return handled; } private bool DoInstallAssemblyAsNuGetPackage(IList<FileSystemPath> assemblyLocations, Project vsProject, out FileSystemPath installedLocation) { var id = GetPackageFromAssemblyLocations(assemblyLocations, out installedLocation); if (id == null) { // Not a NuGet package, we didn't handle this LogNoPackageFound(assemblyLocations); return false; } // We need to get the repository path from the installed package. Sadly, this means knowing that // the package is installed one directory below the repository. Just a small crack in the black box. // (We can pass "All" as the package source, rather than the repository path, but that would give // us an aggregate of the current package sources, rather than using the local repo as a source) // Also, make sure we're dealing with a canonical path, in case the nuget.config has a repository // path defined as a relative path var repositoryPath = installedLocation.Directory; vsPackageInstaller.InstallPackage(repositoryPath.FullPath, vsProject, id, default(string), false); // Successfully installed, we handled it return true; } private void LogNoPackageFound(IEnumerable<FileSystemPath> assemblyLocations) { if (!Logger.IsLoggingEnabled) return; var assemblies = assemblyLocations.AggregateString(", ", (builder, arg) => builder.Append(arg.QuoteIfNeeded())); Logger.LogMessage(LoggingLevel.VERBOSE, "[NUGET PLUGIN] No package found for assemblies: {0}", assemblies); } private string GetPackageFromAssemblyLocations(IList<FileSystemPath> assemblyLocations, out FileSystemPath installedLocation) { lock (syncObject) { installedLocation = FileSystemPath.Empty; foreach (var installedPackage in installedPackages) foreach (var installedPackageLocation in installedPackage) foreach (var assemblyLocation in assemblyLocations) { if (installedPackageLocation.IsPrefixOf(assemblyLocation)) { installedLocation = installedPackageLocation; return installedPackage.Key; } } return null; } } private Project GetVsProject(IProject project) { var projectInfo = projectModelSynchronizer.GetProjectInfoByProject(project); return projectInfo != null ? projectInfo.GetExtProject() : null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Web.Security; using Newtonsoft.Json; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Factories; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Relators; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Security; namespace Umbraco.Core.Persistence.Repositories { /// <summary> /// Represents the UserRepository for doing CRUD operations for <see cref="IUser"/> /// </summary> internal class UserRepository : PetaPocoRepositoryBase<int, IUser>, IUserRepository { private readonly IDictionary<string, string> _passwordConfiguration; /// <summary> /// Constructor /// </summary> /// <param name="work"></param> /// <param name="cacheHelper"></param> /// <param name="logger"></param> /// <param name="sqlSyntax"></param> /// <param name="passwordConfiguration"> /// A dictionary specifying the configuration for user passwords. If this is null then no password configuration will be persisted or read. /// </param> public UserRepository(IScopeUnitOfWork work, CacheHelper cacheHelper, ILogger logger, ISqlSyntaxProvider sqlSyntax, IDictionary<string, string> passwordConfiguration = null) : base(work, cacheHelper, logger, sqlSyntax) { _passwordConfiguration = passwordConfiguration; } #region Overrides of RepositoryBase<int,IUser> protected override IUser PerformGet(int id) { var sql = GetQueryWithGroups(); sql.Where(GetBaseWhereClause(), new { Id = id }); sql //must be included for relator to work .OrderBy<UserDto>(d => d.Id, SqlSyntax) .OrderBy<UserGroupDto>(d => d.Id, SqlSyntax) .OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax); var dto = Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql) .FirstOrDefault(); if (dto == null) return null; var user = UserFactory.BuildEntity(dto); return user; } /// <summary> /// Returns a user by username /// </summary> /// <param name="username"></param> /// <param name="includeSecurityData"> /// Can be used for slightly faster user lookups if the result doesn't require security data (i.e. groups, apps & start nodes). /// This is really only used for a shim in order to upgrade to 7.6. /// </param> /// <returns> /// A non cached <see cref="IUser"/> instance /// </returns> public IUser GetByUsername(string username, bool includeSecurityData) { UserDto dto; if (includeSecurityData) { var sql = GetQueryWithGroups(); sql.Where<UserDto>(userDto => userDto.Login == username, SqlSyntax); sql //must be included for relator to work .OrderBy<UserDto>(d => d.Id, SqlSyntax) .OrderBy<UserGroupDto>(d => d.Id, SqlSyntax) .OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax); dto = Database .Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>( new UserGroupRelator().Map, sql) .FirstOrDefault(); } else { var sql = GetBaseQuery("umbracoUser.*"); sql.Where<UserDto>(userDto => userDto.Login == username, SqlSyntax); dto = Database.FirstOrDefault<UserDto>(sql); } if (dto == null) return null; var user = UserFactory.BuildEntity(dto); return user; } /// <summary> /// Returns a user by id /// </summary> /// <param name="id"></param> /// <param name="includeSecurityData"> /// This is really only used for a shim in order to upgrade to 7.6 but could be used /// for slightly faster user lookups if the result doesn't require security data (i.e. groups, apps & start nodes) /// </param> /// <returns> /// A non cached <see cref="IUser"/> instance /// </returns> public IUser Get(int id, bool includeSecurityData) { UserDto dto; if (includeSecurityData) { var sql = GetQueryWithGroups(); sql.Where(GetBaseWhereClause(), new { Id = id }); sql //must be included for relator to work .OrderBy<UserDto>(d => d.Id, SqlSyntax) .OrderBy<UserGroupDto>(d => d.Id, SqlSyntax) .OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax); dto = Database .Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>( new UserGroupRelator().Map, sql) .FirstOrDefault(); } else { var sql = GetBaseQuery("umbracoUser.*"); sql.Where(GetBaseWhereClause(), new { Id = id }); dto = Database.FirstOrDefault<UserDto>(sql); } if (dto == null) return null; var user = UserFactory.BuildEntity(dto); return user; } public IProfile GetProfile(string username) { var sql = GetBaseQuery(false).Where<UserDto>(userDto => userDto.UserName == username, SqlSyntax); var dto = Database.Fetch<UserDto>(sql) .FirstOrDefault(); if (dto == null) return null; return new UserProfile(dto.Id, dto.UserName); } public IProfile GetProfile(int id) { var sql = GetBaseQuery(false).Where<UserDto>(userDto => userDto.Id == id, SqlSyntax); var dto = Database.Fetch<UserDto>(sql) .FirstOrDefault(); if (dto == null) return null; return new UserProfile(dto.Id, dto.UserName); } public IDictionary<UserState, int> GetUserStates() { var sql = @"SELECT '1CountOfAll' AS colName, COUNT(id) AS num FROM umbracoUser UNION SELECT '2CountOfActive' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NOT NULL UNION SELECT '3CountOfDisabled' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 1 UNION SELECT '4CountOfLockedOut' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userNoConsole = 1 UNION SELECT '5CountOfInvited' AS colName, COUNT(id) AS num FROM umbracoUser WHERE lastLoginDate IS NULL AND userDisabled = 1 AND invitedDate IS NOT NULL ORDER BY colName"; var result = Database.Fetch<dynamic>(sql); return new Dictionary<UserState, int> { {UserState.All, (int)result[0].num}, {UserState.Active, (int)result[1].num}, {UserState.Disabled, (int)result[2].num}, {UserState.LockedOut, (int)result[3].num}, {UserState.Invited, (int)result[4].num} }; } public Guid CreateLoginSession(int userId, string requestingIpAddress, bool cleanStaleSessions = true) { //TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository //and also business logic models for these objects but that's just so overkill for what we are doing //and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore var now = DateTime.UtcNow; var dto = new UserLoginDto { UserId = userId, IpAddress = requestingIpAddress, LoggedInUtc = now, LastValidatedUtc = now, LoggedOutUtc = null, SessionId = Guid.NewGuid() }; Database.Insert(dto); if (cleanStaleSessions) { ClearLoginSessions(TimeSpan.FromDays(15)); } return dto.SessionId; } public bool ValidateLoginSession(int userId, Guid sessionId) { var found = Database.FirstOrDefault<UserLoginDto>("WHERE sessionId=@sessionId", new {sessionId = sessionId}); if (found == null || found.UserId != userId || found.LoggedOutUtc.HasValue) return false; //now detect if there's been a timeout if (DateTime.UtcNow - found.LastValidatedUtc > TimeSpan.FromMinutes(GlobalSettings.TimeOutInMinutes)) { //timeout detected, update the record ClearLoginSession(sessionId); return false; } //update the validate date found.LastValidatedUtc = DateTime.UtcNow; Database.Update(found); return true; } public int ClearLoginSessions(int userId) { //TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository //and also business logic models for these objects but that's just so overkill for what we are doing //and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore var count = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoUserLogin WHERE userId=@userId", new { userId = userId }); Database.Execute("DELETE FROM umbracoUserLogin WHERE userId=@userId", new {userId = userId}); return count; } public int ClearLoginSessions(TimeSpan timespan) { //TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository //and also business logic models for these objects but that's just so overkill for what we are doing //and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore var fromDate = DateTime.UtcNow - timespan; var count = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoUserLogin WHERE lastValidatedUtc=@fromDate", new { fromDate = fromDate }); Database.Execute("DELETE FROM umbracoUserLogin WHERE lastValidatedUtc=@fromDate", new { fromDate = fromDate }); return count; } public void ClearLoginSession(Guid sessionId) { //TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository //and also business logic models for these objects but that's just so overkill for what we are doing //and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore Database.Execute("UPDATE umbracoUserLogin SET loggedOutUtc=@now WHERE sessionId=@sessionId", new { now = DateTime.UtcNow, sessionId = sessionId }); } protected override IEnumerable<IUser> PerformGetAll(params int[] ids) { var sql = GetQueryWithGroups(); if (ids.Any()) { sql.Where("umbracoUser.id in (@ids)", new { ids = ids }); } sql //must be included for relator to work .OrderBy<UserDto>(d => d.Id, SqlSyntax) .OrderBy<UserGroupDto>(d => d.Id, SqlSyntax) .OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax); var users = ConvertFromDtos(Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql)) .ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching. return users; } protected override IEnumerable<IUser> PerformGetByQuery(IQuery<IUser> query) { var sqlClause = GetQueryWithGroups(); var translator = new SqlTranslator<IUser>(sqlClause, query); var sql = translator.Translate(); sql //must be included for relator to work .OrderBy<UserDto>(d => d.Id, SqlSyntax) .OrderBy<UserGroupDto>(d => d.Id, SqlSyntax) .OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax); var dtos = Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql) .DistinctBy(x => x.Id); var users = ConvertFromDtos(dtos) .ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching. return users; } #endregion #region Overrides of PetaPocoRepositoryBase<int,IUser> protected override Sql GetBaseQuery(bool isCount) { var sql = new Sql(); if (isCount) { sql.Select("COUNT(*)").From<UserDto>(); } else { return GetBaseQuery("*"); } return sql; } /// <summary> /// A query to return a user with it's groups and with it's groups sections /// </summary> /// <returns></returns> private Sql GetQueryWithGroups() { //base query includes user groups var sql = GetBaseQuery("umbracoUser.*, umbracoUserGroup.*, umbracoUserGroup2App.*, umbracoUserStartNode.*"); AddGroupLeftJoin(sql); return sql; } private void AddGroupLeftJoin(Sql sql) { sql.LeftJoin<User2UserGroupDto>(SqlSyntax) .On<User2UserGroupDto, UserDto>(SqlSyntax, dto => dto.UserId, dto => dto.Id) .LeftJoin<UserGroupDto>(SqlSyntax) .On<UserGroupDto, User2UserGroupDto>(SqlSyntax, dto => dto.Id, dto => dto.UserGroupId) .LeftJoin<UserGroup2AppDto>(SqlSyntax) .On<UserGroup2AppDto, UserGroupDto>(SqlSyntax, dto => dto.UserGroupId, dto => dto.Id) .LeftJoin<UserStartNodeDto>(SqlSyntax) .On<UserStartNodeDto, UserDto>(SqlSyntax, dto => dto.UserId, dto => dto.Id); } private Sql GetBaseQuery(string columns) { var sql = new Sql(); sql.Select(columns) .From<UserDto>(); return sql; } protected override string GetBaseWhereClause() { return "umbracoUser.id = @Id"; } protected override IEnumerable<string> GetDeleteClauses() { var list = new List<string> { "DELETE FROM cmsTask WHERE userId = @Id", "DELETE FROM cmsTask WHERE parentUserId = @Id", "DELETE FROM umbracoUser2UserGroup WHERE userId = @Id", "DELETE FROM umbracoUser2NodeNotify WHERE userId = @Id", "DELETE FROM umbracoUser WHERE id = @Id", "DELETE FROM umbracoExternalLogin WHERE id = @Id" }; return list; } protected override Guid NodeObjectTypeId { get { throw new NotImplementedException(); } } protected override void PersistNewItem(IUser entity) { ((User)entity).AddingEntity(); //ensure security stamp if non if (entity.SecurityStamp.IsNullOrWhiteSpace()) { entity.SecurityStamp = Guid.NewGuid().ToString(); } var userDto = UserFactory.BuildDto(entity); //Check if we have a known config, we only want to store config for hashing //TODO: This logic will need to be updated when we do http://issues.umbraco.org/issue/U4-10089 if (_passwordConfiguration != null && _passwordConfiguration.Count > 0) { var json = JsonConvert.SerializeObject(_passwordConfiguration); userDto.PasswordConfig = json; } var id = Convert.ToInt32(Database.Insert(userDto)); entity.Id = id; if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds")) { if (entity.IsPropertyDirty("StartContentIds")) { AddingOrUpdateStartNodes(entity, Enumerable.Empty<UserStartNodeDto>(), UserStartNodeDto.StartNodeTypeValue.Content, entity.StartContentIds); } if (entity.IsPropertyDirty("StartMediaIds")) { AddingOrUpdateStartNodes(entity, Enumerable.Empty<UserStartNodeDto>(), UserStartNodeDto.StartNodeTypeValue.Media, entity.StartMediaIds); } } if (entity.IsPropertyDirty("Groups")) { //lookup all assigned var assigned = entity.Groups == null || entity.Groups.Any() == false ? new List<UserGroupDto>() : Database.Fetch<UserGroupDto>("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", new { aliases = entity.Groups.Select(x => x.Alias) }); foreach (var groupDto in assigned) { var dto = new User2UserGroupDto { UserGroupId = groupDto.Id, UserId = entity.Id }; Database.Insert(dto); } } entity.ResetDirtyProperties(); } protected override void PersistUpdatedItem(IUser entity) { //Updates Modified date ((User)entity).UpdatingEntity(); //ensure security stamp if non if (entity.SecurityStamp.IsNullOrWhiteSpace()) { entity.SecurityStamp = Guid.NewGuid().ToString(); } var userDto = UserFactory.BuildDto(entity); //build list of columns to check for saving - we don't want to save the password if it hasn't changed! //List the columns to save, NOTE: would be nice to not have hard coded strings here but no real good way around that var colsToSave = new Dictionary<string, string>() { {"userDisabled", "IsApproved"}, {"userNoConsole", "IsLockedOut"}, {"startStructureID", "StartContentId"}, {"startMediaID", "StartMediaId"}, {"userName", "Name"}, {"userLogin", "Username"}, {"userEmail", "Email"}, {"userLanguage", "Language"}, {"securityStampToken", "SecurityStamp"}, {"lastLockoutDate", "LastLockoutDate"}, {"lastPasswordChangeDate", "LastPasswordChangeDate"}, {"lastLoginDate", "LastLoginDate"}, {"failedLoginAttempts", "FailedPasswordAttempts"}, {"createDate", "CreateDate"}, {"updateDate", "UpdateDate"}, {"avatar", "Avatar"}, {"emailConfirmedDate", "EmailConfirmedDate"}, {"invitedDate", "InvitedDate"}, {"tourData", "TourData"} }; //create list of properties that have changed var changedCols = colsToSave .Where(col => entity.IsPropertyDirty(col.Value)) .Select(col => col.Key) .ToList(); // DO NOT update the password if it has not changed or if it is null or empty if (entity.IsPropertyDirty("RawPasswordValue") && entity.RawPasswordValue.IsNullOrWhiteSpace() == false) { changedCols.Add("userPassword"); //special case - when using ASP.Net identity the user manager will take care of updating the security stamp, however // when not using ASP.Net identity (i.e. old membership providers), we'll need to take care of updating this manually // so we can just detect if that property is dirty, if it's not we'll set it manually if (entity.IsPropertyDirty("SecurityStamp") == false) { userDto.SecurityStampToken = entity.SecurityStamp = Guid.NewGuid().ToString(); changedCols.Add("securityStampToken"); } //Check if we have a known config, we only want to store config for hashing //TODO: This logic will need to be updated when we do http://issues.umbraco.org/issue/U4-10089 if (_passwordConfiguration != null && _passwordConfiguration.Count > 0) { var json = JsonConvert.SerializeObject(_passwordConfiguration); userDto.PasswordConfig = json; changedCols.Add("passwordConfig"); } } //only update the changed cols if (changedCols.Count > 0) { Database.Update(userDto, changedCols); } if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds")) { var assignedStartNodes = Database.Fetch<UserStartNodeDto>("SELECT * FROM umbracoUserStartNode WHERE userId = @userId", new { userId = entity.Id }); if (entity.IsPropertyDirty("StartContentIds")) { AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Content, entity.StartContentIds); } if (entity.IsPropertyDirty("StartMediaIds")) { AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Media, entity.StartMediaIds); } } if (entity.IsPropertyDirty("Groups")) { //lookup all assigned var assigned = entity.Groups == null || entity.Groups.Any() == false ? new List<UserGroupDto>() : Database.Fetch<UserGroupDto>("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", new { aliases = entity.Groups.Select(x => x.Alias) }); //first delete all //TODO: We could do this a nicer way instead of "Nuke and Pave" Database.Delete<User2UserGroupDto>("WHERE UserId = @UserId", new { UserId = entity.Id }); foreach (var groupDto in assigned) { var dto = new User2UserGroupDto { UserGroupId = groupDto.Id, UserId = entity.Id }; Database.Insert(dto); } } entity.ResetDirtyProperties(); } private void AddingOrUpdateStartNodes(IEntity entity, IEnumerable<UserStartNodeDto> current, UserStartNodeDto.StartNodeTypeValue startNodeType, int[] entityStartIds) { var assignedIds = current.Where(x => x.StartNodeType == (int)startNodeType).Select(x => x.StartNode).ToArray(); //remove the ones not assigned to the entity var toDelete = assignedIds.Except(entityStartIds).ToArray(); if (toDelete.Length > 0) Database.Delete<UserStartNodeDto>("WHERE UserId = @UserId AND startNode IN (@startNodes)", new { UserId = entity.Id, startNodes = toDelete }); //add the ones not currently in the db var toAdd = entityStartIds.Except(assignedIds).ToArray(); foreach (var i in toAdd) { var dto = new UserStartNodeDto { StartNode = i, StartNodeType = (int)startNodeType, UserId = entity.Id }; Database.Insert(dto); } } #endregion #region Implementation of IUserRepository public int GetCountByQuery(IQuery<IUser> query) { var sqlClause = GetBaseQuery("umbracoUser.id"); var translator = new SqlTranslator<IUser>(sqlClause, query); var subquery = translator.Translate(); //get the COUNT base query var sql = GetBaseQuery(true) .Append(new Sql("WHERE umbracoUser.id IN (" + subquery.SQL + ")", subquery.Arguments)); return Database.ExecuteScalar<int>(sql); } public bool Exists(string username) { var sql = new Sql(); sql.Select("COUNT(*)") .From<UserDto>() .Where<UserDto>(x => x.UserName == username); return Database.ExecuteScalar<int>(sql) > 0; } /// <summary> /// Gets a list of <see cref="IUser"/> objects associated with a given group /// </summary> /// <param name="groupId">Id of group</param> public IEnumerable<IUser> GetAllInGroup(int groupId) { return GetAllInOrNotInGroup(groupId, true); } /// <summary> /// Gets a list of <see cref="IUser"/> objects not associated with a given group /// </summary> /// <param name="groupId">Id of group</param> public IEnumerable<IUser> GetAllNotInGroup(int groupId) { return GetAllInOrNotInGroup(groupId, false); } private IEnumerable<IUser> GetAllInOrNotInGroup(int groupId, bool include) { var sql = new Sql(); sql.Select("*") .From<UserDto>(); var innerSql = new Sql(); innerSql.Select("umbracoUser.id") .From<UserDto>() .LeftJoin<User2UserGroupDto>() .On<UserDto, User2UserGroupDto>(left => left.Id, right => right.UserId) .Where("umbracoUser2UserGroup.userGroupId = " + groupId); sql.Where(string.Format("umbracoUser.id {0} ({1})", include ? "IN" : "NOT IN", innerSql.SQL)); return ConvertFromDtos(Database.Fetch<UserDto>(sql)); } [Obsolete("Use the overload with long operators instead")] [EditorBrowsable(EditorBrowsableState.Never)] public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, int pageIndex, int pageSize, out int totalRecords, Expression<Func<IUser, string>> orderBy) { if (orderBy == null) throw new ArgumentNullException("orderBy"); // get the referenced column name and find the corresp mapped column name var expressionMember = ExpressionHelper.GetMemberInfo(orderBy); var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser)); var mappedField = mapper.Map(expressionMember.Name); if (mappedField.IsNullOrWhiteSpace()) throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause"); long tr; var results = GetPagedResultsByQuery(query, Convert.ToInt64(pageIndex), pageSize, out tr, mappedField, Direction.Ascending); totalRecords = Convert.ToInt32(tr); return results; } /// <summary> /// Gets paged user results /// </summary> /// <param name="query"></param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="totalRecords"></param> /// <param name="orderBy"></param> /// <param name="orderDirection"></param> /// <param name="includeUserGroups"> /// A filter to only include user that belong to these user groups /// </param> /// <param name="excludeUserGroups"> /// A filter to only include users that do not belong to these user groups /// </param> /// <param name="userState">Optional parameter to filter by specfied user state</param> /// <param name="filter"></param> /// <returns></returns> /// <remarks> /// The query supplied will ONLY work with data specifically on the umbracoUser table because we are using PetaPoco paging (SQL paging) /// </remarks> public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, long pageIndex, int pageSize, out long totalRecords, Expression<Func<IUser, object>> orderBy, Direction orderDirection, string[] includeUserGroups = null, string[] excludeUserGroups = null, UserState[] userState = null, IQuery<IUser> filter = null) { if (orderBy == null) throw new ArgumentNullException("orderBy"); // get the referenced column name and find the corresp mapped column name var expressionMember = ExpressionHelper.GetMemberInfo(orderBy); var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser)); var mappedField = mapper.Map(expressionMember.Name); if (mappedField.IsNullOrWhiteSpace()) throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause"); return GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, mappedField, orderDirection, includeUserGroups, excludeUserGroups, userState, filter); } private IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection, string[] includeUserGroups = null, string[] excludeUserGroups = null, UserState[] userState = null, IQuery<IUser> customFilter = null) { if (string.IsNullOrWhiteSpace(orderBy)) throw new ArgumentException("Value cannot be null or whitespace.", "orderBy"); Sql filterSql = null; var customFilterWheres = customFilter != null ? customFilter.GetWhereClauses().ToArray() : null; var hasCustomFilter = customFilterWheres != null && customFilterWheres.Length > 0; if (hasCustomFilter || (includeUserGroups != null && includeUserGroups.Length > 0) || (excludeUserGroups != null && excludeUserGroups.Length > 0) || (userState != null && userState.Length > 0 && userState.Contains(UserState.All) == false)) filterSql = new Sql(); if (hasCustomFilter) { foreach (var filterClause in customFilterWheres) { filterSql.Append(string.Format("AND ({0})", filterClause.Item1), filterClause.Item2); } } if (includeUserGroups != null && includeUserGroups.Length > 0) { var subQuery = @"AND (umbracoUser.id IN (SELECT DISTINCT umbracoUser.id FROM umbracoUser INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))"; filterSql.Append(subQuery, new { userGroups = includeUserGroups }); } if (excludeUserGroups != null && excludeUserGroups.Length > 0) { var subQuery = @"AND (umbracoUser.id NOT IN (SELECT DISTINCT umbracoUser.id FROM umbracoUser INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))"; filterSql.Append(subQuery, new { userGroups = excludeUserGroups }); } if (userState != null && userState.Length > 0) { //the "ALL" state doesn't require any filtering so we ignore that, if it exists in the list we don't do any filtering if (userState.Contains(UserState.All) == false) { var sb = new StringBuilder("("); var appended = false; if (userState.Contains(UserState.Active)) { sb.Append("(userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NOT NULL)"); appended = true; } if (userState.Contains(UserState.Disabled)) { if (appended) sb.Append(" OR "); sb.Append("(userDisabled = 1)"); appended = true; } if (userState.Contains(UserState.LockedOut)) { if (appended) sb.Append(" OR "); sb.Append("(userNoConsole = 1)"); appended = true; } if (userState.Contains(UserState.Invited)) { if (appended) sb.Append(" OR "); sb.Append("(lastLoginDate IS NULL AND userDisabled = 1 AND invitedDate IS NOT NULL)"); appended = true; } sb.Append(")"); filterSql.Append("AND " + sb); } } // Get base query for returning IDs var sqlBaseIds = GetBaseQuery("id"); if (query == null) query = new Query<IUser>(); var translatorIds = new SqlTranslator<IUser>(sqlBaseIds, query); var sqlQueryIds = translatorIds.Translate(); //get sorted and filtered sql var sqlNodeIdsWithSort = GetSortedSqlForPagedResults( GetFilteredSqlForPagedResults(sqlQueryIds, filterSql), orderDirection, orderBy); // Get page of results and total count var pagedResult = Database.Page<UserDto>(pageIndex + 1, pageSize, sqlNodeIdsWithSort); totalRecords = Convert.ToInt32(pagedResult.TotalItems); //NOTE: We need to check the actual items returned, not the 'totalRecords', that is because if you request a page number // that doesn't actually have any data on it, the totalRecords will still indicate there are records but there are none in // the pageResult. if (pagedResult.Items.Any()) { //Create the inner paged query that was used above to get the paged result, we'll use that as the inner sub query var args = sqlNodeIdsWithSort.Arguments; string sqlStringCount, sqlStringPage; Database.BuildPageQueries<UserDto>(pageIndex * pageSize, pageSize, sqlNodeIdsWithSort.SQL, ref args, out sqlStringCount, out sqlStringPage); var sqlQueryFull = GetBaseQuery("umbracoUser.*, umbracoUserGroup.*, umbracoUserGroup2App.*, umbracoUserStartNode.*"); var fullQueryWithPagedInnerJoin = sqlQueryFull .Append("INNER JOIN (") //join the paged query with the paged query arguments .Append(sqlStringPage, args) .Append(") temp ") .Append("ON umbracoUser.id = temp.id"); AddGroupLeftJoin(fullQueryWithPagedInnerJoin); //get sorted and filtered sql var fullQuery = GetSortedSqlForPagedResults( GetFilteredSqlForPagedResults(fullQueryWithPagedInnerJoin, filterSql), orderDirection, orderBy); var users = ConvertFromDtos(Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, fullQuery)) .ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching. return users; } return Enumerable.Empty<IUser>(); } private Sql GetFilteredSqlForPagedResults(Sql sql, Sql filterSql) { Sql filteredSql; // Apply filter if (filterSql != null) { var sqlFilter = " WHERE " + filterSql.SQL.TrimStart("AND "); //NOTE: this is certainly strange - NPoco handles this much better but we need to re-create the sql // instance a couple of times to get the parameter order correct, for some reason the first // time the arguments don't show up correctly but the SQL argument parameter names are actually updated // accordingly - so we re-create it again. In v8 we don't need to do this and it's already taken care of. filteredSql = new Sql(sql.SQL, sql.Arguments); var args = filteredSql.Arguments.Concat(filterSql.Arguments).ToArray(); filteredSql = new Sql( string.Format("{0} {1}", filteredSql.SQL, sqlFilter), args); filteredSql = new Sql(filteredSql.SQL, args); } else { //copy to var so that the original isn't changed filteredSql = new Sql(sql.SQL, sql.Arguments); } return filteredSql; } private Sql GetSortedSqlForPagedResults(Sql sql, Direction orderDirection, string orderBy) { //copy to var so that the original isn't changed var sortedSql = new Sql(sql.SQL, sql.Arguments); // Apply order according to parameters if (string.IsNullOrEmpty(orderBy) == false) { //each order by param needs to be in a bracket! see: https://github.com/toptensoftware/PetaPoco/issues/177 var orderByParams = new[] { string.Format("({0})", orderBy) }; if (orderDirection == Direction.Ascending) { sortedSql.OrderBy(orderByParams); } else { sortedSql.OrderByDescending(orderByParams); } } return sortedSql; } internal IEnumerable<IUser> GetNextUsers(int id, int count) { var idsQuery = new Sql() .Select("umbracoUser.id") .From<UserDto>(SqlSyntax) .Where<UserDto>(x => x.Id >= id) .OrderBy<UserDto>(x => x.Id, SqlSyntax); // first page is index 1, not zero var ids = Database.Page<int>(1, count, idsQuery).Items.ToArray(); // now get the actual users and ensure they are ordered properly (same clause) return ids.Length == 0 ? Enumerable.Empty<IUser>() : GetAll(ids).OrderBy(x => x.Id); } #endregion private IEnumerable<IUser> ConvertFromDtos(IEnumerable<UserDto> dtos) { return dtos.Select(UserFactory.BuildEntity); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { protected override AbstractNodeLocator CreateNodeLocator() { return new NodeLocator(this); } private class NodeLocator : AbstractNodeLocator { public NodeLocator(CSharpCodeModelService codeModelService) : base(codeModelService) { } protected override EnvDTE.vsCMPart DefaultPart { get { return EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; } } protected override VirtualTreePoint? GetStartPoint(SourceText text, SyntaxNode node, EnvDTE.vsCMPart part) { switch (node.Kind()) { case SyntaxKind.Attribute: return GetStartPoint(text, (AttributeSyntax)node, part); case SyntaxKind.AttributeArgument: return GetStartPoint(text, (AttributeArgumentSyntax)node, part); case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.EnumDeclaration: return GetStartPoint(text, (BaseTypeDeclarationSyntax)node, part); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: return GetStartPoint(text, (BaseMethodDeclarationSyntax)node, part); case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: return GetStartPoint(text, (BasePropertyDeclarationSyntax)node, part); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return GetStartPoint(text, (AccessorDeclarationSyntax)node, part); case SyntaxKind.DelegateDeclaration: return GetStartPoint(text, (DelegateDeclarationSyntax)node, part); case SyntaxKind.NamespaceDeclaration: return GetStartPoint(text, (NamespaceDeclarationSyntax)node, part); case SyntaxKind.UsingDirective: return GetStartPoint(text, (UsingDirectiveSyntax)node, part); case SyntaxKind.EnumMemberDeclaration: return GetStartPoint(text, (EnumMemberDeclarationSyntax)node, part); case SyntaxKind.VariableDeclarator: return GetStartPoint(text, (VariableDeclaratorSyntax)node, part); case SyntaxKind.Parameter: return GetStartPoint(text, (ParameterSyntax)node, part); default: Debug.Fail("Unsupported node kind: " + node.Kind()); throw new NotSupportedException(); } } protected override VirtualTreePoint? GetEndPoint(SourceText text, SyntaxNode node, EnvDTE.vsCMPart part) { switch (node.Kind()) { case SyntaxKind.Attribute: return GetEndPoint(text, (AttributeSyntax)node, part); case SyntaxKind.AttributeArgument: return GetEndPoint(text, (AttributeArgumentSyntax)node, part); case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.EnumDeclaration: return GetEndPoint(text, (BaseTypeDeclarationSyntax)node, part); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: return GetEndPoint(text, (BaseMethodDeclarationSyntax)node, part); case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: return GetEndPoint(text, (BasePropertyDeclarationSyntax)node, part); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return GetEndPoint(text, (AccessorDeclarationSyntax)node, part); case SyntaxKind.DelegateDeclaration: return GetEndPoint(text, (DelegateDeclarationSyntax)node, part); case SyntaxKind.NamespaceDeclaration: return GetEndPoint(text, (NamespaceDeclarationSyntax)node, part); case SyntaxKind.UsingDirective: return GetEndPoint(text, (UsingDirectiveSyntax)node, part); case SyntaxKind.EnumMemberDeclaration: return GetEndPoint(text, (EnumMemberDeclarationSyntax)node, part); case SyntaxKind.VariableDeclarator: return GetEndPoint(text, (VariableDeclaratorSyntax)node, part); case SyntaxKind.Parameter: return GetEndPoint(text, (ParameterSyntax)node, part); default: Debug.Fail("Unsupported node kind: " + node.Kind()); throw new NotSupportedException(); } } private SyntaxToken GetFirstTokenAfterAttributes(BaseTypeDeclarationSyntax node) { return node.AttributeLists.Count != 0 ? node.AttributeLists.Last().GetLastToken().GetNextToken() : node.GetFirstToken(); } private SyntaxToken GetFirstTokenAfterAttributes(BaseMethodDeclarationSyntax node) { return node.AttributeLists.Count != 0 ? node.AttributeLists.Last().GetLastToken().GetNextToken() : node.GetFirstToken(); } private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace) { Debug.Assert(!openBrace.IsMissing); var openBraceLine = text.Lines.GetLineFromPosition(openBrace.Span.End); var textAfterBrace = text.ToString(TextSpan.FromBounds(openBrace.Span.End, openBraceLine.End)); return string.IsNullOrWhiteSpace(textAfterBrace) ? new VirtualTreePoint(openBrace.SyntaxTree, text, text.Lines[openBraceLine.LineNumber + 1].Start) : new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End); } private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace, SyntaxToken closeBrace, int memberStartColumn) { Debug.Assert(!openBrace.IsMissing); Debug.Assert(!closeBrace.IsMissing); Debug.Assert(memberStartColumn >= 0); var openBraceLine = text.Lines.GetLineFromPosition(openBrace.SpanStart); var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart); var tokenAfterOpenBrace = openBrace.GetNextToken(); var nextPosition = tokenAfterOpenBrace.SpanStart; // We need to check if there is any significant trivia trailing this token or leading // to the next token. This accounts for the fact that comments were included in the token // stream in Dev10. var significantTrivia = openBrace.GetAllTrailingTrivia() .Where(t => !t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia)) .FirstOrDefault(); if (significantTrivia.Kind() != SyntaxKind.None) { nextPosition = significantTrivia.SpanStart; } // If the opening and closing curlies are at least two lines apart then place the cursor // on the next line provided that there isn't any token on the line with the open curly. if (openBraceLine.LineNumber + 1 < closeBraceLine.LineNumber && openBraceLine.LineNumber < text.Lines.IndexOf(tokenAfterOpenBrace.SpanStart)) { var lineAfterOpenBrace = text.Lines[openBraceLine.LineNumber + 1]; var firstNonWhitespaceOffset = lineAfterOpenBrace.GetFirstNonWhitespaceOffset() ?? -1; // If the line contains any text, we return the start of the first non-whitespace character. if (firstNonWhitespaceOffset >= 0) { return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.Start + firstNonWhitespaceOffset); } // If the line is all whitespace then place the caret at the first indent after the start // of the member. var indentSize = GetTabSize(text); var lineText = lineAfterOpenBrace.ToString(); var lineEndColumn = lineText.GetColumnFromLineOffset(lineText.Length, indentSize); int indentColumn = memberStartColumn + indentSize; var virtualSpaces = indentColumn - lineEndColumn; return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.End, virtualSpaces); } else { // If the body is empty then place it after the open brace; otherwise, place // at the start of the first token after the open curly. if (closeBrace.SpanStart == nextPosition) { return new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End); } else { return new VirtualTreePoint(openBrace.SyntaxTree, text, nextPosition); } } } private VirtualTreePoint GetBodyEndPoint(SourceText text, SyntaxToken closeBrace) { var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart); var textBeforeBrace = text.ToString(TextSpan.FromBounds(closeBraceLine.Start, closeBrace.SpanStart)); return string.IsNullOrWhiteSpace(textBeforeBrace) ? new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBraceLine.Start) : new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBrace.SpanStart); } private VirtualTreePoint GetStartPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartHeader: startPosition = GetFirstTokenAfterAttributes(node).SpanStart; break; case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartHeader: startPosition = GetFirstTokenAfterAttributes(node).SpanStart; break; case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text)); return GetBodyStartPoint(text, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation); } else { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: startPosition = ((MethodDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.ConstructorDeclaration: startPosition = ((ConstructorDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.DestructorDeclaration: startPosition = ((DestructorDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.ConversionOperatorDeclaration: startPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.SpanStart; break; case SyntaxKind.OperatorDeclaration: startPosition = ((OperatorDeclarationSyntax)node).OperatorToken.SpanStart; break; default: startPosition = GetFirstTokenAfterAttributes(node).SpanStart; break; } } break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.Body.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private AccessorDeclarationSyntax FindFirstAccessorNode(BasePropertyDeclarationSyntax node) { if (node.AccessorList == null) { return null; } return node.AccessorList.Accessors.FirstOrDefault(); } private VirtualTreePoint GetStartPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: var firstAccessorNode = FindFirstAccessorNode(node); if (firstAccessorNode != null) { var line = text.Lines.GetLineFromPosition(firstAccessorNode.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text)); if (firstAccessorNode.Body != null) { return GetBodyStartPoint(text, firstAccessorNode.Body.OpenBraceToken, firstAccessorNode.Body.CloseBraceToken, indentation); } else if (!firstAccessorNode.SemicolonToken.IsMissing) { // This is total weirdness from the old C# code model with auto props. // If there isn't a body, the semi-colon is used return GetBodyStartPoint(text, firstAccessorNode.SemicolonToken, firstAccessorNode.SemicolonToken, indentation); } } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.AccessorList != null && !node.AccessorList.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text)); return GetBodyStartPoint(text, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentation); } throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text)); return GetBodyStartPoint(text, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation); } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.Body.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, NamespaceDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part) { var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (field.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = field.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: return GetBodyEndPoint(text, node.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.CloseBraceToken.IsMissing) { return GetBodyEndPoint(text, node.Body.CloseBraceToken); } else { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: endPosition = ((MethodDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.ConstructorDeclaration: endPosition = ((ConstructorDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.DestructorDeclaration: endPosition = ((DestructorDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.ConversionOperatorDeclaration: endPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.Span.End; break; case SyntaxKind.OperatorDeclaration: endPosition = ((OperatorDeclarationSyntax)node).OperatorToken.Span.End; break; default: endPosition = GetFirstTokenAfterAttributes(node).Span.End; break; } } break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.Body.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: var firstAccessorNode = FindFirstAccessorNode(node); if (firstAccessorNode != null) { if (firstAccessorNode.Body != null) { return GetBodyEndPoint(text, firstAccessorNode.Body.CloseBraceToken); } else { // This is total weirdness from the old C# code model with auto props. // If there isn't a body, the semi-colon is used return GetBodyEndPoint(text, firstAccessorNode.SemicolonToken); } } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.AccessorList != null && !node.AccessorList.CloseBraceToken.IsMissing) { return GetBodyEndPoint(text, node.AccessorList.CloseBraceToken); } throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.Body.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, NamespaceDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part) { var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (field.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = field.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = field.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Threading.Tasks; using System.Threading; namespace System.Data.Common { public abstract class DbCommand : Component, IDbCommand { protected DbCommand() : base() { } [DefaultValue("")] [RefreshProperties(RefreshProperties.All)] public abstract string CommandText { get; set; } public abstract int CommandTimeout { get; set; } [DefaultValue(System.Data.CommandType.Text)] [RefreshProperties(RefreshProperties.All)] public abstract CommandType CommandType { get; set; } [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DbConnection Connection { get { return DbConnection; } set { DbConnection = value; } } IDbConnection IDbCommand.Connection { get { return DbConnection; } set { DbConnection = (DbConnection)value; } } protected abstract DbConnection DbConnection { get; set; } protected abstract DbParameterCollection DbParameterCollection { get; } protected abstract DbTransaction DbTransaction { get; set; } // By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray) // to limit the number of components that clutter the design surface, // when the DataAdapter design wizard generates the insert/update/delete commands it will // set the DesignTimeVisible property to false so that cmds won't appear as individual objects [DefaultValue(true)] [DesignOnly(true)] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public abstract bool DesignTimeVisible { get; set; } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DbParameterCollection Parameters => DbParameterCollection; IDataParameterCollection IDbCommand.Parameters => DbParameterCollection; [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DbTransaction Transaction { get { return DbTransaction; } set { DbTransaction = value; } } IDbTransaction IDbCommand.Transaction { get { return DbTransaction; } set { DbTransaction = (DbTransaction)value; } } [DefaultValue(System.Data.UpdateRowSource.Both)] public abstract UpdateRowSource UpdatedRowSource { get; set; } internal void CancelIgnoreFailure() { // This method is used to route CancellationTokens to the Cancel method. // Cancellation is a suggestion, and exceptions should be ignored // rather than allowed to be unhandled, as the exceptions cannot be // routed to the caller. These errors will be observed in the regular // method instead. try { Cancel(); } catch (Exception) { } } public abstract void Cancel(); public DbParameter CreateParameter() => CreateDbParameter(); IDbDataParameter IDbCommand.CreateParameter() => CreateDbParameter(); protected abstract DbParameter CreateDbParameter(); protected abstract DbDataReader ExecuteDbDataReader(CommandBehavior behavior); public abstract int ExecuteNonQuery(); public DbDataReader ExecuteReader() => ExecuteDbDataReader(CommandBehavior.Default); IDataReader IDbCommand.ExecuteReader() => ExecuteDbDataReader(CommandBehavior.Default); public DbDataReader ExecuteReader(CommandBehavior behavior) => ExecuteDbDataReader(behavior); IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior) => ExecuteDbDataReader(behavior); public Task<int> ExecuteNonQueryAsync() => ExecuteNonQueryAsync(CancellationToken.None); public virtual Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<int>(); } else { CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this); } try { return Task.FromResult(ExecuteNonQuery()); } catch (Exception e) { return Task.FromException<int>(e); } finally { registration.Dispose(); } } } public Task<DbDataReader> ExecuteReaderAsync() => ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None); public Task<DbDataReader> ExecuteReaderAsync(CancellationToken cancellationToken) => ExecuteReaderAsync(CommandBehavior.Default, cancellationToken); public Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior) => ExecuteReaderAsync(behavior, CancellationToken.None); public Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) => ExecuteDbDataReaderAsync(behavior, cancellationToken); protected virtual Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<DbDataReader>(); } else { CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this); } try { return Task.FromResult<DbDataReader>(ExecuteReader(behavior)); } catch (Exception e) { return Task.FromException<DbDataReader>(e); } finally { registration.Dispose(); } } } public Task<object> ExecuteScalarAsync() => ExecuteScalarAsync(CancellationToken.None); public virtual Task<object> ExecuteScalarAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<object>(); } else { CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(s => ((DbCommand)s).CancelIgnoreFailure(), this); } try { return Task.FromResult<object>(ExecuteScalar()); } catch (Exception e) { return Task.FromException<object>(e); } finally { registration.Dispose(); } } } public abstract object ExecuteScalar(); public abstract void Prepare(); } }
// // literal.cs: Literal representation for the IL tree. // // Author: // Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@seznam.cz) // // Copyright 2001 Ximian, Inc. // // // Notice that during parsing we create objects of type Literal, but the // types are not loaded (thats why the Resolve method has to assign the // type at that point). // // Literals differ from the constants in that we know we encountered them // as a literal in the source code (and some extra rules apply there) and // they have to be resolved (since during parsing we have not loaded the // types yet) while constants are created only after types have been loaded // and are fully resolved when born. // #if STATIC using IKVM.Reflection.Emit; #else using System.Reflection.Emit; #endif namespace Mono.CSharp { // // The null literal // // Note: C# specification null-literal is NullLiteral of NullType type // public class NullLiteral : NullConstant { // // Default type of null is an object // public NullLiteral (Location loc) : base (InternalType.Null, loc) { } public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec t, bool expl) { if (t.IsGenericParameter) { ec.Report.Error(403, loc, "Cannot convert null to the type parameter `{0}' because it could be a value " + "type. Consider using `default ({0})' instead", t.Name); return; } if (TypeManager.IsValueType (t)) { ec.Report.Error(37, loc, "Cannot convert null to `{0}' because it is a value type", TypeManager.CSharpName(t)); return; } base.Error_ValueCannotBeConverted (ec, loc, t, expl); } public override string GetValueAsLiteral () { return "null"; } public override bool IsLiteral { get { return true; } } public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx) { return System.Linq.Expressions.Expression.Constant (null); } } // // A null literal in a pointer context // class NullPointer : NullLiteral { public NullPointer (Location loc): base (loc) { type = TypeManager.object_type; } public override void Emit (EmitContext ec) { // // Emits null pointer // ec.Emit (OpCodes.Ldc_I4_0); ec.Emit (OpCodes.Conv_U); } } public class BoolLiteral : BoolConstant { public BoolLiteral (bool val, Location loc) : base (val, loc) { } public override bool IsLiteral { get { return true; } } } public class CharLiteral : CharConstant { public CharLiteral (char c, Location loc) : base (c, loc) { } public override bool IsLiteral { get { return true; } } } public class IntLiteral : IntConstant { public IntLiteral (int l, Location loc) : base (l, loc) { } public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec type) { // // The 0 literal can be converted to an enum value // if (Value == 0 && TypeManager.IsEnumType (type)) { Constant c = ConvertImplicitly (rc, EnumSpec.GetUnderlyingType (type)); if (c == null) return null; return new EnumConstant (c, type).Resolve (rc); } return base.ConvertImplicitly (rc, type); } public override bool IsLiteral { get { return true; } } } public class UIntLiteral : UIntConstant { public UIntLiteral (uint l, Location loc) : base (l, loc) { } public override bool IsLiteral { get { return true; } } } public class LongLiteral : LongConstant { public LongLiteral (long l, Location loc) : base (l, loc) { } public override bool IsLiteral { get { return true; } } } public class ULongLiteral : ULongConstant { public ULongLiteral (ulong l, Location loc) : base (l, loc) { } public override bool IsLiteral { get { return true; } } } public class FloatLiteral : FloatConstant { public FloatLiteral (float f, Location loc) : base (f, loc) { } public override bool IsLiteral { get { return true; } } } public class DoubleLiteral : DoubleConstant { public DoubleLiteral (double d, Location loc) : base (d, loc) { } public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec target, bool expl) { if (target == TypeManager.float_type) { Error_664 (ec, loc, "float", "f"); return; } if (target == TypeManager.decimal_type) { Error_664 (ec, loc, "decimal", "m"); return; } base.Error_ValueCannotBeConverted (ec, loc, target, expl); } static void Error_664 (ResolveContext ec, Location loc, string type, string suffix) { ec.Report.Error (664, loc, "Literal of type double cannot be implicitly converted to type `{0}'. Add suffix `{1}' to create a literal of this type", type, suffix); } public override bool IsLiteral { get { return true; } } } public class DecimalLiteral : DecimalConstant { public DecimalLiteral (decimal d, Location loc) : base (d, loc) { } public override bool IsLiteral { get { return true; } } } public class StringLiteral : StringConstant { public StringLiteral (string s, Location loc) : base (s, loc) { } public override bool IsLiteral { get { return true; } } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Collections.ObjectModel; namespace OpenQA.Selenium { [TestFixture] public class CorrectEventFiringTest : DriverTestFixture { [Test] [IgnoreBrowser(Browser.Chrome, "Webkit bug 22261")] public void ShouldFireFocusEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("focus"); } [Test] [Category("Javascript")] public void ShouldFireClickEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("click"); } [Test] [Category("Javascript")] public void ShouldFireMouseDownEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mousedown"); } [Test] [Category("Javascript")] public void ShouldFireMouseUpEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mouseup"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Chrome)] public void ShouldFireMouseOverEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mouseover"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.Firefox, "Firefox does not report mouse move event when clicking")] public void ShouldFireMouseMoveEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mousemove"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Chrome, "Webkit bug 22261")] public void ShouldFireEventsInTheRightOrder() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); string text = driver.FindElement(By.Id("result")).Text; int lastIndex = -1; List<string> eventList = new List<string>() {"mousedown", "focus", "mouseup", "click"}; foreach(string eventName in eventList) { int index = text.IndexOf(eventName); Assert.IsTrue(index != -1, eventName + " did not fire at all"); Assert.IsTrue(index > lastIndex, eventName + " did not fire in the correct order"); lastIndex = index; } } [Test] [Category("Javascript")] public void ShouldIssueMouseDownEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mousedown")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse down"); } [Test] [Category("Javascript")] public void ShouldIssueClickEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mouseclick")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse click"); } [Test] [Category("Javascript")] public void ShouldIssueMouseUpEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mouseup")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse up"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone)] public void MouseEventsShouldBubbleUpToContainingElements() { driver.Url = javascriptPage; driver.FindElement(By.Id("child")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse down"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone)] public void ShouldEmitOnChangeEventsWhenSelectingElements() { driver.Url = javascriptPage; //Intentionally not looking up the select tag. See selenium r7937 for details. ReadOnlyCollection<IWebElement> allOptions = driver.FindElements(By.XPath("//select[@id='selector']//option")); String initialTextValue = driver.FindElement(By.Id("result")).Text; IWebElement foo = allOptions[0]; IWebElement bar = allOptions[1]; foo.Select(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, initialTextValue); bar.Select(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "bar"); } [Test] [Category("Javascript")] public void ShouldEmitOnChangeEventsWhenChangingTheStateOfACheckbox() { driver.Url = javascriptPage; IWebElement checkbox = driver.FindElement(By.Id("checkbox")); checkbox.Select(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "checkbox thing"); } [Test] [Category("Javascript")] public void ShouldEmitClickEventWhenClickingOnATextInputElement() { driver.Url = javascriptPage; IWebElement clicker = driver.FindElement(By.Id("clickField")); clicker.Click(); Assert.AreEqual(clicker.Value, "Clicked"); } [Test] [Category("Javascript")] public void ClearingAnElementShouldCauseTheOnChangeHandlerToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("clearMe")); element.Clear(); IWebElement result = driver.FindElement(By.Id("result")); Assert.AreEqual(result.Text, "Cleared"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone, "SendKeys implementation is incorrect.")] public void SendingKeysToAnotherElementShouldCauseTheBlurEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); IWebElement element2 = driver.FindElement(By.Id("changeable")); element2.SendKeys("bar"); AssertEventFired("blur"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone, "SendKeys implementation is incorrect.")] public void SendingKeysToAnElementShouldCauseTheFocusEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); AssertEventFired("focus"); } private void ClickOnElementWhichRecordsEvents() { driver.FindElement(By.Id("plainButton")).Click(); } private void AssertEventFired(String eventName) { IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains(eventName), "No " + eventName + " fired: " + text); } } }
/* Ben Scott * bescott@andrew.cmu.edu * 2015-07-07 * Character Motor */ using UnityEngine; using System.Collections; using System.Collections.Generic; using EventArgs=System.EventArgs; using adv=PathwaysEngine.Adventure; using lit=PathwaysEngine.Literature; using u=PathwaysEngine.Utilities; namespace PathwaysEngine.Movement { [RequireComponent(typeof(CharacterController))] public class CharacterMotor : MonoBehaviour, IMotor { public enum transfer { None, initial, PermaTransfer, PermaLocked } bool newPlatform, wait, recentlyLanded; uint massPlayer = 80; //deltaPitch, deltaStep, float maxSpeed = 57.2f, dampingGround = 30f, dampingAirborne = 20f, lastStartTime = 0, lastEndTime = -100f, tgtCrouch = 0, tgtCrouchLand = 1.5f; public float modSprint = 1.6f, modCrouch = 0.8f, speedAnterior = 16f, speedLateral = 12f, speedPosterior = 10f, speedVertical = 1f, deltaHeight = 2f, weightPerp = 0, weightSteep = 0.5f, extraHeight = 4.1f, slidingSpeed = 15f, lateralControl = 1f, speedControl = 0.4f, deltaCrouch = 1f, landingDuration = 0.15f, terminalVelocity = 30f; public transfer dirTransfer = transfer.PermaTransfer; public AnimationCurve responseSlope; CollisionFlags hitFlags; Vector3 inputMove = Vector3.zero, jumpDir = Vector3.zero, platformVelocity = Vector3.zero, groundNormal = Vector3.zero, lastGroundNormal = Vector3.zero, hitPoint = Vector3.zero, lastHitPoint = new Vector3(Mathf.Infinity,0,0), activeLocalPoint = Vector3.zero, activeGlobalPoint = Vector3.zero; Transform hitPlatform, activePlatform, mCamr, playerGraphics; Quaternion activeLocalRotation, activeGlobalRotation; Matrix4x4 lastMatrix; CharacterController cr; ControllerColliderHit lastColl; public u::key jump, dash, duck; public u::axis axisX, axisY; public event lit::Parse KillEvent; public bool IsDead { get { return isDead; } set { isDead = value; } } bool isDead = false; public bool IsJumping { get { return isJumping; } set { if (isJumping!=value) { if (value && !WasJumping) OnJump(); else OnLand(); } WasJumping = isJumping; isJumping = value; } } bool isJumping = false; public bool WasJumping {get;set;} public bool IsGrounded { get { return isGrounded; } set { WasGrounded = isGrounded; isGrounded = value; } } bool isGrounded = false; public bool WasGrounded {get;set;} public bool grounded { get { return (groundNormal.y>0.01); } } public bool IsSliding { get { return (IsGrounded && TooSteep()); } } public bool IsSprinting { get { return dash.input; } } public Vector3 Position { get { return transform.position; } set { transform.position = value; } } public Vector3 LocalPosition { get { return transform.localPosition; } set { transform.localPosition = value; } } public Vector3 Velocity { get { return velocity; } set { velocity = value; lastVelocity = Vector3.zero; IsGrounded = false; } } Vector3 velocity = Vector3.zero; public Vector3 lastVelocity {get;set;} internal CharacterMotor() { jump = new u::key((n)=>jump.input=n); dash = new u::key((n)=>dash.input=n); duck = new u::key((n)=>duck.input=n); axisX = new u::axis((n)=>axisX.input=n); axisY = new u::axis((n)=>axisY.input=n); } /* internal ~CharacterMotor() { GameObject.Destroy(mapFollower); } */ public virtual void Awake() { cr = GetComponent<CharacterController>(); mCamr = GameObject.FindGameObjectsWithTag( "MainCamera")[0].transform; responseSlope = new AnimationCurve( new Keyframe(-90,1), new Keyframe(90,0)); KillEvent += Kill; } void OnDestroy() { KillEvent -= Kill; } public IEnumerator Killing() { if (wait) yield break; wait = true; u::CameraFade.StartAlphaFade( new Color(255,255,255),false,8f,2f, ()=> { if (!Pathways.mainCamera) return; Pathways.mainCamera.cullingMask = 0; Pathways.mainCamera.clearFlags = CameraClearFlags.SolidColor; Pathways.mainCamera.backgroundColor = new Color(255,255,255); }); yield return new WaitForSeconds(12f); wait = false; } public bool Kill() { StartCoroutine(Killing()); IsDead = true; var rb = GetComponent<Rigidbody>(); rb.isKinematic = false; rb.useGravity = true; rb.freezeRotation = false; rb.AddForce(velocity,ForceMode.VelocityChange); GetComponent<Look>().enabled = false; cr.enabled = false; this.enabled = false; return true; } public bool Kill( adv::Person sender, EventArgs e, lit::Command c, string input) => Kill(); public void OnJump() { } public IEnumerator Landed() { if (!wait) { wait = true; recentlyLanded = true; yield return new WaitForSeconds(landingDuration); recentlyLanded = false; wait = false; } } public void OnLand() { StartCoroutine(Landed()); } public void Update() { if (Mathf.Abs(Time.timeScale)<0.01f) return; if (modSprint==0 || modCrouch==0 || speedAnterior==0 || speedLateral==0 || speedPosterior==0) return; var dirVector = new Vector3(axisX.input, 0, axisY.input); if (dirVector != Vector3.zero) { var dirLength = dirVector.magnitude; dirVector /= dirLength; dirLength = Mathf.Min(1f,dirLength); dirLength = dirLength * dirLength; dirVector = dirVector * dirLength; } inputMove = transform.rotation * dirVector; if (!IsDead) UpdateFunction(); } public void FixedUpdate() { if ((Mathf.Abs(Time.timeScale)>0.1f) && activePlatform != null) { if (!newPlatform) platformVelocity = (activePlatform.localToWorldMatrix.MultiplyPoint3x4(activeLocalPoint) - lastMatrix.MultiplyPoint3x4(activeLocalPoint))/((Mathf.Abs(Time.deltaTime)>0.01f)?Time.deltaTime:0.01f); lastMatrix = activePlatform.localToWorldMatrix; newPlatform = false; } else platformVelocity = Vector3.zero; } public void OnCollisionEvent(Collision collision) { } void UpdateFunction() { var tempVelocity = velocity; var moveDistance = Vector3.zero; tempVelocity = applyDeltaVelocity(tempVelocity); if (MoveWithPlatform()) { var newGlobalPoint = activePlatform.TransformPoint(activeLocalPoint); moveDistance = (newGlobalPoint - activeGlobalPoint); if (moveDistance != Vector3.zero) cr.Move(moveDistance); var newGlobalRotation = activePlatform.rotation * activeLocalRotation; var rotationDiff = newGlobalRotation * Quaternion.Inverse(activeGlobalRotation); var yRotation = rotationDiff.eulerAngles.y; if (yRotation!=0) transform.Rotate(0,yRotation,0); } var lastPosition = transform.position; var currentMovementOffset = tempVelocity * ((Mathf.Abs(Time.deltaTime)>0.01f)?Time.deltaTime:0.01f); var pushDownOffset = Mathf.Max(cr.stepOffset, new Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude); if (IsGrounded) currentMovementOffset -= pushDownOffset*Vector3.up; hitPlatform = null; groundNormal = Vector3.zero; // This one moves the user and returns the direction of the hit hitFlags = cr.Move(currentMovementOffset); lastHitPoint = hitPoint; lastGroundNormal = groundNormal; if (activePlatform != hitPlatform && hitPlatform != null) { activePlatform = hitPlatform; lastMatrix = hitPlatform.localToWorldMatrix; newPlatform = true; } var oldHVelocity = new Vector3(tempVelocity.x,0,tempVelocity.z); velocity = (transform.position - lastPosition) / ((Mathf.Abs(Time.deltaTime)>0.01f)?Time.deltaTime:0.01f); var newHVelocity = new Vector3(velocity.x, 0, velocity.z); if (oldHVelocity != Vector3.zero) { var projectedNewVelocity = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMagnitude; velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + velocity.y * Vector3.up; } else velocity = new Vector3(0, velocity.y, 0); if (velocity.y < tempVelocity.y - 0.001) { if (velocity.y < 0) velocity = new Vector3( velocity.x,tempVelocity.y,velocity.z); else WasJumping = false; } if (IsGrounded && !grounded) { IsGrounded = false; if ((dirTransfer==transfer.initial || dirTransfer==transfer.PermaTransfer)) { lastVelocity = platformVelocity; velocity += platformVelocity; } transform.position += pushDownOffset * Vector3.up; } else if (!IsGrounded && grounded) { IsGrounded = true; IsJumping = false; SubtractNewPlatformVelocity(); if (velocity.y<-terminalVelocity) Kill(null,EventArgs.Empty, new lit::Command(),""); } if (MoveWithPlatform()) { activeGlobalPoint = transform.position +Vector3.up*(cr.center.y-cr.height*0.5f+cr.radius); activeLocalPoint = activePlatform.InverseTransformPoint(activeGlobalPoint); activeGlobalRotation = transform.rotation; activeLocalRotation = Quaternion.Inverse( activePlatform.rotation) * activeGlobalRotation; } slidingSpeed = (duck.input)?(4f):(15f); tgtCrouch = (duck.input)?1.62f:2f; if (recentlyLanded) tgtCrouch = tgtCrouchLand; if (Mathf.Abs(deltaHeight-tgtCrouch)<0.01f) deltaHeight = tgtCrouch; deltaHeight = Mathf.SmoothDamp( deltaHeight, tgtCrouch, ref deltaCrouch, 0.06f, 64, Time.smoothDeltaTime); cr.height = deltaHeight; if (mCamr && Pathways.GameState==GameStates.Game) mCamr.localPosition = Vector3.up*(deltaHeight-0.2f); cr.center = Vector3.up*(deltaHeight/2f); } Vector3 applyDeltaVelocity(Vector3 tempVelocity) { // the horizontal to calculate direction from the IsJumping event Vector3 desiredVelocity; if (IsGrounded && TooSteep()) { // and to support walljumping I need to change horizontal here desiredVelocity = new Vector3(groundNormal.x,0,groundNormal.z).normalized; var projectedMoveDir = Vector3.Project( inputMove, desiredVelocity); desiredVelocity = desiredVelocity+projectedMoveDir*speedControl + (inputMove - projectedMoveDir) * lateralControl; desiredVelocity *= slidingSpeed; } else desiredVelocity = GetDesiredHorizontalVelocity(); if (dirTransfer==transfer.PermaTransfer) { desiredVelocity += lastVelocity; desiredVelocity.y = 0; } if (IsGrounded) desiredVelocity = AdjustGroundVelocityToNormal(desiredVelocity, groundNormal); else tempVelocity.y = 0; // Enforce zero on Y because the axes are calculated separately var maxSpeedChange = GetMaxAcceleration(IsGrounded) * Time.deltaTime; var velocityChangeVector = (desiredVelocity - tempVelocity); if (velocityChangeVector.sqrMagnitude > maxSpeedChange * maxSpeedChange) velocityChangeVector = velocityChangeVector.normalized * maxSpeedChange; if (IsGrounded) tempVelocity += velocityChangeVector; if (IsGrounded) tempVelocity.y = Mathf.Min(velocity.y, 0); if (!jump.input) { // This second section aplies only the vertical axis motion but // the reason I've conjoined these two is because I now have an WasJumping = false; // interaction between the user's vertical & horizontal vectors lastEndTime = -100; } if (jump.input && lastEndTime<0) lastEndTime = Time.time; if (IsGrounded) tempVelocity.y = Mathf.Min(0, tempVelocity.y) - -Physics.gravity.y * Time.deltaTime; else { tempVelocity.y = velocity.y - -Physics.gravity.y*2*Time.deltaTime; if (IsJumping && WasJumping) { if (Time.time<lastStartTime + extraHeight / CalculateJumpVerticalSpeed(speedVertical)) tempVelocity += jumpDir * -Physics.gravity.y*2 * Time.deltaTime; } tempVelocity.y = Mathf.Max(tempVelocity.y, -maxSpeed); } if (IsGrounded) { if (Time.time-lastEndTime<0.2) { IsGrounded = false; IsJumping = true; lastStartTime = Time.time; lastEndTime = -100; WasJumping = true; if (TooSteep()) jumpDir = Vector3.Slerp( Vector3.up, groundNormal, weightSteep); else jumpDir = Vector3.Slerp( Vector3.up, groundNormal, weightPerp); tempVelocity.y = 0; tempVelocity += jumpDir * CalculateJumpVerticalSpeed(speedVertical); if (dirTransfer==transfer.initial || dirTransfer==transfer.PermaTransfer) { lastVelocity = platformVelocity; tempVelocity += platformVelocity; } } else WasJumping = false; } else if (cr.collisionFlags==CollisionFlags.Sides) Vector3.Slerp(Vector3.up,lastColl.normal,lateralControl); return tempVelocity; } void OnCollisionEnter(Collision collision) { //Player.OnCollisionEnter(collision); } void OnControllerColliderHit(ControllerColliderHit hit) { //Player.OnCollisionEnter(hit.collider); var other = hit.collider.attachedRigidbody; lastColl = hit; if (other && hit.moveDirection.y>-0.05) other.velocity = new Vector3( hit.moveDirection.x,0,hit.moveDirection.z) *(massPlayer+other.mass)/(2*-Physics.gravity.y); if (hit.normal.y>0 && hit.normal.y>groundNormal.y && hit.moveDirection.y<0) { if ((hit.point - lastHitPoint).sqrMagnitude>0.001 || lastGroundNormal==Vector3.zero) groundNormal = hit.normal; else groundNormal = lastGroundNormal; hitPlatform = hit.collider.transform; lastVelocity = Vector3.zero; hitPoint = hit.point; } } IEnumerator SubtractNewPlatformVelocity() { if (dirTransfer==transfer.initial || dirTransfer==transfer.PermaTransfer) { if (newPlatform) { Transform platform = activePlatform; // Both yields are present as a kind of corruption of von Braun style redundancy as it might be near or have missed the call yield return new WaitForFixedUpdate(); yield return new WaitForFixedUpdate(); if (IsGrounded && platform==activePlatform) yield break; } velocity -= platformVelocity; } } Vector3 GetDesiredHorizontalVelocity() { var dirDesired = transform.InverseTransformDirection(inputMove); var maxSpeed = 0.0f; if (dirDesired != Vector3.zero) { var zAxisEllipseMultiplier = (dirDesired.z>0 ? speedAnterior : speedPosterior) / speedLateral; if (dash.input && IsGrounded) zAxisEllipseMultiplier *= modSprint; else if (duck.input && IsGrounded) zAxisEllipseMultiplier *= modCrouch; var temp = new Vector3(dirDesired.x, 0, dirDesired.z / zAxisEllipseMultiplier).normalized; maxSpeed = new Vector3(temp.x, 0, temp.z * zAxisEllipseMultiplier).magnitude * speedLateral; } if (IsGrounded) { var movementSlopeAngle = Mathf.Asin(velocity.normalized.y) * Mathf.Rad2Deg; maxSpeed *= responseSlope.Evaluate(movementSlopeAngle); } return transform.TransformDirection(dirDesired * maxSpeed); } bool MoveWithPlatform() { return (IsGrounded || dirTransfer==transfer.PermaLocked)&&(activePlatform); } Vector3 AdjustGroundVelocityToNormal(Vector3 v,Vector3 normal) { return Vector3.Cross(Vector3.Cross(Vector3.up, v), normal).normalized * v.magnitude; } float GetMaxAcceleration(bool IsGrounded) { return IsGrounded ? dampingGround : dampingAirborne; } float CalculateJumpVerticalSpeed(float tgtHeight) { return Mathf.Sqrt(2*tgtHeight*-Physics.gravity.y*2); } bool isTouchingCeiling() { return (hitFlags&CollisionFlags.CollidedAbove)!=0; } bool TooSteep() { return (groundNormal.y <= Mathf.Cos(cr.slopeLimit*Mathf.Deg2Rad)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using GenStrings; namespace System.Collections.Specialized.Tests { public class GetItemObjTests { public const int MAX_LEN = 50; // max length of random strings private string[] TestValues(int length) { string[] values = new string[length]; for (int i = 0; i < length; i++) values[i] = "Item" + i; return values; } private string[] TestKeys(int length) { string[] keys = new string[length]; for (int i = 0; i < length; i++) keys[i] = "keY" + i; return keys; } private string[] Test_EdgeCases() { return new string[] { "", " ", "$%^#", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; } [Theory] [InlineData(50)] [InlineData(100)] public void Add(int size) { string[] values = TestValues(size); string[] keys = TestKeys(size); HybridDictionary hd = new HybridDictionary(true); for (int i = 0; i < size; i++) { hd.Add(keys[i], values[i]); Assert.Equal(hd[keys[i].ToLower()], values[i]); Assert.Equal(hd[keys[i].ToUpper()], values[i]); } } [Fact] public void Add_EdgeCases() { string[] values = Test_EdgeCases(); string[] keys = Test_EdgeCases(); HybridDictionary hd = new HybridDictionary(true); for (int i = 0; i < values.Length; i++) { hd.Add(keys[i], values[i]); Assert.Equal(hd[keys[i].ToLower()], values[i]); Assert.Equal(hd[keys[i].ToUpper()], values[i]); } } [Fact] public void Test01() { IntlStrings intl; HybridDictionary hd; // simple string values string[] valuesShort = Test_EdgeCases(); // keys for simple string values string[] keysShort = Test_EdgeCases(); string[] valuesLong = TestValues(100); string[] keysLong = TestKeys(100); int cnt = 0; // Count Object itm; // Item // initialize IntStrings intl = new IntlStrings(); // [] HybridDictionary is constructed as expected //----------------------------------------------------------------- hd = new HybridDictionary(); // [] get Item() on empty dictionary // cnt = hd.Count; Assert.Throws<ArgumentNullException>(() => { itm = hd[null]; }); cnt = hd.Count; itm = hd["some_string"]; if (itm != null) { Assert.False(true, string.Format("Error, returned non-null for Item(some_string)")); } cnt = hd.Count; itm = hd[new Hashtable()]; if (itm != null) { Assert.False(true, string.Format("Error, returned non-null for Item(some_object)")); } // [] get Item() on short dictionary with simple strings // cnt = hd.Count; int len = valuesShort.Length; for (int i = 0; i < len; i++) { hd.Add(keysShort[i], valuesShort[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, valuesShort.Length)); } // for (int i = 0; i < len; i++) { cnt = hd.Count; itm = hd[keysShort[i]]; if (String.Compare(itm.ToString(), valuesShort[i]) != 0) { Assert.False(true, string.Format("Error, returned wrong item", i)); } } // [] get Item() on long dictionary with simple strings // hd.Clear(); cnt = hd.Count; len = valuesLong.Length; for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } // for (int i = 0; i < len; i++) { cnt = hd.Count; itm = hd[keysLong[i]]; if (String.Compare(itm.ToString(), valuesLong[i]) != 0) { Assert.False(true, string.Format("Error, returned wrong item", i)); } } // [] get Item() on long dictionary with Intl strings // Intl strings // len = valuesLong.Length; string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } cnt = hd.Count; for (int i = 0; i < len; i++) { hd.Add(intlValues[i + len], intlValues[i]); } if (hd.Count != (cnt + len)) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len)); } for (int i = 0; i < len; i++) { // cnt = hd.Count; itm = hd[intlValues[i + len]]; if (string.Compare(itm.ToString(), intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned wrong item", i)); } } // [] get Item() on short dictionary with Intl strings // len = valuesShort.Length; hd.Clear(); cnt = hd.Count; for (int i = 0; i < len; i++) { hd.Add(intlValues[i + len], intlValues[i]); } if (hd.Count != (cnt + len)) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len)); } for (int i = 0; i < len; i++) { // cnt = hd.Count; itm = hd[intlValues[i + len]]; if (String.Compare(itm.ToString(), intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned wrong item", i)); } } // // [] Case sensitivity - hashtable // len = valuesLong.Length; hd.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings } // for (int i = 0; i < len; i++) { // uppercase key itm = hd[keysLong[i].ToUpper()]; if (String.Compare(itm.ToString(), valuesLong[i].ToUpper()) != 0) { Assert.False(true, string.Format("Error, returned wrong item", i)); } if (String.Compare(itm.ToString(), valuesLong[i].ToLower()) == 0) { Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i)); } } hd.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings } // LD is case-sensitive by default for (int i = 0; i < len; i++) { // lowercase key itm = hd[keysLong[i].ToLower()]; if (itm != null) { Assert.False(true, string.Format("Error, returned non-null for lowercase key", i)); } } // // [] Case sensitivity - list // len = valuesShort.Length; hd.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings } // for (int i = 0; i < len; i++) { // uppercase key itm = hd[keysLong[i].ToUpper()]; if (String.Compare(itm.ToString(), valuesLong[i].ToUpper()) != 0) { Assert.False(true, string.Format("Error, returned wrong item", i)); } if (String.Compare(itm.ToString(), valuesLong[i].ToLower()) == 0) { Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i)); } } hd.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings } // LD is case-sensitive by default for (int i = 0; i < len; i++) { // lowercase key itm = hd[keysLong[i].ToLower()]; if (itm != null) { Assert.False(true, string.Format("Error, returned non-null for lowercase key", i)); } } // // [] get Item() in case-insensitive HD - list // hd = new HybridDictionary(true); len = valuesShort.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower()); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } for (int i = 0; i < len; i++) { itm = hd[keysLong[i].ToUpper()]; if (String.Compare(itm.ToString(), valuesLong[i].ToLower()) != 0) { Assert.False(true, string.Format("Error, returned wrong item for uppercase key", i)); } itm = hd[keysLong[i].ToLower()]; if (String.Compare(itm.ToString(), valuesLong[i].ToLower()) != 0) { Assert.False(true, string.Format("Error, returned wrong item - for lowercase key", i)); } } // [] get Item() in case-insensitive HD - hashtable // hd = new HybridDictionary(true); len = valuesLong.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower()); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } for (int i = 0; i < len; i++) { itm = hd[keysLong[i].ToUpper()]; if (String.Compare(itm.ToString(), valuesLong[i].ToLower()) != 0) { Assert.False(true, string.Format("Error, returned wrong item for uppercase key", i)); } itm = hd[keysLong[i].ToLower()]; if (String.Compare(itm.ToString(), valuesLong[i].ToLower()) != 0) { Assert.False(true, string.Format("Error, returned wrong item for lowercase key", i)); } } // // [] get Item(null) on filled HD - list // hd = new HybridDictionary(); len = valuesShort.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysShort[i], valuesShort[i]); } Assert.Throws<ArgumentNullException>(() => { itm = hd[null]; }); // [] get Item(null) on filled HD - hashtable // hd = new HybridDictionary(); len = valuesLong.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } Assert.Throws<ArgumentNullException>(() => { itm = hd[null]; }); // // [] get Item(special_object) on filled HD - list // hd = new HybridDictionary(); hd.Clear(); len = 2; ArrayList[] b = new ArrayList[len]; Hashtable[] lbl = new Hashtable[len]; for (int i = 0; i < len; i++) { lbl[i] = new Hashtable(); b[i] = new ArrayList(); hd.Add(lbl[i], b[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } for (int i = 0; i < len; i++) { itm = hd[lbl[i]]; if (!itm.Equals(b[i])) { Assert.False(true, string.Format("Error, returned wrong special object")); } } // [] get Item(special_object) on filled HD - hashtable // hd = new HybridDictionary(); hd.Clear(); len = 40; b = new ArrayList[len]; lbl = new Hashtable[len]; for (int i = 0; i < len; i++) { lbl[i] = new Hashtable(); b[i] = new ArrayList(); hd.Add(lbl[i], b[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } for (int i = 0; i < len; i++) { itm = hd[lbl[i]]; if (!itm.Equals(b[i])) { Assert.False(true, string.Format("Error, returned wrong special object")); } } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using OrchardCore.BackgroundTasks; using OrchardCore.Environment.Shell; using OrchardCore.Environment.Shell.Builders; using OrchardCore.Environment.Shell.Models; using OrchardCore.Locking.Distributed; using OrchardCore.Settings; namespace OrchardCore.Modules { internal class ModularBackgroundService : BackgroundService { private static readonly TimeSpan PollingTime = TimeSpan.FromMinutes(1); private static readonly TimeSpan MinIdleTime = TimeSpan.FromSeconds(10); private readonly ConcurrentDictionary<string, BackgroundTaskScheduler> _schedulers = new ConcurrentDictionary<string, BackgroundTaskScheduler>(); private readonly ConcurrentDictionary<string, IChangeToken> _changeTokens = new ConcurrentDictionary<string, IChangeToken>(); private readonly IShellHost _shellHost; private readonly IHttpContextAccessor _httpContextAccessor; private readonly BackgroundServiceOptions _options; private readonly ILogger _logger; private readonly IClock _clock; public ModularBackgroundService( IShellHost shellHost, IHttpContextAccessor httpContextAccessor, IOptions<BackgroundServiceOptions> options, ILogger<ModularBackgroundService> logger, IClock clock) { _shellHost = shellHost; _httpContextAccessor = httpContextAccessor; _options = options.Value; _logger = logger; _clock = clock; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { stoppingToken.Register(() => { _logger.LogInformation("'{ServiceName}' is stopping.", nameof(ModularBackgroundService)); }); if (_options.ShellWarmup) { // Ensure all ShellContext are loaded and available. await _shellHost.InitializeAsync(); } while (GetRunningShells().Count() < 1) { try { await Task.Delay(MinIdleTime, stoppingToken); } catch (TaskCanceledException) { break; } } var previousShells = Enumerable.Empty<ShellContext>(); while (!stoppingToken.IsCancellationRequested) { try { var runningShells = GetRunningShells(); await UpdateAsync(previousShells, runningShells, stoppingToken); previousShells = runningShells; var pollingDelay = Task.Delay(PollingTime, stoppingToken); await RunAsync(runningShells, stoppingToken); await WaitAsync(pollingDelay, stoppingToken); } catch (Exception ex) when (!ex.IsFatal()) { _logger.LogError(ex, "Error while executing '{ServiceName}'", nameof(ModularBackgroundService)); } } } private async Task RunAsync(IEnumerable<ShellContext> runningShells, CancellationToken stoppingToken) { await GetShellsToRun(runningShells).ForEachAsync(async shell => { var tenant = shell.Settings.Name; var schedulers = GetSchedulersToRun(tenant); _httpContextAccessor.HttpContext = shell.CreateHttpContext(); foreach (var scheduler in schedulers) { if (stoppingToken.IsCancellationRequested) { break; } var shellScope = await _shellHost.GetScopeAsync(shell.Settings); if (!_options.ShellWarmup && shellScope.ShellContext.Pipeline == null) { break; } var distributedLock = shellScope.ShellContext.ServiceProvider.GetRequiredService<IDistributedLock>(); // Try to acquire a lock before using the scope, so that a next process gets the last committed data. (var locker, var locked) = await distributedLock.TryAcquireBackgroundTaskLockAsync(scheduler.Settings); if (!locked) { _logger.LogInformation("Timeout to acquire a lock on background task '{TaskName}' on tenant '{TenantName}'.", scheduler.Name, tenant); return; } await using var acquiredLock = locker; await shellScope.UsingAsync(async scope => { var taskName = scheduler.Name; var task = scope.ServiceProvider.GetServices<IBackgroundTask>().GetTaskByName(taskName); if (task == null) { return; } var siteService = scope.ServiceProvider.GetService<ISiteService>(); if (siteService != null) { try { _httpContextAccessor.HttpContext.SetBaseUrl((await siteService.GetSiteSettingsAsync()).BaseUrl); } catch (Exception ex) when (!ex.IsFatal()) { _logger.LogError(ex, "Error while getting the base url from the site settings of the tenant '{TenantName}'.", tenant); } } var context = new BackgroundTaskEventContext(taskName, scope); var handlers = scope.ServiceProvider.GetServices<IBackgroundTaskEventHandler>(); await handlers.InvokeAsync((handler, context, token) => handler.ExecutingAsync(context, token), context, stoppingToken, _logger); try { _logger.LogInformation("Start processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); scheduler.Run(); await task.DoWorkAsync(scope.ServiceProvider, stoppingToken); _logger.LogInformation("Finished processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); } catch (Exception ex) when (!ex.IsFatal()) { _logger.LogError(ex, "Error while processing background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); context.Exception = ex; await scope.HandleExceptionAsync(ex); } await handlers.InvokeAsync((handler, context, token) => handler.ExecutedAsync(context, token), context, stoppingToken, _logger); }); } }); } private async Task UpdateAsync(IEnumerable<ShellContext> previousShells, IEnumerable<ShellContext> runningShells, CancellationToken stoppingToken) { var referenceTime = DateTime.UtcNow; await GetShellsToUpdate(previousShells, runningShells).ForEachAsync(async shell => { var tenant = shell.Settings.Name; if (stoppingToken.IsCancellationRequested) { return; } _httpContextAccessor.HttpContext = shell.CreateHttpContext(); var shellScope = await _shellHost.GetScopeAsync(shell.Settings); if (!_options.ShellWarmup && shellScope.ShellContext.Pipeline == null) { return; } await shellScope.UsingAsync(async scope => { var tasks = scope.ServiceProvider.GetServices<IBackgroundTask>(); CleanSchedulers(tenant, tasks); if (!tasks.Any()) { return; } var settingsProvider = scope.ServiceProvider.GetService<IBackgroundTaskSettingsProvider>(); _changeTokens[tenant] = settingsProvider?.ChangeToken ?? NullChangeToken.Singleton; ITimeZone timeZone = null; var siteService = scope.ServiceProvider.GetService<ISiteService>(); if (siteService != null) { try { timeZone = _clock.GetTimeZone((await siteService.GetSiteSettingsAsync()).TimeZoneId); } catch (Exception ex) when (!ex.IsFatal()) { _logger.LogError(ex, "Error while getting the time zone from the site settings of the tenant '{TenantName}'.", tenant); } } foreach (var task in tasks) { var taskName = task.GetTaskName(); if (!_schedulers.TryGetValue(tenant + taskName, out var scheduler)) { _schedulers[tenant + taskName] = scheduler = new BackgroundTaskScheduler(tenant, taskName, referenceTime, _clock); } scheduler.TimeZone = timeZone; if (!scheduler.Released && scheduler.Updated) { continue; } BackgroundTaskSettings settings = null; if (settingsProvider != null) { try { settings = await settingsProvider.GetSettingsAsync(task); } catch (Exception ex) when (!ex.IsFatal()) { _logger.LogError(ex, "Error while updating settings of background task '{TaskName}' on tenant '{TenantName}'.", taskName, tenant); } } settings ??= task.GetDefaultSettings(); if (scheduler.Released || !scheduler.Settings.Schedule.Equals(settings.Schedule)) { scheduler.ReferenceTime = referenceTime; } scheduler.Settings = settings; scheduler.Released = false; scheduler.Updated = true; } }); }); } private async Task WaitAsync(Task pollingDelay, CancellationToken stoppingToken) { try { await Task.Delay(MinIdleTime, stoppingToken); await pollingDelay; } catch (OperationCanceledException) { } } private IEnumerable<ShellContext> GetRunningShells() { return _shellHost.ListShellContexts().Where(s => s.Settings.State == TenantState.Running && (_options.ShellWarmup || s.Pipeline != null)).ToArray(); } private IEnumerable<ShellContext> GetShellsToRun(IEnumerable<ShellContext> shells) { var tenantsToRun = _schedulers.Where(s => s.Value.CanRun()).Select(s => s.Value.Tenant).Distinct().ToArray(); return shells.Where(s => tenantsToRun.Contains(s.Settings.Name)).ToArray(); } private IEnumerable<ShellContext> GetShellsToUpdate(IEnumerable<ShellContext> previousShells, IEnumerable<ShellContext> runningShells) { var released = previousShells.Where(s => s.Released).Select(s => s.Settings.Name).ToArray(); if (released.Any()) { UpdateSchedulers(released, s => s.Released = true); } var changed = _changeTokens.Where(t => t.Value.HasChanged).Select(t => t.Key).ToArray(); if (changed.Any()) { UpdateSchedulers(changed, s => s.Updated = false); } var valid = previousShells.Select(s => s.Settings.Name).Except(released).Except(changed); var tenantsToUpdate = runningShells.Select(s => s.Settings.Name).Except(valid).ToArray(); return runningShells.Where(s => tenantsToUpdate.Contains(s.Settings.Name)).ToArray(); } private IEnumerable<BackgroundTaskScheduler> GetSchedulersToRun(string tenant) { return _schedulers.Where(s => s.Value.Tenant == tenant && s.Value.CanRun()).Select(s => s.Value).ToArray(); } private void UpdateSchedulers(IEnumerable<string> tenants, Action<BackgroundTaskScheduler> action) { var keys = _schedulers.Where(kv => tenants.Contains(kv.Value.Tenant)).Select(kv => kv.Key).ToArray(); foreach (var key in keys) { if (_schedulers.TryGetValue(key, out BackgroundTaskScheduler scheduler)) { action(scheduler); } } } private void CleanSchedulers(string tenant, IEnumerable<IBackgroundTask> tasks) { var validKeys = tasks.Select(task => tenant + task.GetTaskName()).ToArray(); var keys = _schedulers.Where(kv => kv.Value.Tenant == tenant).Select(kv => kv.Key).ToArray(); foreach (var key in keys) { if (!validKeys.Contains(key)) { _schedulers.TryRemove(key, out var scheduler); } } } } internal static class HttpContextExtensions { public static void SetBaseUrl(this HttpContext context, string baseUrl) { if (Uri.TryCreate(baseUrl, UriKind.Absolute, out var uri)) { context.Request.Scheme = uri.Scheme; context.Request.Host = new HostString(uri.Host, uri.Port); context.Request.PathBase = uri.AbsolutePath; if (!String.IsNullOrWhiteSpace(uri.Query)) { context.Request.QueryString = new QueryString(uri.Query); } } } } internal static class ShellExtensions { public static HttpContext CreateHttpContext(this ShellContext shell) { var context = shell.Settings.CreateHttpContext(); context.Features.Set(new ShellContextFeature { ShellContext = shell, OriginalPathBase = String.Empty, OriginalPath = "/" }); return context; } public static HttpContext CreateHttpContext(this ShellSettings settings) { var context = new DefaultHttpContext().UseShellScopeServices(); context.Request.Scheme = "https"; var urlHost = settings.RequestUrlHost?.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); context.Request.Host = new HostString(urlHost ?? "localhost"); if (!String.IsNullOrWhiteSpace(settings.RequestUrlPrefix)) { context.Request.PathBase = "/" + settings.RequestUrlPrefix; } context.Request.Path = "/"; context.Items["IsBackground"] = true; return context; } } }
// 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. #if UseSingularityPDB /////////////////////////////////////////////////////////////////////////////// // // Microsoft Research Singularity PDB Info Library // // Copyright (c) Microsoft Corporation. All rights reserved. // // File: InthashTable.cs // // Simplified hash table implementation with integers as keys. // using System; using System.Collections; namespace Microsoft.Singularity.PdbInfo.Features { // The IntHashTable class represents a dictionary of associated keys and // values with constant lookup time. // // Objects used as keys in a hashtable must implement the GetHashCode // and Equals methods (or they can rely on the default implementations // inherited from Object if key equality is simply reference // equality). Furthermore, the GetHashCode and Equals methods of // a key object must produce the same results given the same parameters // for the entire time the key is present in the hashtable. In practical // terms, this means that key objects should be immutable, at least for // the time they are used as keys in a hashtable. // // When entries are added to a hashtable, they are placed into // buckets based on the hashcode of their keys. Subsequent lookups of // keys will use the hashcode of the keys to only search a particular // bucket, thus substantially reducing the number of key comparisons // required to find an entry. A hashtable's maximum load factor, which // can be specified when the hashtable is instantiated, determines the // maximum ratio of hashtable entries to hashtable buckets. Smaller load // factors cause faster average lookup times at the cost of increased // memory consumption. The default maximum load factor of 1.0 generally // provides the best balance between speed and size. As entries are added // to a hashtable, the hashtable's actual load factor increases, and when // the actual load factor reaches the maximum load factor value, the // number of buckets in the hashtable is automatically increased by // approximately a factor of two (to be precise, the number of hashtable // buckets is increased to the smallest prime number that is larger than // twice the current number of hashtable buckets). // // Each object provides their own hash function, accessed by calling // GetHashCode(). However, one can write their own object // implementing IHashCodeProvider and pass it to a constructor on // the IntHashTable. That hash function would be used for all objects in // the table. // // This IntHashTable is implemented to support multiple concurrent readers // and one concurrent writer without using any synchronization primitives. // All read methods essentially must protect themselves from a resize // occuring while they are running. This was done by enforcing an // ordering on inserts & removes, as well as removing some member variables // and special casing the expand code to work in a temporary array instead // of the live bucket array. All inserts must set a bucket's value and // key before setting the hash code & collision field. // // By Brian Grunkemeyer, algorithm by Patrick Dussud. // Version 1.30 2/20/2000 //| <include path='docs/doc[@for="IntHashTable"]/*' /> public class IntHashTable : IEnumerable { /* Implementation Notes: This IntHashTable uses double hashing. There are hashsize buckets in the table, and each bucket can contain 0 or 1 element. We a bit to mark whether there's been a collision when we inserted multiple elements (ie, an inserted item was hashed at least a second time and we probed this bucket, but it was already in use). Using the collision bit, we can terminate lookups & removes for elements that aren't in the hash table more quickly. We steal the most significant bit from the hash code to store the collision bit. Our hash function is of the following form: h(key, n) = h1(key) + n*h2(key) where n is the number of times we've hit a collided bucket and rehashed (on this particular lookup). Here are our hash functions: h1(key) = GetHash(key); // default implementation calls key.GetHashCode(); h2(key) = 1 + (((h1(key) >> 5) + 1) % (hashsize - 1)); The h1 can return any number. h2 must return a number between 1 and hashsize - 1 that is relatively prime to hashsize (not a problem if hashsize is prime). (Knuth's Art of Computer Programming, Vol. 3, p. 528-9) If this is true, then we are guaranteed to visit every bucket in exactly hashsize probes, since the least common multiple of hashsize and h2(key) will be hashsize * h2(key). (This is the first number where adding h2 to h1 mod hashsize will be 0 and we will search the same bucket twice). We previously used a different h2(key, n) that was not constant. That is a horrifically bad idea, unless you can prove that series will never produce any identical numbers that overlap when you mod them by hashsize, for all subranges from i to i+hashsize, for all i. It's not worth investigating, since there was no clear benefit from using that hash function, and it was broken. For efficiency reasons, we've implemented this by storing h1 and h2 in a temporary, and setting a variable called seed equal to h1. We do a probe, and if we collided, we simply add h2 to seed each time through the loop. A good test for h2() is to subclass IntHashTable, provide your own implementation of GetHash() that returns a constant, then add many items to the hash table. Make sure Count equals the number of items you inserted. -- Brian Grunkemeyer, 10/28/1999 */ // Table of prime numbers to use as hash table sizes. Each entry is the // smallest prime number larger than twice the previous entry. private readonly static int[] primes = { 11,17,23,29,37,47,59,71,89,107,131,163,197,239,293,353,431,521,631,761,919, 1103,1327,1597,1931,2333,2801,3371,4049,4861,5839,7013,8419,10103,12143,14591, 17519,21023,25229,30293,36353,43627,52361,62851,75431,90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; private int GetPrime(int minSize) { if (minSize < 0) { throw new ArgumentException("Arg_HTCapacityOverflow"); } for (int i = 0; i < primes.Length; i++) { int size = primes[i]; if (size >= minSize) { return size; } } throw new ArgumentException("Arg_HTCapacityOverflow"); } // Deleted entries have their key set to buckets // The hash table data. // This cannot be serialised private struct bucket { public int key; public int hash_coll; // Store hash code; sign bit means there was a collision. public Object val; } private bucket[] buckets; // The total number of entries in the hash table. private int count; // The total number of collision bits set in the hashtable private int occupancy; private int loadsize; private int loadFactorPerc; // 100 = 1.0 private int version; // Constructs a new hashtable. The hashtable is created with an initial // capacity of zero and a load factor of 1.0. //| <include path='docs/doc[@for="IntHashTable.IntHashTable"]/*' /> public IntHashTable() : this(0, 100) { } // Constructs a new hashtable with the given initial capacity and a load // factor of 1.0. The capacity argument serves as an indication of // the number of entries the hashtable will contain. When this number (or // an approximation) is known, specifying it in the constructor can // eliminate a number of resizing operations that would otherwise be // performed when elements are added to the hashtable. // //| <include path='docs/doc[@for="IntHashTable.IntHashTable1"]/*' /> public IntHashTable(int capacity) : this(capacity, 100) { } // Constructs a new hashtable with the given initial capacity and load // factor. The capacity argument serves as an indication of the // number of entries the hashtable will contain. When this number (or an // approximation) is known, specifying it in the constructor can eliminate // a number of resizing operations that would otherwise be performed when // elements are added to the hashtable. The loadFactorPerc argument // indicates the maximum ratio of hashtable entries to hashtable buckets. // Smaller load factors cause faster average lookup times at the cost of // increased memory consumption. A load factor of 1.0 generally provides // the best balance between speed and size. // //| <include path='docs/doc[@for="IntHashTable.IntHashTable3"]/*' /> public IntHashTable(int capacity, int loadFactorPerc) { if (capacity < 0) throw new ArgumentOutOfRangeException("capacity", "ArgumentOutOfRange_NeedNonNegNum"); if (!(loadFactorPerc >= 10 && loadFactorPerc <= 100)) throw new ArgumentOutOfRangeException("loadFactorPerc", String.Format("ArgumentOutOfRange_IntHashTableLoadFactor", 10, 100)); // Based on perf work, .72 is the optimal load factor for this table. this.loadFactorPerc = (loadFactorPerc * 72) / 100; int hashsize = GetPrime ((int)(capacity / this.loadFactorPerc)); buckets = new bucket[hashsize]; loadsize = (int)(this.loadFactorPerc * hashsize) / 100; if (loadsize >= hashsize) loadsize = hashsize-1; } // Computes the hash function: H(key, i) = h1(key) + i*h2(key, hashSize). // The out parameter seed is h1(key), while the out parameter // incr is h2(key, hashSize). Callers of this function should // add incr each time through a loop. private uint InitHash(int key, int hashsize, out uint seed, out uint incr) { // Hashcode must be positive. Also, we must not use the sign bit, since // that is used for the collision bit. uint hashcode = (uint)key & 0x7FFFFFFF; seed = (uint) hashcode; // Restriction: incr MUST be between 1 and hashsize - 1, inclusive for // the modular arithmetic to work correctly. This guarantees you'll // visit every bucket in the table exactly once within hashsize // iterations. Violate this and it'll cause obscure bugs forever. // If you change this calculation for h2(key), update putEntry too! incr = (uint)(1 + (((seed >> 5) + 1) % ((uint)hashsize - 1))); return hashcode; } // Adds an entry with the given key and value to this hashtable. An // ArgumentException is thrown if the key is null or if the key is already // present in the hashtable. // //| <include path='docs/doc[@for="IntHashTable.Add"]/*' /> public void Add(int key, Object value) { Insert(key, value, true); } // Removes all entries from this hashtable. //| <include path='docs/doc[@for="IntHashTable.Clear"]/*' /> public void Clear() { if (count == 0) return; for (int i = 0; i < buckets.Length; i++){ buckets[i].hash_coll = 0; buckets[i].key = -1; buckets[i].val = null; } count = 0; occupancy = 0; } // Checks if this hashtable contains an entry with the given key. This is // an O(1) operation. // //| <include path='docs/doc[@for="IntHashTable.Contains"]/*' /> public bool Contains(int key) { if (key < 0) { throw new ArgumentException("Argument_KeyLessThanZero"); } uint seed; uint incr; // Take a snapshot of buckets, in case another thread resizes table bucket[] lbuckets = buckets; uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr); int ntry = 0; bucket b; do { int bucketNumber = (int) (seed % (uint)lbuckets.Length); b = lbuckets[bucketNumber]; if (b.val == null) { return false; } if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && b.key == key) { return true; } seed += incr; } while (b.hash_coll < 0 && ++ntry < lbuckets.Length); return false; } // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. // //| <include path='docs/doc[@for="IntHashTable.this"]/*' /> public Object this[int key] { get { if (key < 0) { throw new ArgumentException("Argument_KeyLessThanZero"); } uint seed; uint incr; // Take a snapshot of buckets, in case another thread does a resize bucket[] lbuckets = buckets; uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr); int ntry = 0; bucket b; do { int bucketNumber = (int) (seed % (uint)lbuckets.Length); b = lbuckets[bucketNumber]; if (b.val == null) { return null; } if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && key == b.key) { return b.val; } seed += incr; }while (b.hash_coll < 0 && ++ntry < lbuckets.Length); return null; } set { Insert(key, value, false); } } // Increases the bucket count of this hashtable. This method is called from // the Insert method when the actual load factor of the hashtable reaches // the upper limit specified when the hashtable was constructed. The number // of buckets in the hashtable is increased to the smallest prime number // that is larger than twice the current number of buckets, and the entries // in the hashtable are redistributed into the new buckets using the cached // hashcodes. private void expand() { rehash( GetPrime( 1+buckets.Length*2 ) ); } // We occationally need to rehash the table to clean up the collision bits. private void rehash() { rehash( buckets.Length ); } private void rehash(int newsize) { // reset occupancy occupancy=0; // Don't replace any internal state until we've finished adding to the // new bucket[]. This serves two purposes: // 1) Allow concurrent readers to see valid hashtable contents // at all times // 2) Protect against an OutOfMemoryException while allocating this // new bucket[]. bucket[] newBuckets = new bucket[newsize]; // rehash table into new buckets int nb; for (nb = 0; nb < buckets.Length; nb++){ bucket oldb = buckets[nb]; if (oldb.val != null) { putEntry(newBuckets, oldb.key, oldb.val, oldb.hash_coll & 0x7FFFFFFF); } } // New bucket[] is good to go - replace buckets and other internal state. version++; buckets = newBuckets; loadsize = (int)(loadFactorPerc * newsize) / 100; if (loadsize >= newsize) { loadsize = newsize-1; } return; } // Returns an enumerator for this hashtable. // If modifications made to the hashtable while an enumeration is // in progress, the MoveNext and Current methods of the // enumerator will throw an exception. // //| <include path='docs/doc[@for="IntHashTable.IEnumerable.GetEnumerator"]/*' /> IEnumerator IEnumerable.GetEnumerator() { return new IntHashTableEnumerator(this); } // Internal method to compare two keys. // // Inserts an entry into this hashtable. This method is called from the Set // and Add methods. If the add parameter is true and the given key already // exists in the hashtable, an exception is thrown. private void Insert(int key, Object nvalue, bool add) { if (key < 0) { throw new ArgumentException("Argument_KeyLessThanZero"); } if (nvalue == null) { throw new ArgumentNullException("nvalue", "ArgumentNull_Value"); } if (count >= loadsize) { expand(); } else if(occupancy > loadsize && count > 100) { rehash(); } uint seed; uint incr; // Assume we only have one thread writing concurrently. Modify // buckets to contain new data, as long as we insert in the right order. uint hashcode = InitHash(key, buckets.Length, out seed, out incr); int ntry = 0; int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots // create by remove that have the collision bit set over using up new slots. do { int bucketNumber = (int) (seed % (uint)buckets.Length); // Set emptySlot number to current bucket if it is the first available bucket that we have seen // that once contained an entry and also has had a collision. // We need to search this entire collision chain because we have to ensure that there are no // duplicate entries in the table. // Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry // OR // This bucket once contained an entry but there has never been a collision if (buckets[bucketNumber].val == null) { // If we have found an available bucket that has never had a collision, but we've seen an available // bucket in the past that has the collision bit set, use the previous bucket instead if (emptySlotNumber != -1) { // Reuse slot bucketNumber = emptySlotNumber; } // We pretty much have to insert in this order. Don't set hash // code until the value & key are set appropriately. buckets[bucketNumber].val = nvalue; buckets[bucketNumber].key = key; buckets[bucketNumber].hash_coll |= (int) hashcode; count++; version++; return; } // The current bucket is in use // OR // it is available, but has had the collision bit set and we have already found an available bucket if (((buckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) && key == buckets[bucketNumber].key) { if (add) { throw new ArgumentException("Argument_AddingDuplicate__" + buckets[bucketNumber].key); } buckets[bucketNumber].val = nvalue; version++; return; } // The current bucket is full, and we have therefore collided. We need to set the collision bit // UNLESS // we have remembered an available slot previously. if (emptySlotNumber == -1) {// We don't need to set the collision bit here since we already have an empty slot if( buckets[bucketNumber].hash_coll >= 0 ) { buckets[bucketNumber].hash_coll |= unchecked((int)0x80000000); occupancy++; } } seed += incr; } while (++ntry < buckets.Length); // This code is here if and only if there were no buckets without a collision bit set in the entire table if (emptySlotNumber != -1) { // We pretty much have to insert in this order. Don't set hash // code until the value & key are set appropriately. buckets[emptySlotNumber].val = nvalue; buckets[emptySlotNumber].key = key; buckets[emptySlotNumber].hash_coll |= (int) hashcode; count++; version++; return; } // If you see this assert, make sure load factor & count are reasonable. // Then verify that our double hash function (h2, described at top of file) // meets the requirements described above. You should never see this assert. throw new InvalidOperationException("InvalidOperation_HashInsertFailed"); } private void putEntry(bucket[] newBuckets, int key, Object nvalue, int hashcode) { uint seed = (uint) hashcode; uint incr = (uint)(1 + (((seed >> 5) + 1) % ((uint)newBuckets.Length - 1))); do { int bucketNumber = (int) (seed % (uint)newBuckets.Length); if ((newBuckets[bucketNumber].val == null)) { newBuckets[bucketNumber].val = nvalue; newBuckets[bucketNumber].key = key; newBuckets[bucketNumber].hash_coll |= hashcode; return; } if( newBuckets[bucketNumber].hash_coll >= 0 ) { newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000); occupancy++; } seed += incr; } while( true ); } // Returns the number of associations in this hashtable. // //| <include path='docs/doc[@for="IntHashTable.Count"]/*' /> public int Count { get { return count; } } // Implements an enumerator for a hashtable. The enumerator uses the // internal version number of the hashtabke to ensure that no modifications // are made to the hashtable while an enumeration is in progress. private class IntHashTableEnumerator : IEnumerator { private IntHashTable hashtable; private int bucket; private int version; private bool current; private int currentKey; private Object currentValue; internal IntHashTableEnumerator(IntHashTable hashtable) { this.hashtable = hashtable; bucket = hashtable.buckets.Length; version = hashtable.version; current = false; } public bool MoveNext() { if (version != hashtable.version) throw new InvalidOperationException("InvalidOperation_EnumFailedVersion"); while (bucket > 0) { bucket--; Object val = hashtable.buckets[bucket].val; if (val != null) { currentKey = hashtable.buckets[bucket].key; currentValue = val; current = true; return true; } } current = false; return false; } public int Key { get { if (current == false) throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen"); return currentKey; } } public Object Current { get { if (current == false) throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen"); return currentValue; } } public Object Value { get { if (version != hashtable.version) throw new InvalidOperationException("InvalidOperation_EnumFailedVersion"); if (current == false) throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen"); return currentValue; } } public void Reset() { if (version != hashtable.version) throw new InvalidOperationException("InvalidOperation_EnumFailedVersion"); current = false; bucket = hashtable.buckets.Length; currentKey = -1; currentValue = null; } } } } #endif
// // Copyright (c) 2012-2021 Antmicro // // This file is licensed under the MIT License. // Full license text is available in the LICENSE file. using System; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using Antmicro.Migrant.Utilities; namespace Antmicro.Migrant.Generators { internal static class GeneratorHelper { public static void GenerateLoop(GenerationContextBase context, LocalBuilder countLocal, Action<LocalBuilder> loopAction, bool reversed = false) { var loopControlLocal = context.Generator.DeclareLocal(typeof(int)); GenerateLoop(context, countLocal, loopControlLocal, () => loopAction(loopControlLocal), reversed); } public static void GenerateLoop(GenerationContextBase context, LocalBuilder countLocal, LocalBuilder loopControlLocal, Action loopAction, bool reversed = false) { var loopLabel = context.Generator.DefineLabel(); var loopFinishLabel = context.Generator.DefineLabel(); if(reversed) { context.Generator.PushLocalValueOntoStack(countLocal); context.Generator.PushIntegerOntoStack(1); context.Generator.Emit(OpCodes.Sub); // put <<countLocal>> - 1 on stack } else { context.Generator.PushIntegerOntoStack(0); // put <<0> on stack } context.Generator.StoreLocalValueFromStack(loopControlLocal); // initialize <<loopControl>> variable using value from stack context.Generator.MarkLabel(loopLabel); context.Generator.PushLocalValueOntoStack(loopControlLocal); if(reversed) { context.Generator.PushIntegerOntoStack(-1); } else { context.Generator.PushLocalValueOntoStack(countLocal); } context.Generator.Emit(OpCodes.Beq, loopFinishLabel); loopAction(); context.Generator.PushLocalValueOntoStack(loopControlLocal); context.Generator.PushIntegerOntoStack(reversed ? -1 : 1); context.Generator.Emit(OpCodes.Add); context.Generator.StoreLocalValueFromStack(loopControlLocal); // change <<loopControl>> variable by one context.Generator.Emit(OpCodes.Br, loopLabel); // jump to the next loop iteration context.Generator.MarkLabel(loopFinishLabel); } public static void GenerateCodeCall<T1>(this ILGenerator generator, Action<T1> a) { generator.Emit(OpCodes.Call, a.Method); } public static void GenerateCodeCall<T1, T2>(this ILGenerator generator, Action<T1, T2> a) { generator.Emit(OpCodes.Call, a.Method); } public static void GenerateCodeCall<T1, T2, T3>(this ILGenerator generator, Action<T1, T2, T3> a) { generator.Emit(OpCodes.Call, a.Method); } public static void GenerateCodeCall<T1, T2, T3, T4, T5>(this ILGenerator generator, Action<T1, T2, T3, T4, T5> a) { generator.Emit(OpCodes.Call, a.Method); } public static void GenerateCodeFCall<T1, TResult>(this ILGenerator generator, Func<T1, TResult> f) { generator.Emit(OpCodes.Call, f.Method); } public static void GenerateCodeFCall<T1, T2, T3, TResult>(this ILGenerator generator, Func<T1, T2, T3, TResult> f) { generator.Emit(OpCodes.Call, f.Method); } public static void Call(this ILGenerator generator, Expression<Action> expression) { generator.Emit(OpCodes.Call, Helpers.GetMethodInfo(expression)); } public static void Call<T>(this ILGenerator generator, Expression<Action<T>> expression) { generator.Emit(OpCodes.Call, Helpers.GetMethodInfo(expression)); } public static void Callvirt(this ILGenerator generator, Expression<Action> expression) { generator.Emit(OpCodes.Callvirt, Helpers.GetMethodInfo(expression)); } public static void Callvirt<T>(this ILGenerator generator, Expression<Action<T>> expression) { generator.Emit(OpCodes.Callvirt, Helpers.GetMethodInfo(expression)); } public static void PushPropertyValueOntoStack<T, TResult>(this ILGenerator generator, Expression<Func<T, TResult>> expression) { generator.Emit(OpCodes.Call, Helpers.GetPropertyGetterInfo(expression)); } public static void PushFieldValueOntoStack<T, TResult>(this ILGenerator generator, Expression<Func<T, TResult>> expression) { generator.Emit(OpCodes.Ldfld, Helpers.GetFieldInfo(expression)); } public static void PushFieldInfoOntoStack(this ILGenerator generator, FieldInfo finfo) { generator.Emit(OpCodes.Ldtoken, finfo); if(finfo.DeclaringType.IsGenericType) { generator.Emit(OpCodes.Ldtoken, finfo.ReflectedType); generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<object, object>(x => FieldInfo.GetFieldFromHandle(finfo.FieldHandle, new RuntimeTypeHandle()))); } else { generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<object, object>(x => FieldInfo.GetFieldFromHandle(finfo.FieldHandle))); } } public static void PushTypeOntoStack(this ILGenerator generator, Type type) { generator.Emit(OpCodes.Ldtoken, type); generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<RuntimeTypeHandle, Type>(o => Type.GetTypeFromHandle(o))); // loads value of <<typeToGenerate>> onto stack } public static void PushLocalValueOntoStack(this ILGenerator generator, LocalBuilder local) { switch(local.LocalIndex) { case 0: generator.Emit(OpCodes.Ldloc_0); break; case 1: generator.Emit(OpCodes.Ldloc_1); break; case 2: generator.Emit(OpCodes.Ldloc_2); break; case 3: generator.Emit(OpCodes.Ldloc_3); break; default: if(local.LocalIndex < 256) { generator.Emit(OpCodes.Ldloc_S, (byte)local.LocalIndex); } else { generator.Emit(OpCodes.Ldloc, local); } break; } } public static void PushLocalAddressOntoStack(this ILGenerator generator, LocalBuilder local) { if(local.LocalIndex < 256) { generator.Emit(OpCodes.Ldloca_S, (byte)local.LocalIndex); } else { generator.Emit(OpCodes.Ldloca, local); } } public static void StoreLocalValueFromStack(this ILGenerator generator, LocalBuilder local) { switch(local.LocalIndex) { case 0: generator.Emit(OpCodes.Stloc_0); break; case 1: generator.Emit(OpCodes.Stloc_1); break; case 2: generator.Emit(OpCodes.Stloc_2); break; case 3: generator.Emit(OpCodes.Stloc_3); break; default: if(local.LocalIndex < 256) { generator.Emit(OpCodes.Stloc_S, (byte)local.LocalIndex); } else { generator.Emit(OpCodes.Stloc, local); } break; } } public static void PushIntegerOntoStack(this ILGenerator generator, int value) { switch(value) { case -1: generator.Emit(OpCodes.Ldc_I4_M1); break; case 0: generator.Emit(OpCodes.Ldc_I4_0); break; case 1: generator.Emit(OpCodes.Ldc_I4_1); break; case 2: generator.Emit(OpCodes.Ldc_I4_2); break; case 3: generator.Emit(OpCodes.Ldc_I4_3); break; case 4: generator.Emit(OpCodes.Ldc_I4_4); break; case 5: generator.Emit(OpCodes.Ldc_I4_5); break; case 6: generator.Emit(OpCodes.Ldc_I4_6); break; case 7: generator.Emit(OpCodes.Ldc_I4_7); break; case 8: generator.Emit(OpCodes.Ldc_I4_8); break; default: if(value > -129 && value < 128) { generator.Emit(OpCodes.Ldc_I4_S, value); } else { generator.Emit(OpCodes.Ldc_I4, value); } break; } } public static void PushVariableOntoStack(this ILGenerator generator, Variable var) { var.PushValueOntoStack(generator); } public static void PushVariableAddressOntoStack(this ILGenerator generator, Variable var) { var.PushAddressOntoStack(generator); } public static void StoreVariableValueFromStack(this ILGenerator generator, Variable var) { var.StoreValueFromStack(generator); } [Conditional("DEBUG")] public static void Debug_PrintValueFromLocal<T>(this ILGenerator generator, LocalBuilder local, string message = null) { generator.Emit(OpCodes.Ldloc, local); generator.Debug_PrintValueFromStack<T>(message); } [Conditional("DEBUG")] public static void Debug_PrintValueFromStack<T>(this ILGenerator generator, string message = null) { generator.Emit(OpCodes.Ldstr, message ?? "DEBUG"); GenerateCodeCall<T, string>(generator, (v, m) => { Console.WriteLine("{0}: {1}", m, v); }); } #if NET [Obsolete("AppDomain.DefineDynamicAssembly is not available in .NET Standard 2.0 and above")] [Conditional("DEBUG")] public static void DumpToLibrary<T>(GenerationContextBase context, Action<GenerationContextBase> generateCodeAction, string postfix = null) { throw new NotImplementedException(); } #else [Conditional("DEBUG")] public static void DumpToLibrary<T>(GenerationContextBase context, Action<GenerationContextBase> generateCodeAction, string postfix = null) { var invokeMethod = typeof(T).GetMethod("Invoke"); var returnType = invokeMethod.ReturnType; var argumentTypes = invokeMethod.GetParameters().Select(x => x.ParameterType).ToArray(); if(postfix != null) { foreach(var c in new[] { '`', '<', '>', ',', '[', ']' }) { postfix = postfix.Replace(c, '_'); } } var name = string.Format("{0}_{1}", counter++, postfix); var aname = new AssemblyName(name); var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(aname, AssemblyBuilderAccess.Save); var customAttribute = new CustomAttributeBuilder( typeof(DebuggableAttribute).GetConstructor(new[] { typeof(DebuggableAttribute.DebuggingModes) }), new object[] { DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.Default } ); assembly.SetCustomAttribute(customAttribute); var module = assembly.DefineDynamicModule(aname.Name, aname.Name + ".dll", true); var type = module.DefineType(typeof(T).Name); var method = type.DefineMethod(invokeMethod.Name, MethodAttributes.Public | MethodAttributes.Static, returnType, argumentTypes); var generator = method.GetILGenerator(); generateCodeAction(context.WithGenerator(generator)); generator.Emit(OpCodes.Ret); type.CreateType(); assembly.Save(aname.Name + ".dll"); } private static int counter; #endif } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.CoreModules.World.Wind; namespace OpenSim.Region.CoreModules.World.Wind.Plugins { class ConfigurableWind : Mono.Addins.TypeExtensionNode, IWindModelPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Vector2[] m_windSpeeds = new Vector2[16 * 16]; //private Random m_rndnums = new Random(Environment.TickCount); private float m_avgStrength = 5.0f; // Average magnitude of the wind vector private float m_avgDirection = 0.0f; // Average direction of the wind in degrees private float m_varStrength = 5.0f; // Max Strength Variance private float m_varDirection = 30.0f;// Max Direction Variance private float m_rateChange = 1.0f; // private Vector2 m_curPredominateWind = new Vector2(); #region IPlugin Members public string Version { get { return "1.0.0.0"; } } public string Name { get { return "ConfigurableWind"; } } public void Initialize() { } #endregion #region IDisposable Members public void Dispose() { m_windSpeeds = null; } #endregion #region IWindModelPlugin Members public void WindConfig(OpenSim.Region.Framework.Scenes.Scene scene, Nini.Config.IConfig windConfig) { if (windConfig != null) { // Uses strength value if avg_strength not specified m_avgStrength = windConfig.GetFloat("strength", 5.0F); m_avgStrength = windConfig.GetFloat("avg_strength", 5.0F); m_avgDirection = windConfig.GetFloat("avg_direction", 0.0F); m_varStrength = windConfig.GetFloat("var_strength", 5.0F); m_varDirection = windConfig.GetFloat("var_direction", 30.0F); m_rateChange = windConfig.GetFloat("rate_change", 1.0F); LogSettings(); } } public void WindUpdate(uint frame) { double avgAng = m_avgDirection * (Math.PI/180.0f); double varDir = m_varDirection * (Math.PI/180.0f); // Prevailing wind algorithm // Inspired by Kanker Greenacre // TODO: // * This should probably be based on in-world time. // * should probably move all these local variables to class members and constants double time = DateTime.Now.TimeOfDay.Seconds / 86400.0f; double theta = time * (2 * Math.PI) * m_rateChange; double offset = Math.Sin(theta) * Math.Sin(theta*2) * Math.Sin(theta*9) * Math.Cos(theta*4); double windDir = avgAng + (varDir * offset); offset = Math.Sin(theta) * Math.Sin(theta*4) + (Math.Sin(theta*13) / 3); double windSpeed = m_avgStrength + (m_varStrength * offset); if (windSpeed<0) windSpeed=0; m_curPredominateWind.X = (float)Math.Cos(windDir); m_curPredominateWind.Y = (float)Math.Sin(windDir); m_curPredominateWind.Normalize(); m_curPredominateWind.X *= (float)windSpeed; m_curPredominateWind.Y *= (float)windSpeed; for (int y = 0; y < 16; y++) { for (int x = 0; x < 16; x++) { m_windSpeeds[y * 16 + x] = m_curPredominateWind; } } } public Vector3 WindSpeed(float fX, float fY, float fZ) { return new Vector3(m_curPredominateWind, 0.0f); } // Wind set not implemented. public void WindSet(int type, Vector3 loc, Vector3 speed) { } public Vector2[] WindLLClientArray(Vector3 pos) { return m_windSpeeds; } public string Description { get { return "Provides a predominate wind direction that can change within configured variances for direction and speed."; } } public System.Collections.Generic.Dictionary<string, string> WindParams() { Dictionary<string, string> Params = new Dictionary<string, string>(); Params.Add("avgStrength", "average wind strength"); Params.Add("avgDirection", "average wind direction in degrees"); Params.Add("varStrength", "allowable variance in wind strength"); Params.Add("varDirection", "allowable variance in wind direction in +/- degrees"); Params.Add("rateChange", "rate of change"); return Params; } public void WindParamSet(string param, float value) { switch (param) { case "avgStrength": m_avgStrength = value; break; case "avgDirection": m_avgDirection = value; break; case "varStrength": m_varStrength = value; break; case "varDirection": m_varDirection = value; break; case "rateChange": m_rateChange = value; break; } } public float WindParamGet(string param) { switch (param) { case "avgStrength": return m_avgStrength; case "avgDirection": return m_avgDirection; case "varStrength": return m_varStrength; case "varDirection": return m_varDirection; case "rateChange": return m_rateChange; default: throw new Exception(String.Format("Unknown {0} parameter {1}", this.Name, param)); } } #endregion private void LogSettings() { m_log.InfoFormat("[ConfigurableWind] Average Strength : {0}", m_avgStrength); m_log.InfoFormat("[ConfigurableWind] Average Direction : {0}", m_avgDirection); m_log.InfoFormat("[ConfigurableWind] Varience Strength : {0}", m_varStrength); m_log.InfoFormat("[ConfigurableWind] Varience Direction : {0}", m_varDirection); m_log.InfoFormat("[ConfigurableWind] Rate Change : {0}", m_rateChange); } #region IWindModelPlugin Members #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! 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.Cloud.MediaTranslation.V1Beta1 { /// <summary>Settings for <see cref="SpeechTranslationServiceClient"/> instances.</summary> public sealed partial class SpeechTranslationServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="SpeechTranslationServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="SpeechTranslationServiceSettings"/>.</returns> public static SpeechTranslationServiceSettings GetDefault() => new SpeechTranslationServiceSettings(); /// <summary> /// Constructs a new <see cref="SpeechTranslationServiceSettings"/> object with default settings. /// </summary> public SpeechTranslationServiceSettings() { } private SpeechTranslationServiceSettings(SpeechTranslationServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); StreamingTranslateSpeechSettings = existing.StreamingTranslateSpeechSettings; StreamingTranslateSpeechStreamingSettings = existing.StreamingTranslateSpeechStreamingSettings; OnCopy(existing); } partial void OnCopy(SpeechTranslationServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>SpeechTranslationServiceClient.StreamingTranslateSpeech</c> and /// <c>SpeechTranslationServiceClient.StreamingTranslateSpeechAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 400 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings StreamingTranslateSpeechSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(400000))); /// <summary> /// <see cref="gaxgrpc::BidirectionalStreamingSettings"/> for calls to /// <c>SpeechTranslationServiceClient.StreamingTranslateSpeech</c> and /// <c>SpeechTranslationServiceClient.StreamingTranslateSpeechAsync</c>. /// </summary> /// <remarks>The default local send queue size is 100.</remarks> public gaxgrpc::BidirectionalStreamingSettings StreamingTranslateSpeechStreamingSettings { get; set; } = new gaxgrpc::BidirectionalStreamingSettings(100); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="SpeechTranslationServiceSettings"/> object.</returns> public SpeechTranslationServiceSettings Clone() => new SpeechTranslationServiceSettings(this); } /// <summary> /// Builder class for <see cref="SpeechTranslationServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class SpeechTranslationServiceClientBuilder : gaxgrpc::ClientBuilderBase<SpeechTranslationServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public SpeechTranslationServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public SpeechTranslationServiceClientBuilder() { UseJwtAccessWithScopes = SpeechTranslationServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref SpeechTranslationServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SpeechTranslationServiceClient> task); /// <summary>Builds the resulting client.</summary> public override SpeechTranslationServiceClient Build() { SpeechTranslationServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<SpeechTranslationServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<SpeechTranslationServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private SpeechTranslationServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return SpeechTranslationServiceClient.Create(callInvoker, Settings); } private async stt::Task<SpeechTranslationServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return SpeechTranslationServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => SpeechTranslationServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => SpeechTranslationServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => SpeechTranslationServiceClient.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>SpeechTranslationService client wrapper, for convenient use.</summary> /// <remarks> /// Provides translation from/to media types. /// </remarks> public abstract partial class SpeechTranslationServiceClient { /// <summary> /// The default endpoint for the SpeechTranslationService service, which is a host of /// "mediatranslation.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "mediatranslation.googleapis.com:443"; /// <summary>The default SpeechTranslationService scopes.</summary> /// <remarks> /// The default SpeechTranslationService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); 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="SpeechTranslationServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="SpeechTranslationServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="SpeechTranslationServiceClient"/>.</returns> public static stt::Task<SpeechTranslationServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new SpeechTranslationServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="SpeechTranslationServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="SpeechTranslationServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="SpeechTranslationServiceClient"/>.</returns> public static SpeechTranslationServiceClient Create() => new SpeechTranslationServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="SpeechTranslationServiceClient"/> 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="SpeechTranslationServiceSettings"/>.</param> /// <returns>The created <see cref="SpeechTranslationServiceClient"/>.</returns> internal static SpeechTranslationServiceClient Create(grpccore::CallInvoker callInvoker, SpeechTranslationServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } SpeechTranslationService.SpeechTranslationServiceClient grpcClient = new SpeechTranslationService.SpeechTranslationServiceClient(callInvoker); return new SpeechTranslationServiceClientImpl(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 SpeechTranslationService client</summary> public virtual SpeechTranslationService.SpeechTranslationServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Bidirectional streaming methods for /// <see cref="StreamingTranslateSpeech(gaxgrpc::CallSettings,gaxgrpc::BidirectionalStreamingSettings)"/>. /// </summary> public abstract partial class StreamingTranslateSpeechStream : gaxgrpc::BidirectionalStreamingBase<StreamingTranslateSpeechRequest, StreamingTranslateSpeechResponse> { } /// <summary> /// Performs bidirectional streaming speech translation: receive results while /// sending audio. This method is only available via the gRPC API (not REST). /// </summary> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param> /// <returns>The client-server stream.</returns> public virtual StreamingTranslateSpeechStream StreamingTranslateSpeech(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) => throw new sys::NotImplementedException(); } /// <summary>SpeechTranslationService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Provides translation from/to media types. /// </remarks> public sealed partial class SpeechTranslationServiceClientImpl : SpeechTranslationServiceClient { private readonly gaxgrpc::ApiBidirectionalStreamingCall<StreamingTranslateSpeechRequest, StreamingTranslateSpeechResponse> _callStreamingTranslateSpeech; /// <summary> /// Constructs a client wrapper for the SpeechTranslationService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="SpeechTranslationServiceSettings"/> used within this client. /// </param> public SpeechTranslationServiceClientImpl(SpeechTranslationService.SpeechTranslationServiceClient grpcClient, SpeechTranslationServiceSettings settings) { GrpcClient = grpcClient; SpeechTranslationServiceSettings effectiveSettings = settings ?? SpeechTranslationServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callStreamingTranslateSpeech = clientHelper.BuildApiCall<StreamingTranslateSpeechRequest, StreamingTranslateSpeechResponse>(grpcClient.StreamingTranslateSpeech, effectiveSettings.StreamingTranslateSpeechSettings, effectiveSettings.StreamingTranslateSpeechStreamingSettings); Modify_ApiCall(ref _callStreamingTranslateSpeech); Modify_StreamingTranslateSpeechApiCall(ref _callStreamingTranslateSpeech); 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_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiBidirectionalStreamingCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_StreamingTranslateSpeechApiCall(ref gaxgrpc::ApiBidirectionalStreamingCall<StreamingTranslateSpeechRequest, StreamingTranslateSpeechResponse> call); partial void OnConstruction(SpeechTranslationService.SpeechTranslationServiceClient grpcClient, SpeechTranslationServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC SpeechTranslationService client</summary> public override SpeechTranslationService.SpeechTranslationServiceClient GrpcClient { get; } partial void Modify_StreamingTranslateSpeechRequestCallSettings(ref gaxgrpc::CallSettings settings); partial void Modify_StreamingTranslateSpeechRequestRequest(ref StreamingTranslateSpeechRequest request); internal sealed partial class StreamingTranslateSpeechStreamImpl : StreamingTranslateSpeechStream { /// <summary>Construct the bidirectional streaming method for <c>StreamingTranslateSpeech</c>.</summary> /// <param name="service">The service containing this streaming method.</param> /// <param name="call">The underlying gRPC duplex streaming call.</param> /// <param name="writeBuffer"> /// The <see cref="gaxgrpc::BufferedClientStreamWriter{StreamingTranslateSpeechRequest}"/> instance /// associated with this streaming call. /// </param> public StreamingTranslateSpeechStreamImpl(SpeechTranslationServiceClientImpl service, grpccore::AsyncDuplexStreamingCall<StreamingTranslateSpeechRequest, StreamingTranslateSpeechResponse> call, gaxgrpc::BufferedClientStreamWriter<StreamingTranslateSpeechRequest> writeBuffer) { _service = service; GrpcCall = call; _writeBuffer = writeBuffer; } private SpeechTranslationServiceClientImpl _service; private gaxgrpc::BufferedClientStreamWriter<StreamingTranslateSpeechRequest> _writeBuffer; public override grpccore::AsyncDuplexStreamingCall<StreamingTranslateSpeechRequest, StreamingTranslateSpeechResponse> GrpcCall { get; } private StreamingTranslateSpeechRequest ModifyRequest(StreamingTranslateSpeechRequest request) { _service.Modify_StreamingTranslateSpeechRequestRequest(ref request); return request; } public override stt::Task TryWriteAsync(StreamingTranslateSpeechRequest message) => _writeBuffer.TryWriteAsync(ModifyRequest(message)); public override stt::Task WriteAsync(StreamingTranslateSpeechRequest message) => _writeBuffer.WriteAsync(ModifyRequest(message)); public override stt::Task TryWriteAsync(StreamingTranslateSpeechRequest message, grpccore::WriteOptions options) => _writeBuffer.TryWriteAsync(ModifyRequest(message), options); public override stt::Task WriteAsync(StreamingTranslateSpeechRequest message, grpccore::WriteOptions options) => _writeBuffer.WriteAsync(ModifyRequest(message), options); public override stt::Task TryWriteCompleteAsync() => _writeBuffer.TryWriteCompleteAsync(); public override stt::Task WriteCompleteAsync() => _writeBuffer.WriteCompleteAsync(); } /// <summary> /// Performs bidirectional streaming speech translation: receive results while /// sending audio. This method is only available via the gRPC API (not REST). /// </summary> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param> /// <returns>The client-server stream.</returns> public override SpeechTranslationServiceClient.StreamingTranslateSpeechStream StreamingTranslateSpeech(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) { Modify_StreamingTranslateSpeechRequestCallSettings(ref callSettings); gaxgrpc::BidirectionalStreamingSettings effectiveStreamingSettings = streamingSettings ?? _callStreamingTranslateSpeech.StreamingSettings; grpccore::AsyncDuplexStreamingCall<StreamingTranslateSpeechRequest, StreamingTranslateSpeechResponse> call = _callStreamingTranslateSpeech.Call(callSettings); gaxgrpc::BufferedClientStreamWriter<StreamingTranslateSpeechRequest> writeBuffer = new gaxgrpc::BufferedClientStreamWriter<StreamingTranslateSpeechRequest>(call.RequestStream, effectiveStreamingSettings.BufferedClientWriterCapacity); return new StreamingTranslateSpeechStreamImpl(this, call, writeBuffer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.Serialization; namespace System.Collections.Specialized { /// <devdoc> /// <para> /// OrderedDictionary offers IDictionary syntax with ordering. Objects /// added or inserted in an IOrderedDictionary must have both a key and an index, and /// can be retrieved by either. /// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of /// parameters, while almost all other DBs do not. DataKeyArray also uses it so /// DataKeys can be retrieved by either their name or their index. /// /// OrderedDictionary implements IDeserializationCallback because it needs to have the /// contained ArrayList and Hashtable deserialized before it tries to get its count and objects. /// </para> /// </devdoc> [Serializable] public class OrderedDictionary : IOrderedDictionary, ISerializable, IDeserializationCallback { private ArrayList _objectsArray; private Hashtable _objectsTable; private int _initialCapacity; private IEqualityComparer _comparer; private bool _readOnly; private Object _syncRoot; private SerializationInfo _siInfo; //A temporary variable which we need during deserialization. private const string KeyComparerName = "KeyComparer"; private const string ArrayListName = "ArrayList"; private const string ReadOnlyName = "ReadOnly"; private const string InitCapacityName = "InitialCapacity"; public OrderedDictionary() : this(0) { } public OrderedDictionary(int capacity) : this(capacity, null) { } public OrderedDictionary(IEqualityComparer comparer) : this(0, comparer) { } public OrderedDictionary(int capacity, IEqualityComparer comparer) { _initialCapacity = capacity; _comparer = comparer; } private OrderedDictionary(OrderedDictionary dictionary) { Debug.Assert(dictionary != null); _readOnly = true; _objectsArray = dictionary._objectsArray; _objectsTable = dictionary._objectsTable; _comparer = dictionary._comparer; _initialCapacity = dictionary._initialCapacity; } protected OrderedDictionary(SerializationInfo info, StreamingContext context) { // We can't do anything with the keys and values until the entire graph has been deserialized // and getting Counts and objects won't fail. For the time being, we'll just cache this. // The graph is not valid until OnDeserialization has been called. _siInfo = info; } /// <devdoc> /// Gets the size of the table. /// </devdoc> public int Count { get { return objectsArray.Count; } } /// <devdoc> /// Indicates that the collection can grow. /// </devdoc> bool IDictionary.IsFixedSize { get { return _readOnly; } } /// <devdoc> /// Indicates that the collection is not read-only /// </devdoc> public bool IsReadOnly { get { return _readOnly; } } /// <devdoc> /// Indicates that this class is not synchronized /// </devdoc> bool ICollection.IsSynchronized { get { return false; } } /// <devdoc> /// Gets the collection of keys in the table in order. /// </devdoc> public ICollection Keys { get { return new OrderedDictionaryKeyValueCollection(objectsArray, true); } } private ArrayList objectsArray { get { if (_objectsArray == null) { _objectsArray = new ArrayList(_initialCapacity); } return _objectsArray; } } private Hashtable objectsTable { get { if (_objectsTable == null) { _objectsTable = new Hashtable(_initialCapacity, _comparer); } return _objectsTable; } } /// <devdoc> /// The SyncRoot object. Not used because IsSynchronized is false /// </devdoc> object ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); } return _syncRoot; } } /// <devdoc> /// Gets or sets the object at the specified index /// </devdoc> public object this[int index] { get { return ((DictionaryEntry)objectsArray[index]).Value; } set { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (index < 0 || index >= objectsArray.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } object key = ((DictionaryEntry)objectsArray[index]).Key; objectsArray[index] = new DictionaryEntry(key, value); objectsTable[key] = value; } } /// <devdoc> /// Gets or sets the object with the specified key /// </devdoc> public object this[object key] { get { return objectsTable[key]; } set { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (objectsTable.Contains(key)) { objectsTable[key] = value; objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value); } else { Add(key, value); } } } /// <devdoc> /// Returns an arrayList of the values in the table /// </devdoc> public ICollection Values { get { return new OrderedDictionaryKeyValueCollection(objectsArray, false); } } /// <devdoc> /// Adds a new entry to the table with the lowest-available index. /// </devdoc> public void Add(object key, object value) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } objectsTable.Add(key, value); objectsArray.Add(new DictionaryEntry(key, value)); } /// <devdoc> /// Clears all elements in the table. /// </devdoc> public void Clear() { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } objectsTable.Clear(); objectsArray.Clear(); } /// <devdoc> /// Returns a readonly OrderedDictionary for the given OrderedDictionary. /// </devdoc> public OrderedDictionary AsReadOnly() { return new OrderedDictionary(this); } /// <devdoc> /// Returns true if the key exists in the table, false otherwise. /// </devdoc> public bool Contains(object key) { return objectsTable.Contains(key); } /// <devdoc> /// Copies the table to an array. This will not preserve order. /// </devdoc> public void CopyTo(Array array, int index) { objectsTable.CopyTo(array, index); } private int IndexOfKey(object key) { for (int i = 0; i < objectsArray.Count; i++) { object o = ((DictionaryEntry)objectsArray[i]).Key; if (_comparer != null) { if (_comparer.Equals(o, key)) { return i; } } else { if (o.Equals(key)) { return i; } } } return -1; } /// <devdoc> /// Inserts a new object at the given index with the given key. /// </devdoc> public void Insert(int index, object key, object value) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (index > Count || index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } objectsTable.Add(key, value); objectsArray.Insert(index, new DictionaryEntry(key, value)); } /// <devdoc> /// Removes the entry at the given index. /// </devdoc> public void RemoveAt(int index) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (index >= Count || index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } object key = ((DictionaryEntry)objectsArray[index]).Key; objectsArray.RemoveAt(index); objectsTable.Remove(key); } /// <devdoc> /// Removes the entry with the given key. /// </devdoc> public void Remove(object key) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (key == null) { throw new ArgumentNullException(nameof(key)); } int index = IndexOfKey(key); if (index < 0) { return; } objectsTable.Remove(key); objectsArray.RemoveAt(index); } #region IDictionary implementation public virtual IDictionaryEnumerator GetEnumerator() { return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry); } #endregion #region IEnumerable implementation IEnumerator IEnumerable.GetEnumerator() { return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry); } #endregion #region ISerializable implementation public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer)); info.AddValue(ReadOnlyName, _readOnly); info.AddValue(InitCapacityName, _initialCapacity); object[] serArray = new object[Count]; _objectsArray.CopyTo(serArray); info.AddValue(ArrayListName, serArray); } #endregion #region IDeserializationCallback implementation void IDeserializationCallback.OnDeserialization(object sender) { if (_siInfo == null) { throw new SerializationException(SR.Serialization_InvalidOnDeser); } _comparer = (IEqualityComparer)_siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer)); _readOnly = _siInfo.GetBoolean(ReadOnlyName); _initialCapacity = _siInfo.GetInt32(InitCapacityName); object[] serArray = (object[])_siInfo.GetValue(ArrayListName, typeof(object[])); if (serArray != null) { foreach (object o in serArray) { DictionaryEntry entry; try { // DictionaryEntry is a value type, so it can only be casted. entry = (DictionaryEntry)o; } catch { throw new SerializationException(SR.OrderedDictionary_SerializationMismatch); } objectsArray.Add(entry); objectsTable.Add(entry.Key, entry.Value); } } } #endregion /// <devdoc> /// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries /// in the order by index. /// </devdoc> private class OrderedDictionaryEnumerator : IDictionaryEnumerator { private int _objectReturnType; internal const int Keys = 1; internal const int Values = 2; internal const int DictionaryEntry = 3; private IEnumerator _arrayEnumerator; internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType) { _arrayEnumerator = array.GetEnumerator(); _objectReturnType = objectReturnType; } /// <devdoc> /// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed. /// </devdoc> public object Current { get { if (_objectReturnType == Keys) { return ((DictionaryEntry)_arrayEnumerator.Current).Key; } if (_objectReturnType == Values) { return ((DictionaryEntry)_arrayEnumerator.Current).Value; } return Entry; } } /// <devdoc> /// Retrieves the current DictionaryEntry /// </devdoc> public DictionaryEntry Entry { get { return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value); } } /// <devdoc> /// Retrieves the key of the current DictionaryEntry /// </devdoc> public object Key { get { return ((DictionaryEntry)_arrayEnumerator.Current).Key; } } /// <devdoc> /// Retrieves the value of the current DictionaryEntry /// </devdoc> public object Value { get { return ((DictionaryEntry)_arrayEnumerator.Current).Value; } } /// <devdoc> /// Moves the enumerator pointer to the next member /// </devdoc> public bool MoveNext() { return _arrayEnumerator.MoveNext(); } /// <devdoc> /// Resets the enumerator pointer to the beginning. /// </devdoc> public void Reset() { _arrayEnumerator.Reset(); } } /// <devdoc> /// OrderedDictionaryKeyValueCollection implements a collection for the Values and Keys properties /// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter /// was called. /// </devdoc> private class OrderedDictionaryKeyValueCollection : ICollection { private ArrayList _objects; private bool _isKeys; public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys) { _objects = array; _isKeys = isKeys; } void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); foreach (object o in _objects) { array.SetValue(_isKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index); index++; } } int ICollection.Count { get { return _objects.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return _objects.SyncRoot; } } IEnumerator IEnumerable.GetEnumerator() { return new OrderedDictionaryEnumerator(_objects, _isKeys == true ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values); } } } }
/* * Exchange Web Services Managed API * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; /// <summary> /// Represents an object that can be used to store user-defined configuration settings. /// </summary> public class UserConfiguration { private const ExchangeVersion ObjectVersion = ExchangeVersion.Exchange2010; // For consistency with ServiceObject behavior, access to ItemId is permitted for a new object. private const UserConfigurationProperties PropertiesAvailableForNewObject = UserConfigurationProperties.BinaryData | UserConfigurationProperties.Dictionary | UserConfigurationProperties.XmlData; private const UserConfigurationProperties NoProperties = (UserConfigurationProperties)0; // TODO: Consider using SimplePropertyBag class to store XmlData & BinaryData property values. private ExchangeService service; private string name; private FolderId parentFolderId = null; private ItemId itemId = null; private UserConfigurationDictionary dictionary = null; private byte[] xmlData = null; private byte[] binaryData = null; private UserConfigurationProperties propertiesAvailableForAccess; private UserConfigurationProperties updatedProperties; /// <summary> /// Indicates whether changes trigger an update or create operation. /// </summary> private bool isNew = false; /// <summary> /// Initializes a new instance of <see cref="UserConfiguration"/> class. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> public UserConfiguration(ExchangeService service) : this(service, PropertiesAvailableForNewObject) { } /// <summary> /// Writes a byte array to Xml. /// </summary> /// <param name="writer">The writer.</param> /// <param name="byteArray">Byte array to write.</param> /// <param name="xmlElementName">Name of the Xml element.</param> private static void WriteByteArrayToXml( EwsServiceXmlWriter writer, byte[] byteArray, string xmlElementName) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteByteArrayToXml", "writer is null"); EwsUtilities.Assert( xmlElementName != null, "UserConfiguration.WriteByteArrayToXml", "xmlElementName is null"); writer.WriteStartElement(XmlNamespace.Types, xmlElementName); if (byteArray != null && byteArray.Length > 0) { writer.WriteValue(Convert.ToBase64String(byteArray), xmlElementName); } writer.WriteEndElement(); } /// <summary> /// Writes to Xml. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="name">The user configuration name.</param> /// <param name="parentFolderId">The Id of the folder containing the user configuration.</param> internal static void WriteUserConfigurationNameToXml( EwsServiceXmlWriter writer, XmlNamespace xmlNamespace, string name, FolderId parentFolderId) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteUserConfigurationNameToXml", "writer is null"); EwsUtilities.Assert( name != null, "UserConfiguration.WriteUserConfigurationNameToXml", "name is null"); EwsUtilities.Assert( parentFolderId != null, "UserConfiguration.WriteUserConfigurationNameToXml", "parentFolderId is null"); writer.WriteStartElement(xmlNamespace, XmlElementNames.UserConfigurationName); writer.WriteAttributeValue(XmlAttributeNames.Name, name); parentFolderId.WriteToXml(writer); writer.WriteEndElement(); } /// <summary> /// Initializes a new instance of <see cref="UserConfiguration"/> class. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="requestedProperties">The properties requested for this user configuration.</param> internal UserConfiguration(ExchangeService service, UserConfigurationProperties requestedProperties) { EwsUtilities.ValidateParam(service, "service"); if (service.RequestedServerVersion < UserConfiguration.ObjectVersion) { throw new ServiceVersionException( string.Format( Strings.ObjectTypeIncompatibleWithRequestVersion, this.GetType().Name, UserConfiguration.ObjectVersion)); } this.service = service; this.isNew = true; this.InitializeProperties(requestedProperties); } /// <summary> /// Gets the name of the user configuration. /// </summary> public string Name { get { return this.name; } internal set { this.name = value; } } /// <summary> /// Gets the Id of the folder containing the user configuration. /// </summary> public FolderId ParentFolderId { get { return this.parentFolderId; } internal set { this.parentFolderId = value; } } /// <summary> /// Gets the Id of the user configuration. /// </summary> public ItemId ItemId { get { return this.itemId; } } /// <summary> /// Gets the dictionary of the user configuration. /// </summary> public UserConfigurationDictionary Dictionary { get { return this.dictionary; } } /// <summary> /// Gets or sets the xml data of the user configuration. /// </summary> public byte[] XmlData { get { this.ValidatePropertyAccess(UserConfigurationProperties.XmlData); return this.xmlData; } set { this.xmlData = value; this.MarkPropertyForUpdate(UserConfigurationProperties.XmlData); } } /// <summary> /// Gets or sets the binary data of the user configuration. /// </summary> public byte[] BinaryData { get { this.ValidatePropertyAccess(UserConfigurationProperties.BinaryData); return this.binaryData; } set { this.binaryData = value; this.MarkPropertyForUpdate(UserConfigurationProperties.BinaryData); } } /// <summary> /// Gets a value indicating whether this user configuration has been modified. /// </summary> public bool IsDirty { get { return (this.updatedProperties != NoProperties) || this.dictionary.IsDirty; } } /// <summary> /// Binds to an existing user configuration and loads the specified properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder containing the user configuration.</param> /// <param name="properties">The properties to load.</param> /// <returns>A user configuration instance.</returns> public static UserConfiguration Bind( ExchangeService service, string name, FolderId parentFolderId, UserConfigurationProperties properties) { UserConfiguration result = service.GetUserConfiguration( name, parentFolderId, properties); result.isNew = false; return result; } /// <summary> /// Binds to an existing user configuration and loads the specified properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderName">The name of the folder containing the user configuration.</param> /// <param name="properties">The properties to load.</param> /// <returns>A user configuration instance.</returns> public static UserConfiguration Bind( ExchangeService service, string name, WellKnownFolderName parentFolderName, UserConfigurationProperties properties) { return UserConfiguration.Bind( service, name, new FolderId(parentFolderName), properties); } /// <summary> /// Saves the user configuration. Calling this method results in a call to EWS. /// </summary> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder in which to save the user configuration.</param> public void Save(string name, FolderId parentFolderId) { EwsUtilities.ValidateParam(name, "name"); EwsUtilities.ValidateParam(parentFolderId, "parentFolderId"); parentFolderId.Validate(this.service.RequestedServerVersion); if (!this.isNew) { throw new InvalidOperationException(Strings.CannotSaveNotNewUserConfiguration); } this.parentFolderId = parentFolderId; this.name = name; this.service.CreateUserConfiguration(this); this.isNew = false; this.ResetIsDirty(); } /// <summary> /// Saves the user configuration. Calling this method results in a call to EWS. /// </summary> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderName">The name of the folder in which to save the user configuration.</param> public void Save(string name, WellKnownFolderName parentFolderName) { this.Save(name, new FolderId(parentFolderName)); } /// <summary> /// Updates the user configuration by applying local changes to the Exchange server. /// Calling this method results in a call to EWS. /// </summary> public void Update() { if (this.isNew) { throw new InvalidOperationException(Strings.CannotUpdateNewUserConfiguration); } if (this.IsPropertyUpdated(UserConfigurationProperties.BinaryData) || this.IsPropertyUpdated(UserConfigurationProperties.Dictionary) || this.IsPropertyUpdated(UserConfigurationProperties.XmlData)) { this.service.UpdateUserConfiguration(this); } this.ResetIsDirty(); } /// <summary> /// Deletes the user configuration. Calling this method results in a call to EWS. /// </summary> public void Delete() { if (this.isNew) { throw new InvalidOperationException(Strings.DeleteInvalidForUnsavedUserConfiguration); } else { this.service.DeleteUserConfiguration(this.name, this.parentFolderId); } } /// <summary> /// Loads the specified properties on the user configuration. Calling this method results in a call to EWS. /// </summary> /// <param name="properties">The properties to load.</param> public void Load(UserConfigurationProperties properties) { this.InitializeProperties(properties); this.service.LoadPropertiesForUserConfiguration(this, properties); } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal void WriteToXml( EwsServiceXmlWriter writer, XmlNamespace xmlNamespace, string xmlElementName) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteToXml", "writer is null"); EwsUtilities.Assert( xmlElementName != null, "UserConfiguration.WriteToXml", "xmlElementName is null"); writer.WriteStartElement(xmlNamespace, xmlElementName); // Write the UserConfigurationName element WriteUserConfigurationNameToXml( writer, XmlNamespace.Types, this.name, this.parentFolderId); // Write the Dictionary element if (this.IsPropertyUpdated(UserConfigurationProperties.Dictionary)) { this.dictionary.WriteToXml(writer, XmlElementNames.Dictionary); } // Write the XmlData element if (this.IsPropertyUpdated(UserConfigurationProperties.XmlData)) { this.WriteXmlDataToXml(writer); } // Write the BinaryData element if (this.IsPropertyUpdated(UserConfigurationProperties.BinaryData)) { this.WriteBinaryDataToXml(writer); } writer.WriteEndElement(); } /// <summary> /// Gets the base64 property value. /// </summary> /// <param name="bytes">The bytes.</param> /// <returns></returns> private string GetBase64PropertyValue(byte[] bytes) { if (bytes == null || bytes.Length == 0) { return String.Empty; } else { return Convert.ToBase64String(bytes); } } /// <summary> /// Determines whether the specified property was updated. /// </summary> /// <param name="property">property to evaluate.</param> /// <returns>Boolean indicating whether to send the property Xml.</returns> private bool IsPropertyUpdated(UserConfigurationProperties property) { bool isPropertyDirty = false; bool isPropertyEmpty = false; switch (property) { case UserConfigurationProperties.Dictionary: isPropertyDirty = this.Dictionary.IsDirty; isPropertyEmpty = this.Dictionary.Count == 0; break; case UserConfigurationProperties.XmlData: isPropertyDirty = (property & this.updatedProperties) == property; isPropertyEmpty = (this.xmlData == null) || (this.xmlData.Length == 0); break; case UserConfigurationProperties.BinaryData: isPropertyDirty = (property & this.updatedProperties) == property; isPropertyEmpty = (this.binaryData == null) || (this.binaryData.Length == 0); break; default: EwsUtilities.Assert( false, "UserConfiguration.IsPropertyUpdated", "property not supported: " + property.ToString()); break; } // Consider the property updated, if it's been modified, and either // . there's a value or // . there's no value but the operation is update. return isPropertyDirty && ((!isPropertyEmpty) || (!this.isNew)); } /// <summary> /// Writes the XmlData property to Xml. /// </summary> /// <param name="writer">The writer.</param> private void WriteXmlDataToXml(EwsServiceXmlWriter writer) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteXmlDataToXml", "writer is null"); WriteByteArrayToXml( writer, this.xmlData, XmlElementNames.XmlData); } /// <summary> /// Writes the BinaryData property to Xml. /// </summary> /// <param name="writer">The writer.</param> private void WriteBinaryDataToXml(EwsServiceXmlWriter writer) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteBinaryDataToXml", "writer is null"); WriteByteArrayToXml( writer, this.binaryData, XmlElementNames.BinaryData); } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> internal void LoadFromXml(EwsServiceXmlReader reader) { EwsUtilities.Assert( reader != null, "UserConfiguration.LoadFromXml", "reader is null"); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.UserConfiguration); reader.Read(); // Position at first property element do { if (reader.NodeType == XmlNodeType.Element) { switch (reader.LocalName) { case XmlElementNames.UserConfigurationName: string responseName = reader.ReadAttributeValue(XmlAttributeNames.Name); EwsUtilities.Assert( string.Compare(this.name, responseName, StringComparison.Ordinal) == 0, "UserConfiguration.LoadFromXml", "UserConfigurationName does not match: Expected: " + this.name + " Name in response: " + responseName); reader.SkipCurrentElement(); break; case XmlElementNames.ItemId: this.itemId = new ItemId(); this.itemId.LoadFromXml(reader, XmlElementNames.ItemId); break; case XmlElementNames.Dictionary: this.dictionary.LoadFromXml(reader, XmlElementNames.Dictionary); break; case XmlElementNames.XmlData: this.xmlData = Convert.FromBase64String(reader.ReadElementValue()); break; case XmlElementNames.BinaryData: this.binaryData = Convert.FromBase64String(reader.ReadElementValue()); break; default: EwsUtilities.Assert( false, "UserConfiguration.LoadFromXml", "Xml element not supported: " + reader.LocalName); break; } } // If XmlData was loaded, read is skipped because GetXmlData positions the reader at the next property. reader.Read(); } while (!reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.UserConfiguration)); } /// <summary> /// Initializes properties. /// </summary> /// <param name="requestedProperties">The properties requested for this UserConfiguration.</param> /// <remarks> /// InitializeProperties is called in 3 cases: /// . Create new object: From the UserConfiguration constructor. /// . Bind to existing object: Again from the constructor. The constructor is called eventually by the GetUserConfiguration request. /// . Refresh properties: From the Load method. /// </remarks> private void InitializeProperties(UserConfigurationProperties requestedProperties) { this.itemId = null; this.dictionary = new UserConfigurationDictionary(); this.xmlData = null; this.binaryData = null; this.propertiesAvailableForAccess = requestedProperties; this.ResetIsDirty(); } /// <summary> /// Resets flags to indicate that properties haven't been modified. /// </summary> private void ResetIsDirty() { this.updatedProperties = NoProperties; this.dictionary.IsDirty = false; } /// <summary> /// Determines whether the specified property may be accessed. /// </summary> /// <param name="property">Property to access.</param> private void ValidatePropertyAccess(UserConfigurationProperties property) { if ((property & this.propertiesAvailableForAccess) != property) { throw new PropertyException(Strings.MustLoadOrAssignPropertyBeforeAccess, property.ToString()); } } /// <summary> /// Adds the passed property to updatedProperties. /// </summary> /// <param name="property">Property to update.</param> private void MarkPropertyForUpdate(UserConfigurationProperties property) { this.updatedProperties |= property; this.propertiesAvailableForAccess |= property; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Implementation.Structure; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal partial class VisualStudioSymbolNavigationService : ForegroundThreadAffinitizedObject, ISymbolNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactory; private readonly ITextEditorFactoryService _textEditorFactoryService; private readonly ITextDocumentFactoryService _textDocumentFactoryService; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; private readonly VisualStudio14StructureTaggerProvider _outliningTaggerProvider; public VisualStudioSymbolNavigationService( SVsServiceProvider serviceProvider, VisualStudio14StructureTaggerProvider outliningTaggerProvider) { _serviceProvider = serviceProvider; _outliningTaggerProvider = outliningTaggerProvider; var componentModel = _serviceProvider.GetService<SComponentModel, IComponentModel>(); _editorAdaptersFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _textEditorFactoryService = componentModel.GetService<ITextEditorFactoryService>(); _textDocumentFactoryService = componentModel.GetService<ITextDocumentFactoryService>(); _metadataAsSourceFileService = componentModel.GetService<IMetadataAsSourceFileService>(); } public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options, CancellationToken cancellationToken) { if (project == null || symbol == null) { return false; } options = options ?? project.Solution.Workspace.Options; symbol = symbol.OriginalDefinition; // Prefer visible source locations if possible. var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource); var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation()); var sourceLocation = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault(); if (sourceLocation != null) { var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree); if (targetDocument != null) { var editorWorkspace = targetDocument.Project.Solution.Workspace; var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>(); return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options); } } // We don't have a source document, so show the Metadata as Source view in a preview tab. var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault(); if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { return false; } // Should we prefer navigating to the Object Browser over metadata-as-source? if (options.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language)) { var libraryService = project.LanguageServices.GetService<ILibraryService>(); if (libraryService == null) { return false; } var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation); if (navInfo == null) { navInfo = libraryService.NavInfoFactory.CreateForProject(project); } if (navInfo != null) { var navigationTool = _serviceProvider.GetService<SVsObjBrowser, IVsNavigationTool>(); return navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK; } // Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen. } // Generate new source or retrieve existing source for the symbol in question var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken); var vsRunningDocumentTable4 = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>(); var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid(result.FilePath); var openDocumentService = _serviceProvider.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(); IVsUIHierarchy hierarchy; uint itemId; IOleServiceProvider localServiceProvider; IVsWindowFrame windowFrame; openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame); var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath); var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie); var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer); if (!fileAlreadyOpen) { ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true)); ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle)); ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip)); } windowFrame.Show(); var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault(); if (openedDocument != null) { var editorWorkspace = openedDocument.Project.Solution.Workspace; var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>(); return navigationService.TryNavigateToSpan( workspace: editorWorkspace, documentId: openedDocument.Id, textSpan: result.IdentifierLocation.SourceSpan, options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true)); } return true; } public bool TrySymbolNavigationNotify(ISymbol symbol, Solution solution) { return TryNotifyForSpecificSymbol(symbol, solution); } private bool TryNotifyForSpecificSymbol(ISymbol symbol, Solution solution) { AssertIsForeground(); IVsHierarchy hierarchy; IVsSymbolicNavigationNotify navigationNotify; string rqname; uint itemID; if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out itemID, out navigationNotify, out rqname)) { return false; } int navigationHandled; int returnCode = navigationNotify.OnBeforeNavigateToSymbol( hierarchy, itemID, rqname, out navigationHandled); if (returnCode == VSConstants.S_OK && navigationHandled == 1) { return true; } return false; } public bool WouldNavigateToSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset) { if (WouldNotifyToSpecificSymbol(symbol, solution, out filePath, out lineNumber, out charOffset)) { return true; } // If the symbol being considered is a constructor and no third parties choose to // navigate to the constructor, then try the constructor's containing type. if (symbol.IsConstructor() && WouldNotifyToSpecificSymbol(symbol.ContainingType, solution, out filePath, out lineNumber, out charOffset)) { return true; } filePath = null; lineNumber = 0; charOffset = 0; return false; } public bool WouldNotifyToSpecificSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset) { AssertIsForeground(); filePath = null; lineNumber = 0; charOffset = 0; IVsHierarchy hierarchy; IVsSymbolicNavigationNotify navigationNotify; string rqname; uint itemID; if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out itemID, out navigationNotify, out rqname)) { return false; } IVsHierarchy navigateToHierarchy; uint navigateToItem; int wouldNavigate; var navigateToTextSpan = new Microsoft.VisualStudio.TextManager.Interop.TextSpan[1]; int queryNavigateStatusCode = navigationNotify.QueryNavigateToSymbol( hierarchy, itemID, rqname, out navigateToHierarchy, out navigateToItem, navigateToTextSpan, out wouldNavigate); if (queryNavigateStatusCode == VSConstants.S_OK && wouldNavigate == 1) { navigateToHierarchy.GetCanonicalName(navigateToItem, out filePath); lineNumber = navigateToTextSpan[0].iStartLine; charOffset = navigateToTextSpan[0].iStartIndex; return true; } return false; } private bool TryGetNavigationAPIRequiredArguments( ISymbol symbol, Solution solution, out IVsHierarchy hierarchy, out uint itemID, out IVsSymbolicNavigationNotify navigationNotify, out string rqname) { AssertIsForeground(); hierarchy = null; navigationNotify = null; rqname = null; itemID = (uint)VSConstants.VSITEMID.Nil; if (!symbol.Locations.Any()) { return false; } var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource); if (!sourceLocations.Any()) { return false; } var documents = sourceLocations.Select(loc => solution.GetDocument(loc.SourceTree)).WhereNotNull(); if (!documents.Any()) { return false; } // We can only pass one itemid to IVsSymbolicNavigationNotify, so prefer itemids from // documents we consider to be "generated" to give external language services the best // chance of participating. var generatedCodeRecognitionService = solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>(); var generatedDocuments = documents.Where(d => generatedCodeRecognitionService.IsGeneratedCode(d)); var documentToUse = generatedDocuments.FirstOrDefault() ?? documents.First(); if (!TryGetVsHierarchyAndItemId(documentToUse, out hierarchy, out itemID)) { return false; } navigationNotify = hierarchy as IVsSymbolicNavigationNotify; if (navigationNotify == null) { return false; } rqname = LanguageServices.RQName.From(symbol); return rqname != null; } private bool TryGetVsHierarchyAndItemId(Document document, out IVsHierarchy hierarchy, out uint itemID) { AssertIsForeground(); var visualStudioWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl; if (visualStudioWorkspace != null) { var hostProject = visualStudioWorkspace.GetHostProject(document.Project.Id); hierarchy = hostProject.Hierarchy; itemID = hostProject.GetDocumentOrAdditionalDocument(document.Id).GetItemId(); return true; } hierarchy = null; itemID = (uint)VSConstants.VSITEMID.Nil; return false; } private IVsRunningDocumentTable GetRunningDocumentTable() { var runningDocumentTable = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable>(); Debug.Assert(runningDocumentTable != null); return runningDocumentTable; } } }
// 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.Linq; using System.Text; using System.Runtime.InteropServices; using System.Threading; //using System.Configuration; namespace StackCommitTest { public unsafe class WinApi { [DllImport("kernel32.dll")] public static extern void GetSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo); [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { internal PROCESSOR_INFO_UNION uProcessorInfo; public uint dwPageSize; public IntPtr lpMinimumApplicationAddress; public IntPtr lpMaximumApplicationAddress; public IntPtr dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public ushort dwProcessorLevel; public ushort dwProcessorRevision; } [StructLayout(LayoutKind.Explicit)] public struct PROCESSOR_INFO_UNION { [FieldOffset(0)] internal uint dwOemId; [FieldOffset(0)] internal ushort wProcessorArchitecture; [FieldOffset(2)] internal ushort wReserved; } [DllImport("kernel32")] public static extern IntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, IntPtr length); public struct MEMORY_BASIC_INFORMATION { public byte* BaseAddress; public byte* AllocationBase; public int AllocationProtect; public IntPtr RegionSize; public MemState State; public int Protect; public int Type; } [Flags] public enum MemState { MEM_COMMIT = 0x1000, MEM_RESERVE = 0x2000, MEM_FREE = 0x10000, } public const int PAGE_GUARD = 0x100; } unsafe public static class Utility { public static Int64 PageSize { get; private set; } static Utility() { WinApi.SYSTEM_INFO sysInfo = new WinApi.SYSTEM_INFO(); WinApi.GetSystemInfo(ref sysInfo); PageSize = (Int64)sysInfo.dwPageSize; } public static void GetStackExtents(out byte* stackBase, out long stackSize) { WinApi.MEMORY_BASIC_INFORMATION info = new WinApi.MEMORY_BASIC_INFORMATION(); WinApi.VirtualQuery(&info, ref info, new IntPtr(sizeof(WinApi.MEMORY_BASIC_INFORMATION))); stackBase = info.AllocationBase; stackSize = (info.BaseAddress - info.AllocationBase) + info.RegionSize.ToInt64(); } public static List<WinApi.MEMORY_BASIC_INFORMATION> GetRegionsOfStack() { byte* stackBase; long stackSize; GetStackExtents(out stackBase, out stackSize); List<WinApi.MEMORY_BASIC_INFORMATION> result = new List<WinApi.MEMORY_BASIC_INFORMATION>(); byte* current = stackBase; while (current < stackBase + stackSize) { WinApi.MEMORY_BASIC_INFORMATION info = new WinApi.MEMORY_BASIC_INFORMATION(); WinApi.VirtualQuery(current, ref info, new IntPtr(sizeof(WinApi.MEMORY_BASIC_INFORMATION))); result.Add(info); current = info.BaseAddress + info.RegionSize.ToInt64(); } result.Reverse(); return result; } public static bool ValidateStack(string threadName, bool shouldBePreCommitted, Int32 expectedStackSize) { bool result = true; byte* stackBase; long stackSize; GetStackExtents(out stackBase, out stackSize); Console.WriteLine("{2} -- Base: {0:x}, Size: {1}kb", new IntPtr(stackBase).ToInt64(), stackSize / 1024, threadName); // // Start at the highest addresses, which should be committed (because that's where we're currently running). // The next region should be committed, but marked as a guard page. // After that, we'll either find committed pages, or reserved pages, depending on whether the runtime // is pre-committing stacks. // bool foundGuardRegion = false; foreach (var info in GetRegionsOfStack()) { string regionType = string.Empty; if (!foundGuardRegion) { if ((info.Protect & WinApi.PAGE_GUARD) != 0) { foundGuardRegion = true; regionType = "guard region"; } else { regionType = "active region"; } } else { if (shouldBePreCommitted) { if (!info.State.HasFlag(WinApi.MemState.MEM_COMMIT)) { // If we pre-commit the stack, the last 1 or 2 pages are left "reserved" (they are the "hard guard region") // ??? How to decide whether it is 1 or 2 pages? if ((info.BaseAddress != stackBase || info.RegionSize.ToInt64() > PageSize)) { result = false; regionType = "<---- should be pre-committed"; } } } else { if (info.State.HasFlag(WinApi.MemState.MEM_COMMIT)) { result = false; regionType = "<---- should not be pre-committed"; } } } Console.WriteLine( "{0:x8}-{1:x8} {2,5:g}kb {3,-11:g} {4}", new IntPtr(info.BaseAddress).ToInt64(), new IntPtr(info.BaseAddress + info.RegionSize.ToInt64()).ToInt64(), info.RegionSize.ToInt64() / 1024, info.State, regionType); } if (!foundGuardRegion) { result = false; Console.WriteLine("Did not find GuardRegion for the whole stack"); } if (expectedStackSize != -1 && stackSize != expectedStackSize) { result = false; Console.WriteLine("Stack size is not as expected: actual -- {0}, expected -- {1}", stackSize, expectedStackSize); } Console.WriteLine(); return result; } static private bool RunTestItem(string threadName, bool shouldBePreCommitted, Int32 expectedThreadSize, Action<Action> runOnThread) { bool result = false; ManualResetEventSlim mre = new ManualResetEventSlim(); runOnThread(() => { result = Utility.ValidateStack(threadName, shouldBePreCommitted, expectedThreadSize); mre.Set(); }); mre.Wait(); return result; } static public bool RunTest(bool shouldBePreCommitted) { if (RunTestItem("Main", shouldBePreCommitted, -1, action => action()) & RunTestItem("ThreadPool", shouldBePreCommitted, -1, action => ThreadPool.QueueUserWorkItem(state => action())) & RunTestItem("new Thread()", shouldBePreCommitted, -1, action => new Thread(() => action()).Start()) & //RunTestItem("new Thread(512kb)", true, 512 * 1024, action => new Thread(() => action(), 512 * 1024).Start()) & RunTestItem("Finalizer", shouldBePreCommitted, -1, action => Finalizer.Run(action))) { return true; } return false; } } public class Finalizer { Action m_action; private Finalizer(Action action) { m_action = action; } ~Finalizer() { m_action(); } public static void Run(Action action) { //We need to allocate the object inside of a seperate method to ensure that //the reference will be eliminated before GC.Collect is called. Technically //even across methods we probably don't make any formal guarantees but this //is sufficient for current runtime implementations. CreateUnreferencedObject(action); GC.Collect(); GC.WaitForPendingFinalizers(); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void CreateUnreferencedObject(Action action) { new Finalizer(action); } } }
using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Search; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using Occur = Lucene.Net.Search.Occur; using IReaderClosedListener = Lucene.Net.Index.IndexReader.IReaderClosedListener; [TestFixture] public class TestParallelCompositeReader : LuceneTestCase { private IndexSearcher parallel, single; private Directory dir, dir1, dir2; [Test] public virtual void TestQueries() { single = Single(Random, false); parallel = Parallel(Random, false); Queries(); single.IndexReader.Dispose(); single = null; parallel.IndexReader.Dispose(); parallel = null; dir.Dispose(); dir = null; dir1.Dispose(); dir1 = null; dir2.Dispose(); dir2 = null; } [Test] public virtual void TestQueriesCompositeComposite() { single = Single(Random, true); parallel = Parallel(Random, true); Queries(); single.IndexReader.Dispose(); single = null; parallel.IndexReader.Dispose(); parallel = null; dir.Dispose(); dir = null; dir1.Dispose(); dir1 = null; dir2.Dispose(); dir2 = null; } private void Queries() { QueryTest(new TermQuery(new Term("f1", "v1"))); QueryTest(new TermQuery(new Term("f1", "v2"))); QueryTest(new TermQuery(new Term("f2", "v1"))); QueryTest(new TermQuery(new Term("f2", "v2"))); QueryTest(new TermQuery(new Term("f3", "v1"))); QueryTest(new TermQuery(new Term("f3", "v2"))); QueryTest(new TermQuery(new Term("f4", "v1"))); QueryTest(new TermQuery(new Term("f4", "v2"))); BooleanQuery bq1 = new BooleanQuery(); bq1.Add(new TermQuery(new Term("f1", "v1")), Occur.MUST); bq1.Add(new TermQuery(new Term("f4", "v1")), Occur.MUST); QueryTest(bq1); } [Test] public virtual void TestRefCounts1() { Directory dir1 = GetDir1(Random); Directory dir2 = GetDir2(Random); DirectoryReader ir1, ir2; // close subreaders, ParallelReader will not change refCounts, but close on its own close ParallelCompositeReader pr = new ParallelCompositeReader(ir1 = DirectoryReader.Open(dir1), ir2 = DirectoryReader.Open(dir2)); IndexReader psub1 = pr.GetSequentialSubReaders()[0]; // check RefCounts Assert.AreEqual(1, ir1.RefCount); Assert.AreEqual(1, ir2.RefCount); Assert.AreEqual(1, psub1.RefCount); pr.Dispose(); Assert.AreEqual(0, ir1.RefCount); Assert.AreEqual(0, ir2.RefCount); Assert.AreEqual(0, psub1.RefCount); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestRefCounts2() { Directory dir1 = GetDir1(Random); Directory dir2 = GetDir2(Random); DirectoryReader ir1 = DirectoryReader.Open(dir1); DirectoryReader ir2 = DirectoryReader.Open(dir2); // don't close subreaders, so ParallelReader will increment refcounts ParallelCompositeReader pr = new ParallelCompositeReader(false, ir1, ir2); IndexReader psub1 = pr.GetSequentialSubReaders()[0]; // check RefCounts Assert.AreEqual(2, ir1.RefCount); Assert.AreEqual(2, ir2.RefCount); Assert.AreEqual(1, psub1.RefCount, "refCount must be 1, as the synthetic reader was created by ParallelCompositeReader"); pr.Dispose(); Assert.AreEqual(1, ir1.RefCount); Assert.AreEqual(1, ir2.RefCount); Assert.AreEqual(0, psub1.RefCount, "refcount must be 0 because parent was closed"); ir1.Dispose(); ir2.Dispose(); Assert.AreEqual(0, ir1.RefCount); Assert.AreEqual(0, ir2.RefCount); Assert.AreEqual(0, psub1.RefCount, "refcount should not change anymore"); dir1.Dispose(); dir2.Dispose(); } // closeSubreaders=false [Test] public virtual void TestReaderClosedListener1() { Directory dir1 = GetDir1(Random); CompositeReader ir1 = DirectoryReader.Open(dir1); // with overlapping ParallelCompositeReader pr = new ParallelCompositeReader(false, new CompositeReader[] { ir1 }, new CompositeReader[] { ir1 }); int[] listenerClosedCount = new int[1]; Assert.AreEqual(3, pr.Leaves.Count); foreach (AtomicReaderContext cxt in pr.Leaves) { cxt.Reader.AddReaderClosedListener(new ReaderClosedListenerAnonymousInnerClassHelper(this, listenerClosedCount)); } pr.Dispose(); ir1.Dispose(); Assert.AreEqual(3, listenerClosedCount[0]); dir1.Dispose(); } private class ReaderClosedListenerAnonymousInnerClassHelper : IReaderClosedListener { private readonly TestParallelCompositeReader outerInstance; private readonly int[] listenerClosedCount; public ReaderClosedListenerAnonymousInnerClassHelper(TestParallelCompositeReader outerInstance, int[] listenerClosedCount) { this.outerInstance = outerInstance; this.listenerClosedCount = listenerClosedCount; } public void OnClose(IndexReader reader) { listenerClosedCount[0]++; } } // closeSubreaders=true [Test] public virtual void TestReaderClosedListener2() { Directory dir1 = GetDir1(Random); CompositeReader ir1 = DirectoryReader.Open(dir1); // with overlapping ParallelCompositeReader pr = new ParallelCompositeReader(true, new CompositeReader[] { ir1 }, new CompositeReader[] { ir1 }); int[] listenerClosedCount = new int[1]; Assert.AreEqual(3, pr.Leaves.Count); foreach (AtomicReaderContext cxt in pr.Leaves) { cxt.Reader.AddReaderClosedListener(new ReaderClosedListenerAnonymousInnerClassHelper2(this, listenerClosedCount)); } pr.Dispose(); Assert.AreEqual(3, listenerClosedCount[0]); dir1.Dispose(); } private class ReaderClosedListenerAnonymousInnerClassHelper2 : IReaderClosedListener { private readonly TestParallelCompositeReader outerInstance; private readonly int[] listenerClosedCount; public ReaderClosedListenerAnonymousInnerClassHelper2(TestParallelCompositeReader outerInstance, int[] listenerClosedCount) { this.outerInstance = outerInstance; this.listenerClosedCount = listenerClosedCount; } public void OnClose(IndexReader reader) { listenerClosedCount[0]++; } } [Test] public virtual void TestCloseInnerReader() { Directory dir1 = GetDir1(Random); CompositeReader ir1 = DirectoryReader.Open(dir1); Assert.AreEqual(1, ir1.GetSequentialSubReaders()[0].RefCount); // with overlapping ParallelCompositeReader pr = new ParallelCompositeReader(true, new CompositeReader[] { ir1 }, new CompositeReader[] { ir1 }); IndexReader psub = pr.GetSequentialSubReaders()[0]; Assert.AreEqual(1, psub.RefCount); ir1.Dispose(); Assert.AreEqual(1, psub.RefCount, "refCount of synthetic subreader should be unchanged"); try { psub.Document(0); Assert.Fail("Subreader should be already closed because inner reader was closed!"); } #pragma warning disable 168 catch (ObjectDisposedException e) #pragma warning restore 168 { // pass } try { pr.Document(0); Assert.Fail("ParallelCompositeReader should be already closed because inner reader was closed!"); } #pragma warning disable 168 catch (ObjectDisposedException e) #pragma warning restore 168 { // pass } // noop: pr.Dispose(); Assert.AreEqual(0, psub.RefCount); dir1.Dispose(); } [Test] public virtual void TestIncompatibleIndexes1() { // two documents: Directory dir1 = GetDir1(Random); // one document only: Directory dir2 = NewDirectory(); IndexWriter w2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document d3 = new Document(); d3.Add(NewTextField("f3", "v1", Field.Store.YES)); w2.AddDocument(d3); w2.Dispose(); DirectoryReader ir1 = DirectoryReader.Open(dir1), ir2 = DirectoryReader.Open(dir2); try { new ParallelCompositeReader(ir1, ir2); Assert.Fail("didn't get expected exception: indexes don't have same number of documents"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { // expected exception } try { new ParallelCompositeReader(Random.NextBoolean(), ir1, ir2); Assert.Fail("didn't get expected exception: indexes don't have same number of documents"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { // expected exception } Assert.AreEqual(1, ir1.RefCount); Assert.AreEqual(1, ir2.RefCount); ir1.Dispose(); ir2.Dispose(); Assert.AreEqual(0, ir1.RefCount); Assert.AreEqual(0, ir2.RefCount); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestIncompatibleIndexes2() { Directory dir1 = GetDir1(Random); Directory dir2 = GetInvalidStructuredDir2(Random); DirectoryReader ir1 = DirectoryReader.Open(dir1), ir2 = DirectoryReader.Open(dir2); CompositeReader[] readers = new CompositeReader[] { ir1, ir2 }; try { new ParallelCompositeReader(readers); Assert.Fail("didn't get expected exception: indexes don't have same subreader structure"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { // expected exception } try { new ParallelCompositeReader(Random.NextBoolean(), readers, readers); Assert.Fail("didn't get expected exception: indexes don't have same subreader structure"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { // expected exception } Assert.AreEqual(1, ir1.RefCount); Assert.AreEqual(1, ir2.RefCount); ir1.Dispose(); ir2.Dispose(); Assert.AreEqual(0, ir1.RefCount); Assert.AreEqual(0, ir2.RefCount); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestIncompatibleIndexes3() { Directory dir1 = GetDir1(Random); Directory dir2 = GetDir2(Random); CompositeReader ir1 = new MultiReader(DirectoryReader.Open(dir1), SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir1))), ir2 = new MultiReader(DirectoryReader.Open(dir2), DirectoryReader.Open(dir2)); CompositeReader[] readers = new CompositeReader[] { ir1, ir2 }; try { new ParallelCompositeReader(readers); Assert.Fail("didn't get expected exception: indexes don't have same subreader structure"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { // expected exception } try { new ParallelCompositeReader(Random.NextBoolean(), readers, readers); Assert.Fail("didn't get expected exception: indexes don't have same subreader structure"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { // expected exception } Assert.AreEqual(1, ir1.RefCount); Assert.AreEqual(1, ir2.RefCount); ir1.Dispose(); ir2.Dispose(); Assert.AreEqual(0, ir1.RefCount); Assert.AreEqual(0, ir2.RefCount); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestIgnoreStoredFields() { Directory dir1 = GetDir1(Random); Directory dir2 = GetDir2(Random); CompositeReader ir1 = DirectoryReader.Open(dir1); CompositeReader ir2 = DirectoryReader.Open(dir2); // with overlapping ParallelCompositeReader pr = new ParallelCompositeReader(false, new CompositeReader[] { ir1, ir2 }, new CompositeReader[] { ir1 }); Assert.AreEqual("v1", pr.Document(0).Get("f1")); Assert.AreEqual("v1", pr.Document(0).Get("f2")); Assert.IsNull(pr.Document(0).Get("f3")); Assert.IsNull(pr.Document(0).Get("f4")); // check that fields are there AtomicReader slow = SlowCompositeReaderWrapper.Wrap(pr); Assert.IsNotNull(slow.GetTerms("f1")); Assert.IsNotNull(slow.GetTerms("f2")); Assert.IsNotNull(slow.GetTerms("f3")); Assert.IsNotNull(slow.GetTerms("f4")); pr.Dispose(); // no stored fields at all pr = new ParallelCompositeReader(false, new CompositeReader[] { ir2 }, new CompositeReader[0]); Assert.IsNull(pr.Document(0).Get("f1")); Assert.IsNull(pr.Document(0).Get("f2")); Assert.IsNull(pr.Document(0).Get("f3")); Assert.IsNull(pr.Document(0).Get("f4")); // check that fields are there slow = SlowCompositeReaderWrapper.Wrap(pr); Assert.IsNull(slow.GetTerms("f1")); Assert.IsNull(slow.GetTerms("f2")); Assert.IsNotNull(slow.GetTerms("f3")); Assert.IsNotNull(slow.GetTerms("f4")); pr.Dispose(); // without overlapping pr = new ParallelCompositeReader(true, new CompositeReader[] { ir2 }, new CompositeReader[] { ir1 }); Assert.AreEqual("v1", pr.Document(0).Get("f1")); Assert.AreEqual("v1", pr.Document(0).Get("f2")); Assert.IsNull(pr.Document(0).Get("f3")); Assert.IsNull(pr.Document(0).Get("f4")); // check that fields are there slow = SlowCompositeReaderWrapper.Wrap(pr); Assert.IsNull(slow.GetTerms("f1")); Assert.IsNull(slow.GetTerms("f2")); Assert.IsNotNull(slow.GetTerms("f3")); Assert.IsNotNull(slow.GetTerms("f4")); pr.Dispose(); // no main readers try { new ParallelCompositeReader(true, new CompositeReader[0], new CompositeReader[] { ir1 }); Assert.Fail("didn't get expected exception: need a non-empty main-reader array"); } #pragma warning disable 168 catch (ArgumentException iae) #pragma warning restore 168 { // pass } dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestToString() { Directory dir1 = GetDir1(Random); CompositeReader ir1 = DirectoryReader.Open(dir1); ParallelCompositeReader pr = new ParallelCompositeReader(new CompositeReader[] { ir1 }); string s = pr.ToString(); Assert.IsTrue(s.StartsWith("ParallelCompositeReader(ParallelAtomicReader(", StringComparison.Ordinal), "toString incorrect: " + s); pr.Dispose(); dir1.Dispose(); } [Test] public virtual void TestToStringCompositeComposite() { Directory dir1 = GetDir1(Random); CompositeReader ir1 = DirectoryReader.Open(dir1); ParallelCompositeReader pr = new ParallelCompositeReader(new CompositeReader[] { new MultiReader(ir1) }); string s = pr.ToString(); Assert.IsTrue(s.StartsWith("ParallelCompositeReader(ParallelCompositeReaderAnonymousInnerClassHelper(ParallelAtomicReader(", StringComparison.Ordinal), "toString incorrect: " + s); pr.Dispose(); dir1.Dispose(); } private void QueryTest(Query query) { ScoreDoc[] parallelHits = parallel.Search(query, null, 1000).ScoreDocs; ScoreDoc[] singleHits = single.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(parallelHits.Length, singleHits.Length); for (int i = 0; i < parallelHits.Length; i++) { Assert.AreEqual(parallelHits[i].Score, singleHits[i].Score, 0.001f); Document docParallel = parallel.Doc(parallelHits[i].Doc); Document docSingle = single.Doc(singleHits[i].Doc); Assert.AreEqual(docParallel.Get("f1"), docSingle.Get("f1")); Assert.AreEqual(docParallel.Get("f2"), docSingle.Get("f2")); Assert.AreEqual(docParallel.Get("f3"), docSingle.Get("f3")); Assert.AreEqual(docParallel.Get("f4"), docSingle.Get("f4")); } } // Fields 1-4 indexed together: private IndexSearcher Single(Random random, bool compositeComposite) { dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); Document d1 = new Document(); d1.Add(NewTextField("f1", "v1", Field.Store.YES)); d1.Add(NewTextField("f2", "v1", Field.Store.YES)); d1.Add(NewTextField("f3", "v1", Field.Store.YES)); d1.Add(NewTextField("f4", "v1", Field.Store.YES)); w.AddDocument(d1); Document d2 = new Document(); d2.Add(NewTextField("f1", "v2", Field.Store.YES)); d2.Add(NewTextField("f2", "v2", Field.Store.YES)); d2.Add(NewTextField("f3", "v2", Field.Store.YES)); d2.Add(NewTextField("f4", "v2", Field.Store.YES)); w.AddDocument(d2); Document d3 = new Document(); d3.Add(NewTextField("f1", "v3", Field.Store.YES)); d3.Add(NewTextField("f2", "v3", Field.Store.YES)); d3.Add(NewTextField("f3", "v3", Field.Store.YES)); d3.Add(NewTextField("f4", "v3", Field.Store.YES)); w.AddDocument(d3); Document d4 = new Document(); d4.Add(NewTextField("f1", "v4", Field.Store.YES)); d4.Add(NewTextField("f2", "v4", Field.Store.YES)); d4.Add(NewTextField("f3", "v4", Field.Store.YES)); d4.Add(NewTextField("f4", "v4", Field.Store.YES)); w.AddDocument(d4); w.Dispose(); CompositeReader ir; if (compositeComposite) { ir = new MultiReader(DirectoryReader.Open(dir), DirectoryReader.Open(dir)); } else { ir = DirectoryReader.Open(dir); } return NewSearcher(ir); } // Fields 1 & 2 in one index, 3 & 4 in other, with ParallelReader: private IndexSearcher Parallel(Random random, bool compositeComposite) { dir1 = GetDir1(random); dir2 = GetDir2(random); CompositeReader rd1, rd2; if (compositeComposite) { rd1 = new MultiReader(DirectoryReader.Open(dir1), DirectoryReader.Open(dir1)); rd2 = new MultiReader(DirectoryReader.Open(dir2), DirectoryReader.Open(dir2)); Assert.AreEqual(2, rd1.Context.Children.Count); Assert.AreEqual(2, rd2.Context.Children.Count); } else { rd1 = DirectoryReader.Open(dir1); rd2 = DirectoryReader.Open(dir2); Assert.AreEqual(3, rd1.Context.Children.Count); Assert.AreEqual(3, rd2.Context.Children.Count); } ParallelCompositeReader pr = new ParallelCompositeReader(rd1, rd2); return NewSearcher(pr); } // subreader structure: (1,2,1) private Directory GetDir1(Random random) { Directory dir1 = NewDirectory(); IndexWriter w1 = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES)); Document d1 = new Document(); d1.Add(NewTextField("f1", "v1", Field.Store.YES)); d1.Add(NewTextField("f2", "v1", Field.Store.YES)); w1.AddDocument(d1); w1.Commit(); Document d2 = new Document(); d2.Add(NewTextField("f1", "v2", Field.Store.YES)); d2.Add(NewTextField("f2", "v2", Field.Store.YES)); w1.AddDocument(d2); Document d3 = new Document(); d3.Add(NewTextField("f1", "v3", Field.Store.YES)); d3.Add(NewTextField("f2", "v3", Field.Store.YES)); w1.AddDocument(d3); w1.Commit(); Document d4 = new Document(); d4.Add(NewTextField("f1", "v4", Field.Store.YES)); d4.Add(NewTextField("f2", "v4", Field.Store.YES)); w1.AddDocument(d4); w1.Dispose(); return dir1; } // subreader structure: (1,2,1) private Directory GetDir2(Random random) { Directory dir2 = NewDirectory(); IndexWriter w2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES)); Document d1 = new Document(); d1.Add(NewTextField("f3", "v1", Field.Store.YES)); d1.Add(NewTextField("f4", "v1", Field.Store.YES)); w2.AddDocument(d1); w2.Commit(); Document d2 = new Document(); d2.Add(NewTextField("f3", "v2", Field.Store.YES)); d2.Add(NewTextField("f4", "v2", Field.Store.YES)); w2.AddDocument(d2); Document d3 = new Document(); d3.Add(NewTextField("f3", "v3", Field.Store.YES)); d3.Add(NewTextField("f4", "v3", Field.Store.YES)); w2.AddDocument(d3); w2.Commit(); Document d4 = new Document(); d4.Add(NewTextField("f3", "v4", Field.Store.YES)); d4.Add(NewTextField("f4", "v4", Field.Store.YES)); w2.AddDocument(d4); w2.Dispose(); return dir2; } // this dir has a different subreader structure (1,1,2); private Directory GetInvalidStructuredDir2(Random random) { Directory dir2 = NewDirectory(); IndexWriter w2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES)); Document d1 = new Document(); d1.Add(NewTextField("f3", "v1", Field.Store.YES)); d1.Add(NewTextField("f4", "v1", Field.Store.YES)); w2.AddDocument(d1); w2.Commit(); Document d2 = new Document(); d2.Add(NewTextField("f3", "v2", Field.Store.YES)); d2.Add(NewTextField("f4", "v2", Field.Store.YES)); w2.AddDocument(d2); w2.Commit(); Document d3 = new Document(); d3.Add(NewTextField("f3", "v3", Field.Store.YES)); d3.Add(NewTextField("f4", "v3", Field.Store.YES)); w2.AddDocument(d3); Document d4 = new Document(); d4.Add(NewTextField("f3", "v4", Field.Store.YES)); d4.Add(NewTextField("f4", "v4", Field.Store.YES)); w2.AddDocument(d4); w2.Dispose(); return dir2; } } }
using UnityEngine; using System.Collections; public class Shooting : MonoBehaviour { // Transforms to manipulate objects. public Transform gun; // Gun. public Transform sphere; // Sphere. Transform clone; // Clone of sphere. public Transform targetSphere; // Target spheres. public Transform wallLeft; // Left wall of level. public Transform wallRight; // Right wall of level. public Transform wallTop; // Top wall of level. public Transform wallDown; // Down wall of level. public Transform capsule; // Shows mouse location. public Transform cameraMain; // Main camera. public Transform cameraWide; // Alternate camera. int frames = 0; // Count for each Update() frame ran. float movespeed = 1; // Move speed of gun. Vector3 gunRotation; // Gun rotation towards mouse. int shotPowerStart = 10; // How much power the shot starts with. int shotPower = 10; // Force used to shoot Sphere. int shotPowerPlus = 1; // How fast shot power increaces. int shotPowerLimit = 100; // Max shot power. int spheres = 0; // Count for Sphere clones. int maxSpheres = 5; // Max spheres that can be created. int targetSpheres = 0; // Count for target Spheres. float targetOrigin = 0; // Origin for target Sphere. string hitChecker = "Nothing"; // Hit check for target Spheres. int scrollLimit = 2; // Max scroll limit. int scrolled = 0; // Count for scroll. // Interface string GUIPower; // Displays shot power. string GUITime; // //Displays frames played so far. // Mouse Position Ray ray; RaycastHit hit; bool gameOver = false; // Graphical User Interface void OnGUI() { // Box displaying shot power at top left of screen. GUI.Box(new Rect(0,Screen.height-60,100,60), GUIPower); //Box displaying total frames and time at top right of screen. //GUI.Box(new Rect (Screen.width - 100,0,100,50), GUITime); // Restart button. if (GUI.Button (new Rect (100,Screen.height-50,100,50), "Restart (R)")) Application.LoadLevel(Application.loadedLevel); // Level selecters. if (GUI.Button (new Rect (210,Screen.height-50,80,25), "Level 1 (1)")) Application.LoadLevel(1); if (GUI.Button (new Rect (210,Screen.height-25,80,25), "Level 2 (2)")) Application.LoadLevel(2); if (GUI.Button (new Rect (290,Screen.height-50,80,25), "Level 3 (3)")) Application.LoadLevel(3); if (GUI.Button (new Rect (290,Screen.height-25,80,25), "Level 4 (4)")) Application.LoadLevel(4); // Quit button. if (GUI.Button (new Rect (380,Screen.height-50,100,50), "Quit(ESC)")) Application.LoadLevel(0); // Game over. if(gameOver == true){ GUI.Box(new Rect(200,200,250,25), "Congratulations, you completed level " + Application.loadedLevel + "!"); if(Application.loadedLevel < 4){ if (GUI.Button (new Rect (220,220,200,40), "Next Level (Space)") || Input.GetKeyDown(KeyCode.Space)) Application.LoadLevel(Application.loadedLevel+1); } else { GUI.Box(new Rect(200,220,250,25), "Game finished, go back to main menu?"); if (GUI.Button (new Rect (220,240,200,40), "Back to main menu. (Space)") || Input.GetKeyDown(KeyCode.Space)) Application.LoadLevel(0); } //gameOver = false; } } void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawLine(transform.position, hit.point); } void Update () { // Set ray to mouse position. if(cameraMain.camera.enabled == true){ ray = cameraMain.camera.ScreenPointToRay(Input.mousePosition); } else{ ray = cameraWide.camera.ScreenPointToRay(Input.mousePosition); } // Controls // W, A, S, D to move Gun left, right, up, down. // Left click to shoot, right click to switch camera. // 1, 2, 3, 4 for each level. // R to restart current level. // Escape to go back to main menu. // Menu if(Input.GetKeyDown(KeyCode.Escape)) { Application.LoadLevel(0); } // Movement for gun. // Press W to go up. /* if(Input.GetKey("w")) rigidbody.MovePosition(new Vector3(rigidbody.position.x ,rigidbody.position.y+movespeed/5 ,rigidbody.position.z)); // Press A to go Left. if(Input.GetKey("a")) rigidbody.MovePosition(new Vector3(rigidbody.position.x-movespeed/5 ,rigidbody.position.y ,rigidbody.position.z)); // Press S to go Down. if(Input.GetKey("s")) rigidbody.MovePosition(new Vector3(rigidbody.position.x ,rigidbody.position.y-movespeed/5 ,rigidbody.position.z)); // Press D to go Right. if(Input.GetKey("d")) rigidbody.MovePosition(new Vector3(rigidbody.position.x+movespeed/5 ,rigidbody.position.y ,rigidbody.position.z)); */ // Limit Spheres created. if(spheres < maxSpheres){ // Increase shot power. // Check if left mouse button if pressed. if(Input.GetKey(KeyCode.Mouse0)){ // Check if shot power is under limit. if(shotPower<shotPowerLimit) // Increase shot power. shotPower += shotPowerPlus; // Display shot power GUIPower = "Power: " + shotPower; } // Launch Sphere clone. // Check if left mouse button is released. if(Input.GetKeyUp(KeyCode.Mouse0)){ // Set Clone instance of a Sphere and position at gun. clone = Instantiate(sphere ,transform.position ,transform.rotation) as Transform; // Push clone by shot power towards mouse location. clone.rigidbody.AddRelativeForce(0 ,0 ,shotPower*20); // Reset shot power. shotPower = shotPowerStart; } } // Change cameras // Right click to invert to other camera. if(Input.GetKeyDown(KeyCode.Mouse1)) { cameraMain.camera.enabled = !cameraMain.camera.enabled; cameraWide.camera.enabled = !cameraWide.camera.enabled; } float scrollWheel = Input.GetAxis("Mouse ScrollWheel"); if(scrolled < scrollLimit){ // Mouse scroll forwards. if(scrollWheel > 0){ // Move camera forward. cameraMain.Translate(Vector3.forward*5); scrolled++; } } if(scrolled > ~scrollLimit){ // ~ means reverse. // Mouse scroll backwards. if(scrollWheel < 0){ // Move camera back. cameraMain.Translate(Vector3.back*5); scrolled--; } } // 1, 2, 3, 4 for each level. if(Input.GetKeyDown(KeyCode.Alpha1)){ Application.LoadLevel(1); } if(Input.GetKeyDown(KeyCode.Alpha2)){ Application.LoadLevel(2); } if(Input.GetKeyDown(KeyCode.Alpha3)){ Application.LoadLevel(3); } if(Input.GetKeyDown(KeyCode.Alpha4)){ Application.LoadLevel(4); } // R to restart current level. if(Input.GetKeyDown(KeyCode.R)){ Application.LoadLevel(Application.loadedLevel); } // Change timescale of game. // Press Q to increase timescale. /* if(Input.GetKeyDown(KeyCode.Q)) Time.timeScale++; // Press E to decrease timescale. if(Input.GetKeyDown(KeyCode.E)) Time.timeScale--; // Press R to reset timescale. if(Input.GetKeyDown(KeyCode.R)) Time.timeScale = 1; */ // Restricting movement. // Restrict movement of gun. if(gun && gun.position.x > wallRight.position.x){ gun.rigidbody.MovePosition(new Vector3(wallLeft.position.x ,gun.position.y ,gun.position.z)); } if(gun && gun.position.x < wallLeft.position.x){ gun.rigidbody.MovePosition(new Vector3(wallRight.position.x ,gun.position.y ,gun.position.z)); } if(gun && gun.position.y < wallDown .position.y){ gun.rigidbody.MovePosition(new Vector3(gun.rigidbody.position.x ,wallTop.position.y ,gun.position.z)); } if(gun && gun.position.y > wallTop.position.y){ gun.rigidbody.MovePosition(new Vector3(gun.rigidbody.position.x ,wallDown.position.y ,gun.position.z)); } string clonePosition = ""; // Restricting clone of Sphere movement. if(clone){ if(clone.position.x > wallRight.position.x || clone.position.x < wallLeft.position.x || clone.position.y < wallDown .position.y || clone.position.y > wallTop.position.y){ clonePosition = "Outside"; } else if(clone.position.x < wallRight.position.x || clone.position.x > wallLeft.position.x || clone.position.y > wallDown .position.y || clone.position.y < wallTop.position.y){ clonePosition = "Inside"; } } if(clonePosition == "Outside"){ // When clone is created and is outside the walls, destroy clone. Destroy(clone.gameObject); } if(clonePosition == "Inside"){ // When clone is created and inside the walls, destroy clone in 10 seconds. Destroy(clone.gameObject, 5f); } // Hitting target. if(targetOrigin != 0 && targetSphere) { if(hitChecker == "Nothing") if(targetSphere.transform.position.x == targetOrigin) { hitChecker = "Not Hit"; } if(hitChecker == "Nothing" || hitChecker == "Not Hit") if(targetSphere.transform.position.x != targetOrigin) { Destroy(targetSphere.gameObject,2f); hitChecker = "Hit"; } } // Every frame maintinance. // Check if raycast has been set, then draw line on Scene Screen. if (Physics.Raycast(ray, out hit, 1000)) Debug.DrawLine(transform.position, hit.point); // Draw line from gun to mouse location. capsule.rigidbody.MovePosition(hit.point); // Set casule at mouse position. if(cameraMain){ Vector3 cameraPosition = new Vector3(transform.position.x-cameraMain.transform.position.x ,transform.position.y-cameraMain.transform.position.y ,0); cameraMain.Translate(cameraPosition); // Position camera above Gun. } // Rotation of gun towards mouse position. gunRotation = new Vector3(hit.point.x,hit.point.y,0); transform.LookAt(gunRotation); if(targetSphere)targetOrigin = targetSphere.transform.position.x; capsule.Rotate(new Vector3(0,0,10)); // Rotate capsule. spheres = GameObject.FindGameObjectsWithTag("Respawn").Length; // Number of spheres in game. targetSpheres = GameObject.FindGameObjectsWithTag("Finish").Length; // Number of target spheres in game. GUIPower = "Power: " + shotPower + "\n Spheres: " + spheres + "\n Targets: " + targetSpheres; // Display shot power, spheres and target spheres. GUITime = "Time: " + (int)Time.time + "\n TimeScale: " + Time.timeScale + "\n Frames: " + frames; // //Display frames run. frames++; // Add to frames run. // Game Over. if(GameObject.FindGameObjectsWithTag("Finish").Length == 0){ gameOver = true; } } }
using System.Runtime.InteropServices; namespace OpenNI2 { internal enum OniImageRegistrationMode { ONI_IMAGE_REGISTRATION_OFF = 0, ONI_IMAGE_REGISTRATION_DEPTH_TO_COLOR = 1, } internal enum OniPixelFormat { ONI_PIXEL_FORMAT_DEPTH_1_MM = 100, ONI_PIXEL_FORMAT_DEPTH_100_UM = 101, ONI_PIXEL_FORMAT_SHIFT_9_2 = 102, ONI_PIXEL_FORMAT_SHIFT_9_3 = 103, ONI_PIXEL_FORMAT_RGB888 = 200, ONI_PIXEL_FORMAT_YUV422 = 201, ONI_PIXEL_FORMAT_GRAY8 = 202, ONI_PIXEL_FORMAT_GRAY16 = 203, ONI_PIXEL_FORMAT_JPEG = 204, ONI_PIXEL_FORMAT_YUYV = 205, } internal enum OniDeviceState { ONI_DEVICE_STATE_OK = 0, ONI_DEVICE_STATE_ERROR = 1, ONI_DEVICE_STATE_NOT_READY = 2, ONI_DEVICE_STATE_EOF = 3, } internal enum OniStatus { ONI_STATUS_OK = 0, ONI_STATUS_ERROR = 1, ONI_STATUS_NOT_IMPLEMENTED = 2, ONI_STATUS_NOT_SUPPORTED = 3, ONI_STATUS_BAD_PARAMETER = 4, ONI_STATUS_OUT_OF_FLOW = 5, ONI_STATUS_NO_DEVICE = 6, ONI_STATUS_TIME_OUT = 102, } internal enum OniSensorType { ONI_SENSOR_IR = 1, ONI_SENSOR_COLOR = 2, ONI_SENSOR_DEPTH = 3, } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 4)] internal unsafe struct OniVideoMode { internal OniPixelFormat pixelFormat; internal int resolutionX; internal int resolutionY; internal int fps; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 4)] internal unsafe struct OniFrame { internal int dataSize; internal void* data; internal OniSensorType sensorType; internal ulong timestamp; internal int frameIndex; internal int width; internal int height; internal OniVideoMode videoMode; internal int croppingEnabled; internal int cropOriginX; internal int cropOriginY; internal int stride; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 2)] internal unsafe struct OniDeviceInfo { internal fixed byte uri [256]; internal fixed byte vendor [256]; internal fixed byte name [256]; internal ushort usbVendorId; internal ushort usbProductId; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 4)] internal unsafe struct OniVersion { internal int major; internal int minor; internal int maintenance; internal int build; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 4)] internal unsafe struct OniSensorInfo { internal OniSensorType sensorType; internal int numSupportedVideoModes; internal OniVideoMode* pSupportedVideoModes; } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal unsafe delegate void OniDeviceInfoCallback (OniDeviceInfo* p0, void* p1); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal unsafe delegate void OniDeviceStateCallback (OniDeviceInfo* p0, OniDeviceState p1, void* p2); [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 4)] internal unsafe struct OniDeviceCallbacks { internal OniDeviceInfoCallback deviceConnected; internal OniDeviceInfoCallback deviceDisconnected; internal OniDeviceStateCallback deviceStateChanged; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 4)] internal unsafe struct OniCropping { internal int enabled; internal int originX; internal int originY; internal int width; internal int height; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal unsafe struct OniYUV422DoublePixel { internal byte u; internal byte y1; internal byte v; internal byte y2; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal unsafe struct _OniRecorder { } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal unsafe struct OniRGB888Pixel { internal byte r; internal byte g; internal byte b; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal unsafe struct _OniStream { } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 4)] internal unsafe struct OniSeek { internal int frameIndex; internal _OniStream* stream; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal unsafe struct OniCallbackHandleImpl { } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal unsafe struct _OniDevice { } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal unsafe delegate void* OniFrameAllocBufferCallback (int p0, void* p1); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal unsafe delegate void OniFrameFreeBufferCallback (void* p0, void* p1); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal unsafe delegate void OniNewFrameCallback (_OniStream* p0, void* p1); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal unsafe delegate void OniGeneralCallback (void* p0); internal static unsafe class OniCAPI { internal const int ONI_TIMEOUT_NONE = 0; internal const int ONI_TIMEOUT_FOREVER = -1; internal const int ONI_DEVICE_PROPERTY_FIRMWARE_VERSION = 0; internal const int ONI_DEVICE_PROPERTY_DRIVER_VERSION = 1; internal const int ONI_DEVICE_PROPERTY_HARDWARE_VERSION = 2; internal const int ONI_DEVICE_PROPERTY_SERIAL_NUMBER = 3; internal const int ONI_DEVICE_PROPERTY_ERROR_STATE = 4; internal const int ONI_DEVICE_PROPERTY_IMAGE_REGISTRATION = 5; internal const int ONI_DEVICE_PROPERTY_PLAYBACK_SPEED = 100; internal const int ONI_DEVICE_PROPERTY_PLAYBACK_REPEAT_ENABLED = 101; internal const int ONI_DEVICE_COMMAND_SEEK = 1; internal const int ONI_STREAM_PROPERTY_CROPPING = 0; internal const int ONI_STREAM_PROPERTY_HORIZONTAL_FOV = 1; internal const int ONI_STREAM_PROPERTY_VERTICAL_FOV = 2; internal const int ONI_STREAM_PROPERTY_VIDEO_MODE = 3; internal const int ONI_STREAM_PROPERTY_MAX_VALUE = 4; internal const int ONI_STREAM_PROPERTY_MIN_VALUE = 5; internal const int ONI_STREAM_PROPERTY_STRIDE = 6; internal const int ONI_STREAM_PROPERTY_MIRRORING = 7; internal const int ONI_STREAM_PROPERTY_NUMBER_OF_FRAMES = 8; internal const int ONI_STREAM_PROPERTY_AUTO_WHITE_BALANCE = 100; internal const int ONI_STREAM_PROPERTY_AUTO_EXPOSURE = 101; internal const int ONI_STREAM_PROPERTY_EXPOSURE = 102; internal const int ONI_STREAM_PROPERTY_GAIN = 103; [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniStreamStop(_OniStream* stream); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceEnableDepthColorSync(_OniDevice* device); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniStreamSetFrameBuffersAllocator(_OniStream* stream, OniFrameAllocBufferCallback alloc, OniFrameFreeBufferCallback free, void* pCookie); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern int oniDeviceIsImageRegistrationModeSupported(_OniDevice* device, OniImageRegistrationMode mode); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceCreateStream(_OniDevice* device, OniSensorType sensorType, _OniStream** pStream); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniGetDeviceList(OniDeviceInfo** pDevices, int* pNumDevices); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniShutdown(); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniFrameAddRef(OniFrame* pFrame); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern int oniDeviceIsCommandSupported(_OniDevice* device, int commandId); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern byte* oniGetExtendedError(); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniSensorInfo* oniDeviceGetSensorInfo(_OniDevice* device, OniSensorType sensorType); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniReleaseDeviceList(OniDeviceInfo* pDevices); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceInvoke(_OniDevice* device, int commandId, void* data, int dataSize); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniCoordinateConverterDepthToWorld(_OniStream* depthStream, float depthX, float depthY, float depthZ, float* pWorldX, float* pWorldY, float* pWorldZ); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniDeviceDisableDepthColorSync(_OniDevice* device); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniStreamSetProperty(_OniStream* stream, int propertyId, void* data, int dataSize); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniVersion oniGetVersion(); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniRecorderStart(_OniRecorder* recorder); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniRegisterDeviceCallbacks(OniDeviceCallbacks pCallbacks, void* pCookie, OniCallbackHandleImpl** pHandle); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniSetLogConsoleOutput(int bConsoleOutput); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceGetProperty(_OniDevice* device, int propertyId, void* data, int* pDataSize); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern int oniStreamIsCommandSupported(_OniStream* stream, int commandId); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniCreateRecorder(byte* fileName, _OniRecorder** pRecorder); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniSetLogMinSeverity(int nMinSeverity); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniStreamUnregisterNewFrameCallback(_OniStream* stream, OniCallbackHandleImpl* handle); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceOpen(byte* uri, _OniDevice** pDevice); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniFrameRelease(OniFrame* pFrame); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniGetLogFileName(byte* strFileName, int nBufferSize); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniCoordinateConverterDepthToColor(_OniStream* depthStream, _OniStream* colorStream, int depthX, int depthY, ushort depthZ, int* pColorX, int* pColorY); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniRecorderAttachStream(_OniRecorder* recorder, _OniStream* stream, int allowLossyCompression); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniInitialize(int apiVersion); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniSetLogOutputFolder(byte* strOutputFolder); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniStreamReadFrame(_OniStream* stream, OniFrame** pFrame); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniStreamGetProperty(_OniStream* stream, int propertyId, void* data, int* pDataSize); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceSetProperty(_OniDevice* device, int propertyId, void* data, int dataSize); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniRecorderDestroy(_OniRecorder** pRecorder); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceGetInfo(_OniDevice* device, OniDeviceInfo* pInfo); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniSensorInfo* oniStreamGetSensorInfo(_OniStream* stream); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceClose(_OniDevice* device); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniUnregisterDeviceCallbacks(OniCallbackHandleImpl* handle); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniRecorderStop(_OniRecorder* recorder); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniSetLogFileOutput(int bFileOutput); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniStreamInvoke(_OniStream* stream, int commandId, void* data, int dataSize); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern int oniFormatBytesPerPixel(OniPixelFormat format); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniCoordinateConverterWorldToDepth(_OniStream* depthStream, float worldX, float worldY, float worldZ, float* pDepthX, float* pDepthY, float* pDepthZ); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniStreamStart(_OniStream* stream); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern int oniDeviceIsPropertySupported(_OniDevice* device, int propertyId); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniStreamRegisterNewFrameCallback(_OniStream* stream, OniNewFrameCallback handler, void* pCookie, OniCallbackHandleImpl** pHandle); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniDeviceOpenEx(byte* uri, byte* mode, _OniDevice** pDevice); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern OniStatus oniWaitForAnyStream(_OniStream** pStreams, int numStreams, int* pStreamIndex, int timeout); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern int oniDeviceGetDepthColorSyncEnabled(_OniDevice* device); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern int oniStreamIsPropertySupported(_OniStream* stream, int propertyId); [DllImport(@"OpenNI2", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)] internal static extern void oniStreamDestroy(_OniStream* stream); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { private partial class WorkCoordinator { private const int MinimumDelayInMS = 50; private readonly Registration _registration; private readonly LogAggregator _logAggregator; private readonly IAsynchronousOperationListener _listener; private readonly IOptionService _optionService; private readonly CancellationTokenSource _shutdownNotificationSource; private readonly CancellationToken _shutdownToken; private readonly SimpleTaskQueue _eventProcessingQueue; // points to processor task private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor; private readonly SemanticChangeProcessor _semanticChangeProcessor; public WorkCoordinator( IAsynchronousOperationListener listener, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, Registration registration) { _logAggregator = new LogAggregator(); _registration = registration; _listener = listener; _optionService = _registration.GetService<IOptionService>(); _optionService.OptionChanged += OnOptionChanged; // event and worker queues _shutdownNotificationSource = new CancellationTokenSource(); _shutdownToken = _shutdownNotificationSource.Token; _eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default); var activeFileBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS); var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS); var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS); _documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor( listener, analyzerProviders, _registration, activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken); var semanticBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS); var projectBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS); _semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken); // if option is on if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler)) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } } public int CorrelationId { get { return _registration.CorrelationId; } } public void Shutdown(bool blockingShutdown) { _optionService.OptionChanged -= OnOptionChanged; // detach from the workspace _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; // cancel any pending blocks _shutdownNotificationSource.Cancel(); _documentAndProjectWorkerProcessor.Shutdown(); SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator); if (blockingShutdown) { var shutdownTask = Task.WhenAll( _eventProcessingQueue.LastScheduledTask, _documentAndProjectWorkerProcessor.AsyncProcessorTask, _semanticChangeProcessor.AsyncProcessorTask); shutdownTask.Wait(TimeSpan.FromSeconds(5)); if (!shutdownTask.IsCompleted) { SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId); } } } private void OnOptionChanged(object sender, OptionChangedEventArgs e) { // if solution crawler got turned off or on. if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler) { var value = (bool)e.Value; if (value) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } else { _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; } SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value); return; } // TODO: remove this once prototype is done // it is here just because it was convenient to add per workspace option change monitoring // for incremental analyzer if (e.Option == Diagnostics.InternalDiagnosticsOptions.UseDiagnosticEngineV2) { _documentAndProjectWorkerProcessor.ChangeDiagnosticsEngine((bool)e.Value); } ReanalyzeOnOptionChange(sender, e); } private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e) { // otherwise, let each analyzer decide what they want on option change ISet<DocumentId> set = null; foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers) { if (analyzer.NeedsReanalysisOnOptionChanged(sender, e)) { set = set ?? _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(); this.Reanalyze(analyzer, set); } } } public void Reanalyze(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { var asyncToken = _listener.BeginAsyncOperation("Reanalyze"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(analyzer, documentIds), _shutdownToken).CompletesAsyncOperation(asyncToken); SolutionCrawlerLogger.LogReanalyze(CorrelationId, analyzer, documentIds); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { // guard us from cancellation try { ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged")); } catch (OperationCanceledException oce) { if (NotOurShutdownToken(oce)) { throw; } // it is our cancellation, ignore } catch (AggregateException ae) { ae = ae.Flatten(); // If we had a mix of exceptions, don't eat it if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) || ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken)) { // We had a cancellation with a different token, so don't eat it throw; } // it is our cancellation, ignore } } private bool NotOurShutdownToken(OperationCanceledException oce) { return oce.CancellationToken == _shutdownToken; } private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken) { SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind); // TODO: add telemetry that record how much it takes to process an event (max, min, average and etc) switch (args.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: ProcessSolutionEvent(args, asyncToken); break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: ProcessProjectEvent(args, asyncToken); break; case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: ProcessDocumentEvent(args, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnDocumentOpened(object sender, DocumentEventArgs e) { var asyncToken = _listener.BeginAsyncOperation("OnDocumentOpened"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentOpened), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnDocumentClosed(object sender, DocumentEventArgs e) { var asyncToken = _listener.BeginAsyncOperation("OnDocumentClosed"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentClosed), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.DocumentAdded: EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.DocumentRemoved: EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken); break; case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: // If an additional file has changed we need to reanalyze the entire project. EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.ProjectAdded: OnProjectAdded(e.NewSolution.GetProject(e.ProjectId)); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.ProjectRemoved: EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: OnSolutionAdded(e.NewSolution); EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.SolutionRemoved: EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionCleared: EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnSolutionAdded(Solution solution) { var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(solution); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnProjectAdded(Project project) { var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(project); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken) { // document changed event is the special one. _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private async Task EnqueueWorkItemAsync(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null) { // we are shutting down _shutdownToken.ThrowIfCancellationRequested(); var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false); var currentMember = GetSyntaxPath(changedMember); // call to this method is serialized. and only this method does the writing. _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(document.Id, document.Project.Language, invocationReasons, isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem"))); // enqueue semantic work planner if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { // must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later. // due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual. _semanticChangeProcessor.Enqueue(document, currentMember); } } private SyntaxPath GetSyntaxPath(SyntaxNode changedMember) { // using syntax path might be too expansive since it will be created on every keystroke. // but currently, we have no other way to track a node between two different tree (even for incrementally parsed one) if (changedMember == null) { return null; } return new SyntaxPath(changedMember); } private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons) { foreach (var documentId in project.DocumentIds) { var document = project.GetDocument(documentId); await EnqueueWorkItemAsync(document, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { var solution = _registration.CurrentSolution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); if (document == null) { continue; } var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false); _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, document.Project.Language, InvocationReasons.Reanalyze, isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem"))); } } private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution) { var solutionChanges = newSolution.GetChanges(oldSolution); // TODO: Async version for GetXXX methods? foreach (var addedProject in solutionChanges.GetAddedProjects()) { await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var projectChanges in solutionChanges.GetProjectChanges()) { await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedProject in solutionChanges.GetRemovedProjects()) { await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges) { await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false); foreach (var addedDocumentId in projectChanges.GetAddedDocuments()) { await EnqueueWorkItemAsync(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId)) .ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedDocumentId in projectChanges.GetRemovedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges) { var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document? var projectConfigurationChange = InvocationReasons.Empty; if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged); } if (projectChanges.GetAddedMetadataReferences().Any() || projectChanges.GetAddedProjectReferences().Any() || projectChanges.GetAddedAnalyzerReferences().Any() || projectChanges.GetRemovedMetadataReferences().Any() || projectChanges.GetRemovedProjectReferences().Any() || projectChanges.GetRemovedAnalyzerReferences().Any() || !object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) || !object.Equals(oldProject.AssemblyName, newProject.AssemblyName) || !object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged); } if (!projectConfigurationChange.IsEmpty) { await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument) { var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>(); if (differenceService != null) { var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false); if (differenceResult != null) { await EnqueueWorkItemAsync(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false); } } } private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons) { var document = solution.GetDocument(documentId); return EnqueueWorkItemAsync(document, invocationReasons); } private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons) { var project = solution.GetProject(projectId); return EnqueueWorkItemAsync(project, invocationReasons); } private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons) { foreach (var projectId in solution.ProjectIds) { await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId) { var oldProject = oldSolution.GetProject(projectId); var newProject = newSolution.GetProject(projectId); await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false); } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId) { var oldProject = oldSolution.GetProject(documentId.ProjectId); var newProject = newSolution.GetProject(documentId.ProjectId); await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false); } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers) { var solution = _registration.CurrentSolution; var list = new List<WorkItem>(); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { list.Add( new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, _listener.BeginAsyncOperation("WorkItem"))); } } _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list); } internal void WaitUntilCompletion_ForTestingPurposesOnly() { _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("GenericNameSignatureHelpProvider", LanguageNames.CSharp), Shared] internal partial class GenericNameSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) { return ch == '<' || ch == ','; } public override bool IsRetriggerCharacter(char ch) { return ch == '>'; } protected virtual bool TryGetGenericIdentifier( SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) { GenericNameSyntax name; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out name)) { genericIdentifier = name.Identifier; lessThanToken = name.TypeArgumentList.LessThanToken; return true; } genericIdentifier = default(SyntaxToken); lessThanToken = default(SyntaxToken); return false; } private bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacter(token.ValueText[0]) && token.Parent is TypeArgumentListSyntax && token.Parent.Parent is GenericNameSyntax; } private bool IsArgumentListToken(GenericNameSyntax node, SyntaxToken token) { return node.TypeArgumentList != null && node.TypeArgumentList.Span.Contains(token.SpanStart) && token != node.TypeArgumentList.GreaterThanToken; } protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); SyntaxToken genericIdentifier, lessThanToken; if (!TryGetGenericIdentifier(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out genericIdentifier, out lessThanToken)) { return null; } var simpleName = genericIdentifier.Parent as SimpleNameSyntax; if (simpleName == null) { return null; } var beforeDotExpression = simpleName.IsRightSideOfDot() ? simpleName.GetLeftSideOfDot() : null; var semanticModel = await document.GetSemanticModelForNodeAsync(simpleName, cancellationToken).ConfigureAwait(false); var leftSymbol = beforeDotExpression == null ? null : semanticModel.GetSymbolInfo(beforeDotExpression, cancellationToken).GetAnySymbol() as INamespaceOrTypeSymbol; var leftType = beforeDotExpression == null ? null : semanticModel.GetTypeInfo(beforeDotExpression, cancellationToken).Type as INamespaceOrTypeSymbol; var leftContainer = leftSymbol ?? leftType; var isBaseAccess = beforeDotExpression is BaseExpressionSyntax; var namespacesOrTypesOnly = SyntaxFacts.IsInNamespaceOrTypeContext(simpleName); var includeExtensions = leftSymbol == null && leftType != null; var name = genericIdentifier.ValueText; var symbols = isBaseAccess ? semanticModel.LookupBaseMembers(position, name) : namespacesOrTypesOnly ? semanticModel.LookupNamespacesAndTypes(position, leftContainer, name) : semanticModel.LookupSymbols(position, leftContainer, name, includeExtensions); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>(); var accessibleSymbols = symbols.Where(s => s.GetArity() > 0) .Where(s => s is INamedTypeSymbol || s is IMethodSymbol) .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(symbolDisplayService, semanticModel, genericIdentifier.SpanStart); if (!accessibleSymbols.Any()) { return null; } var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>(); var textSpan = GetTextSpan(genericIdentifier, lessThanToken); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); return CreateSignatureHelpItems(accessibleSymbols.Select(s => Convert(s, lessThanToken, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken)), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { SyntaxToken genericIdentifier, lessThanToken; if (!TryGetGenericIdentifier(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out genericIdentifier, out lessThanToken)) { return null; } GenericNameSyntax genericName; if (genericIdentifier.TryParseGenericName(cancellationToken, out genericName)) { // Because we synthesized the generic name, it will have an index starting at 0 // instead of at the actual position it's at in the text. Because of this, we need to // offset the position we are checking accordingly. var offset = genericIdentifier.SpanStart - genericName.SpanStart; position -= offset; return SignatureHelpUtilities.GetSignatureHelpState(genericName.TypeArgumentList, position); } return null; } protected virtual TextSpan GetTextSpan(SyntaxToken genericIdentifier, SyntaxToken lessThanToken) { Contract.ThrowIfFalse(lessThanToken.Parent is TypeArgumentListSyntax && lessThanToken.Parent.Parent is GenericNameSyntax); return SignatureHelpUtilities.GetSignatureHelpSpan(((GenericNameSyntax)lessThanToken.Parent.Parent).TypeArgumentList); } private SignatureHelpItem Convert( ISymbol symbol, SyntaxToken lessThanToken, SemanticModel semanticModel, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService, CancellationToken cancellationToken) { var position = lessThanToken.SpanStart; SignatureHelpItem item; if (symbol is INamedTypeSymbol) { var namedType = (INamedTypeSymbol)symbol; item = CreateItem( symbol, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService, false, symbol.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(namedType, semanticModel, position), GetSeparatorParts(), GetPostambleParts(namedType), namedType.TypeParameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken))); } else { var method = (IMethodSymbol)symbol; item = CreateItem( symbol, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService, false, c => symbol.GetDocumentationParts(semanticModel, position, documentationCommentFormattingService, c).Concat(GetAwaitableUsage(method, semanticModel, position)), GetPreambleParts(method, semanticModel, position), GetSeparatorParts(), GetPostambleParts(method, semanticModel, position), method.TypeParameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken))); } return item; } private static readonly SymbolDisplayFormat s_minimallyQualifiedFormat = SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions( SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeVariance); private SignatureHelpParameter Convert( ITypeParameterSymbol parameter, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) { return new SignatureHelpParameter( parameter.Name, isOptional: false, documentationFactory: parameter.GetDocumentationPartsFactory(semanticModel, position, formatter), displayParts: parameter.ToMinimalDisplayParts(semanticModel, position, s_minimallyQualifiedFormat), selectedDisplayParts: GetSelectedDisplayParts(parameter, semanticModel, position, cancellationToken)); } private IList<SymbolDisplayPart> GetSelectedDisplayParts( ITypeParameterSymbol typeParam, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var parts = new List<SymbolDisplayPart>(); if (TypeParameterHasConstraints(typeParam)) { parts.Add(Space()); parts.Add(Keyword(SyntaxKind.WhereKeyword)); parts.Add(Space()); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.TypeParameterName, typeParam, typeParam.Name)); parts.Add(Space()); parts.Add(Punctuation(SyntaxKind.ColonToken)); parts.Add(Space()); bool needComma = false; // class/struct constraint must be first if (typeParam.HasReferenceTypeConstraint) { parts.Add(Keyword(SyntaxKind.ClassKeyword)); needComma = true; } else if (typeParam.HasValueTypeConstraint) { parts.Add(Keyword(SyntaxKind.StructKeyword)); needComma = true; } foreach (var baseType in typeParam.ConstraintTypes) { if (needComma) { parts.Add(Punctuation(SyntaxKind.CommaToken)); parts.Add(Space()); } parts.AddRange(baseType.ToMinimalDisplayParts(semanticModel, position)); needComma = true; } // ctor constraint must be last if (typeParam.HasConstructorConstraint) { if (needComma) { parts.Add(Punctuation(SyntaxKind.CommaToken)); parts.Add(Space()); } parts.Add(Keyword(SyntaxKind.NewKeyword)); parts.Add(Punctuation(SyntaxKind.OpenParenToken)); parts.Add(Punctuation(SyntaxKind.CloseParenToken)); } } return parts; } private static bool TypeParameterHasConstraints(ITypeParameterSymbol typeParam) { return !typeParam.ConstraintTypes.IsDefaultOrEmpty || typeParam.HasConstructorConstraint || typeParam.HasReferenceTypeConstraint || typeParam.HasValueTypeConstraint; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractDouble() { var test = new SimpleBinaryOpTest__SubtractDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractDouble { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int Op2ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static SimpleBinaryOpTest__SubtractDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SubtractDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.Subtract( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.Subtract( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.Subtract( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractDouble(); var result = Avx.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(left[0] - right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i] - right[i]) != BitConverter.DoubleToInt64Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Subtract)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcdcv = Google.Cloud.Dialogflow.Cx.V3; using sys = System; namespace Google.Cloud.Dialogflow.Cx.V3 { /// <summary>Resource name for the <c>Version</c> resource.</summary> public sealed partial class VersionName : gax::IResourceName, sys::IEquatable<VersionName> { /// <summary>The possible contents of <see cref="VersionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </summary> ProjectLocationAgentFlowVersion = 1, } private static gax::PathTemplate s_projectLocationAgentFlowVersion = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}"); /// <summary>Creates a <see cref="VersionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="VersionName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static VersionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new VersionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="VersionName"/> with the pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="VersionName"/> constructed from the provided ids.</returns> public static VersionName FromProjectLocationAgentFlowVersion(string projectId, string locationId, string agentId, string flowId, string versionId) => new VersionName(ResourceNameType.ProjectLocationAgentFlowVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), flowId: gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), versionId: gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="VersionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VersionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </returns> public static string Format(string projectId, string locationId, string agentId, string flowId, string versionId) => FormatProjectLocationAgentFlowVersion(projectId, locationId, agentId, flowId, versionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="VersionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VersionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </returns> public static string FormatProjectLocationAgentFlowVersion(string projectId, string locationId, string agentId, string flowId, string versionId) => s_projectLocationAgentFlowVersion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId))); /// <summary>Parses the given resource name string into a new <see cref="VersionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="VersionName"/> if successful.</returns> public static VersionName Parse(string versionName) => Parse(versionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="VersionName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="VersionName"/> if successful.</returns> public static VersionName Parse(string versionName, bool allowUnparsed) => TryParse(versionName, allowUnparsed, out VersionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VersionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="VersionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string versionName, out VersionName result) => TryParse(versionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VersionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="VersionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string versionName, bool allowUnparsed, out VersionName result) { gax::GaxPreconditions.CheckNotNull(versionName, nameof(versionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationAgentFlowVersion.TryParseName(versionName, out resourceName)) { result = FromProjectLocationAgentFlowVersion(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(versionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private VersionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string flowId = null, string locationId = null, string projectId = null, string versionId = null) { Type = type; UnparsedResource = unparsedResourceName; AgentId = agentId; FlowId = flowId; LocationId = locationId; ProjectId = projectId; VersionId = versionId; } /// <summary> /// Constructs a new instance of a <see cref="VersionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param> public VersionName(string projectId, string locationId, string agentId, string flowId, string versionId) : this(ResourceNameType.ProjectLocationAgentFlowVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), flowId: gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), versionId: gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AgentId { get; } /// <summary> /// The <c>Flow</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FlowId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Version</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string VersionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationAgentFlowVersion: return s_projectLocationAgentFlowVersion.Expand(ProjectId, LocationId, AgentId, FlowId, VersionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as VersionName); /// <inheritdoc/> public bool Equals(VersionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(VersionName a, VersionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(VersionName a, VersionName b) => !(a == b); } public partial class CreateVersionOperationMetadata { /// <summary> /// <see cref="VersionName"/>-typed view over the <see cref="Version"/> resource name property. /// </summary> public VersionName VersionAsVersionName { get => string.IsNullOrEmpty(Version) ? null : VersionName.Parse(Version, allowUnparsed: true); set => Version = value?.ToString() ?? ""; } } public partial class Version { /// <summary> /// <see cref="gcdcv::VersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::VersionName VersionName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::VersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListVersionsRequest { /// <summary><see cref="FlowName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public FlowName ParentAsFlowName { get => string.IsNullOrEmpty(Parent) ? null : FlowName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetVersionRequest { /// <summary> /// <see cref="gcdcv::VersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::VersionName VersionName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::VersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateVersionRequest { /// <summary><see cref="FlowName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public FlowName ParentAsFlowName { get => string.IsNullOrEmpty(Parent) ? null : FlowName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteVersionRequest { /// <summary> /// <see cref="gcdcv::VersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::VersionName VersionName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::VersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class LoadVersionRequest { /// <summary> /// <see cref="gcdcv::VersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::VersionName VersionName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::VersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CompareVersionsRequest { /// <summary> /// <see cref="VersionName"/>-typed view over the <see cref="BaseVersion"/> resource name property. /// </summary> public VersionName BaseVersionAsVersionName { get => string.IsNullOrEmpty(BaseVersion) ? null : VersionName.Parse(BaseVersion, allowUnparsed: true); set => BaseVersion = value?.ToString() ?? ""; } /// <summary> /// <see cref="VersionName"/>-typed view over the <see cref="TargetVersion"/> resource name property. /// </summary> public VersionName TargetVersionAsVersionName { get => string.IsNullOrEmpty(TargetVersion) ? null : VersionName.Parse(TargetVersion, allowUnparsed: true); set => TargetVersion = value?.ToString() ?? ""; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Windows; using Microsoft.Practices.ServiceLocation; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Prism.Regions; namespace Prism.Wpf.Tests.Regions { [TestClass] public class RegionNavigationServiceFixture { [TestMethod] public void WhenNavigating_ViewIsActivated() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act bool isNavigationSuccessful = false; target.RequestNavigate(viewUri, nr => isNavigationSuccessful = nr.Result == true); // Verify Assert.IsTrue(isNavigationSuccessful); bool isViewActive = region.ActiveViews.Contains(view); Assert.IsTrue(isViewActive); } [TestMethod] public void WhenNavigatingWithQueryString_ViewIsActivated() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name + "?MyQuery=true", UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act bool isNavigationSuccessful = false; target.RequestNavigate(viewUri, nr => isNavigationSuccessful = nr.Result == true); // Verify Assert.IsTrue(isNavigationSuccessful); bool isViewActive = region.ActiveViews.Contains(view); Assert.IsTrue(isViewActive); } [TestMethod] public void WhenNavigatingAndViewCannotBeAcquired_ThenNavigationResultHasError() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string otherType = "OtherType"; var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; Mock<IRegionNavigationContentLoader> targetHandlerMock = new Mock<IRegionNavigationContentLoader>(); targetHandlerMock.Setup(th => th.LoadContent(It.IsAny<IRegion>(), It.IsAny<NavigationContext>())).Throws<ArgumentException>(); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, targetHandlerMock.Object, journal); target.Region = region; // Act Exception error = null; target.RequestNavigate( new Uri(otherType.GetType().Name, UriKind.Relative), nr => { error = nr.Error; }); // Verify bool isViewActive = region.ActiveViews.Contains(view); Assert.IsFalse(isViewActive); Assert.IsInstanceOfType(error, typeof(ArgumentException)); } [TestMethod] public void WhenNavigatingWithNullUri_Throws() { // Prepare IRegion region = new Region(); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act NavigationResult navigationResult = null; target.RequestNavigate((Uri)null, nr => navigationResult = nr); // Verify Assert.IsFalse(navigationResult.Result.Value); Assert.IsNotNull(navigationResult.Error); Assert.IsInstanceOfType(navigationResult.Error, typeof(ArgumentNullException)); } [TestMethod] public void WhenNavigatingAndViewImplementsINavigationAware_ThenNavigatedIsInvokedOnNavigation() { // Prepare var region = new Region(); var viewMock = new Mock<INavigationAware>(); viewMock.Setup(ina => ina.IsNavigationTarget(It.IsAny<NavigationContext>())).Returns(true); var view = viewMock.Object; region.Add(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify viewMock.Verify(v => v.OnNavigatedTo(It.Is<NavigationContext>(nc => nc.Uri == navigationUri && nc.NavigationService == target))); } [TestMethod] public void WhenNavigatingAndDataContextImplementsINavigationAware_ThenNavigatedIsInvokesOnNavigation() { // Prepare var region = new Region(); Mock<FrameworkElement> mockFrameworkElement = new Mock<FrameworkElement>(); Mock<INavigationAware> mockINavigationAwareDataContext = new Mock<INavigationAware>(); mockINavigationAwareDataContext.Setup(ina => ina.IsNavigationTarget(It.IsAny<NavigationContext>())).Returns(true); mockFrameworkElement.Object.DataContext = mockINavigationAwareDataContext.Object; var view = mockFrameworkElement.Object; region.Add(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify mockINavigationAwareDataContext.Verify(v => v.OnNavigatedTo(It.Is<NavigationContext>(nc => nc.Uri == navigationUri))); } [TestMethod] public void WhenNavigatingAndBothViewAndDataContextImplementINavigationAware_ThenNavigatedIsInvokesOnNavigation() { // Prepare var region = new Region(); Mock<FrameworkElement> mockFrameworkElement = new Mock<FrameworkElement>(); Mock<INavigationAware> mockINavigationAwareView = mockFrameworkElement.As<INavigationAware>(); mockINavigationAwareView.Setup(ina => ina.IsNavigationTarget(It.IsAny<NavigationContext>())).Returns(true); Mock<INavigationAware> mockINavigationAwareDataContext = new Mock<INavigationAware>(); mockINavigationAwareDataContext.Setup(ina => ina.IsNavigationTarget(It.IsAny<NavigationContext>())).Returns(true); mockFrameworkElement.Object.DataContext = mockINavigationAwareDataContext.Object; var view = mockFrameworkElement.Object; region.Add(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify mockINavigationAwareView.Verify(v => v.OnNavigatedTo(It.Is<NavigationContext>(nc => nc.Uri == navigationUri))); mockINavigationAwareDataContext.Verify(v => v.OnNavigatedTo(It.Is<NavigationContext>(nc => nc.Uri == navigationUri))); } [TestMethod] public void WhenNavigating_NavigationIsRecordedInJournal() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); IRegionNavigationJournalEntry journalEntry = new RegionNavigationJournalEntry(); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(journalEntry); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); var journalMock = new Mock<IRegionNavigationJournal>(); journalMock.Setup(x => x.RecordNavigation(journalEntry)).Verifiable(); IRegionNavigationJournal journal = journalMock.Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(viewUri, nr => { }); // Verify Assert.IsNotNull(journalEntry); Assert.AreEqual(viewUri, journalEntry.Uri); journalMock.VerifyAll(); } [TestMethod] public void WhenNavigatingAndCurrentlyActiveViewImplementsINavigateWithVeto_ThenNavigationRequestQueriesForVeto() { // Prepare var region = new Region(); var viewMock = new Mock<IConfirmNavigationRequest>(); viewMock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Verifiable(); var view = viewMock.Object; region.Add(view); region.Activate(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify viewMock.VerifyAll(); } [TestMethod] public void WhenNavigating_ThenNavigationRequestQueriesForVetoOnAllActiveViewsIfAllSucceed() { // Prepare var region = new Region(); var view1Mock = new Mock<IConfirmNavigationRequest>(); view1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(true)) .Verifiable(); var view1 = view1Mock.Object; region.Add(view1); region.Activate(view1); var view2Mock = new Mock<IConfirmNavigationRequest>(); var view2 = view2Mock.Object; region.Add(view2); var view3Mock = new Mock<INavigationAware>(); var view3 = view3Mock.Object; region.Add(view3); region.Activate(view3); var view4Mock = new Mock<IConfirmNavigationRequest>(); view4Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(true)) .Verifiable(); var view4 = view4Mock.Object; region.Add(view4); region.Activate(view4); var navigationUri = new Uri(view1.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify view1Mock.VerifyAll(); view2Mock.Verify(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>()), Times.Never()); view3Mock.VerifyAll(); view4Mock.VerifyAll(); } [TestMethod] public void WhenRequestNavigateAwayAcceptsThroughCallback_ThenNavigationProceeds() { // Prepare var region = new Region(); var view1Mock = new Mock<IConfirmNavigationRequest>(); view1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(true)) .Verifiable(); var view1 = view1Mock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act var navigationSucceeded = false; target.RequestNavigate(navigationUri, nr => { navigationSucceeded = nr.Result == true; }); // Verify view1Mock.VerifyAll(); Assert.IsTrue(navigationSucceeded); CollectionAssert.AreEqual(new object[] { view1, view2 }, region.ActiveViews.ToArray()); } [TestMethod] public void WhenRequestNavigateAwayRejectsThroughCallback_ThenNavigationDoesNotProceed() { // Prepare var region = new Region(); var view1Mock = new Mock<IConfirmNavigationRequest>(); view1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(false)) .Verifiable(); var view1 = view1Mock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act var navigationFailed = false; target.RequestNavigate(navigationUri, nr => { navigationFailed = nr.Result == false; }); // Verify view1Mock.VerifyAll(); Assert.IsTrue(navigationFailed); CollectionAssert.AreEqual(new object[] { view1 }, region.ActiveViews.ToArray()); } [TestMethod] public void WhenNavigatingAndDataContextOnCurrentlyActiveViewImplementsINavigateWithVeto_ThenNavigationRequestQueriesForVeto() { // Prepare var region = new Region(); var viewModelMock = new Mock<IConfirmNavigationRequest>(); viewModelMock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Verifiable(); var viewMock = new Mock<FrameworkElement>(); var view = viewMock.Object; view.DataContext = viewModelMock.Object; region.Add(view); region.Activate(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify viewModelMock.VerifyAll(); } [TestMethod] public void WhenRequestNavigateAwayOnDataContextAcceptsThroughCallback_ThenNavigationProceeds() { // Prepare var region = new Region(); var view1DataContextMock = new Mock<IConfirmNavigationRequest>(); view1DataContextMock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(true)) .Verifiable(); var view1Mock = new Mock<FrameworkElement>(); var view1 = view1Mock.Object; view1.DataContext = view1DataContextMock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act var navigationSucceeded = false; target.RequestNavigate(navigationUri, nr => { navigationSucceeded = nr.Result == true; }); // Verify view1DataContextMock.VerifyAll(); Assert.IsTrue(navigationSucceeded); CollectionAssert.AreEqual(new object[] { view1, view2 }, region.ActiveViews.ToArray()); } [TestMethod] public void WhenRequestNavigateAwayOnDataContextRejectsThroughCallback_ThenNavigationDoesNotProceed() { // Prepare var region = new Region(); var view1DataContextMock = new Mock<IConfirmNavigationRequest>(); view1DataContextMock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(false)) .Verifiable(); var view1Mock = new Mock<FrameworkElement>(); var view1 = view1Mock.Object; view1.DataContext = view1DataContextMock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act var navigationFailed = false; target.RequestNavigate(navigationUri, nr => { navigationFailed = nr.Result == false; }); // Verify view1DataContextMock.VerifyAll(); Assert.IsTrue(navigationFailed); CollectionAssert.AreEqual(new object[] { view1 }, region.ActiveViews.ToArray()); } [TestMethod] public void WhenViewAcceptsNavigationOutAfterNewIncomingRequestIsReceived_ThenOriginalRequestIsIgnored() { var region = new Region(); var viewMock = new Mock<IConfirmNavigationRequest>(); var view = viewMock.Object; var confirmationRequests = new List<Action<bool>>(); viewMock .Setup(icnr => icnr.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => { confirmationRequests.Add(c); }); region.Add(view); region.Activate(view); var navigationUri = new Uri("", UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Returns(view); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; bool firstNavigation = false; bool secondNavigation = false; target.RequestNavigate(navigationUri, nr => firstNavigation = nr.Result.Value); target.RequestNavigate(navigationUri, nr => secondNavigation = nr.Result.Value); Assert.AreEqual(2, confirmationRequests.Count); confirmationRequests[0](true); confirmationRequests[1](true); Assert.IsFalse(firstNavigation); Assert.IsTrue(secondNavigation); } [TestMethod] public void WhenViewModelAcceptsNavigationOutAfterNewIncomingRequestIsReceived_ThenOriginalRequestIsIgnored() { var region = new Region(); var viewModelMock = new Mock<IConfirmNavigationRequest>(); var viewMock = new Mock<FrameworkElement>(); var view = viewMock.Object; view.DataContext = viewModelMock.Object; var confirmationRequests = new List<Action<bool>>(); viewModelMock .Setup(icnr => icnr.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => { confirmationRequests.Add(c); }); region.Add(view); region.Activate(view); var navigationUri = new Uri("", UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Returns(view); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; bool firstNavigation = false; bool secondNavigation = false; target.RequestNavigate(navigationUri, nr => firstNavigation = nr.Result.Value); target.RequestNavigate(navigationUri, nr => secondNavigation = nr.Result.Value); Assert.AreEqual(2, confirmationRequests.Count); confirmationRequests[0](true); confirmationRequests[1](true); Assert.IsFalse(firstNavigation); Assert.IsTrue(secondNavigation); } [TestMethod] public void BeforeNavigating_NavigatingEventIsRaised() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; bool isNavigatingRaised = false; target.Navigating += delegate(object sender, RegionNavigationEventArgs e) { if (sender == target) { isNavigatingRaised = true; } }; // Act bool isNavigationSuccessful = false; target.RequestNavigate(viewUri, nr => isNavigationSuccessful = nr.Result == true); // Verify Assert.IsTrue(isNavigationSuccessful); Assert.IsTrue(isNavigatingRaised); } [TestMethod] public void WhenNavigationSucceeds_NavigatedIsRaised() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; bool isNavigatedRaised = false; target.Navigated += delegate(object sender, RegionNavigationEventArgs e) { if (sender == target) { isNavigatedRaised = true; } }; // Act bool isNavigationSuccessful = false; target.RequestNavigate(viewUri, nr => isNavigationSuccessful = nr.Result == true); // Verify Assert.IsTrue(isNavigationSuccessful); Assert.IsTrue(isNavigatedRaised); } [TestMethod] public void WhenTargetViewCreationThrowsWithAsyncConfirmation_ThenExceptionIsProvidedToNavigationCallback() { var serviceLocatorMock = new Mock<IServiceLocator>(); var targetException = new Exception(); var targetHandlerMock = new Mock<IRegionNavigationContentLoader>(); targetHandlerMock .Setup(th => th.LoadContent(It.IsAny<IRegion>(), It.IsAny<NavigationContext>())) .Throws(targetException); var journalMock = new Mock<IRegionNavigationJournal>(); Action<bool> navigationCallback = null; var viewMock = new Mock<IConfirmNavigationRequest>(); viewMock .Setup(v => v.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => { navigationCallback = c; }); var region = new Region(); region.Add(viewMock.Object); region.Activate(viewMock.Object); var target = new RegionNavigationService(serviceLocatorMock.Object, targetHandlerMock.Object, journalMock.Object); target.Region = region; NavigationResult result = null; target.RequestNavigate(new Uri("", UriKind.Relative), nr => result = nr); navigationCallback(true); Assert.IsNotNull(result); Assert.AreSame(targetException, result.Error); } [TestMethod] public void WhenNavigatingFromViewThatIsNavigationAware_ThenNotifiesActiveViewNavigatingFrom() { // Arrange var region = new Region(); var viewMock = new Mock<INavigationAware>(); var view = viewMock.Object; region.Add(view); var view2 = new object(); region.Add(view2); region.Activate(view); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify viewMock.Verify(v => v.OnNavigatedFrom(It.Is<NavigationContext>(ctx => ctx.Uri == navigationUri && ctx.Parameters.Count() == 0))); } [TestMethod] public void WhenNavigationFromViewThatIsNavigationAware_OnlyNotifiesOnNavigateFromForActiveViews() { // Arrange bool navigationFromInvoked = false; var region = new Region(); var viewMock = new Mock<INavigationAware>(); viewMock .Setup(x => x.OnNavigatedFrom(It.IsAny<NavigationContext>())).Callback(() => navigationFromInvoked = true); var view = viewMock.Object; region.Add(view); var targetViewMock = new Mock<INavigationAware>(); region.Add(targetViewMock.Object); var activeViewMock = new Mock<INavigationAware>(); region.Add(activeViewMock.Object); region.Activate(activeViewMock.Object); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); var navigationUri = new Uri(targetViewMock.Object.GetType().Name, UriKind.Relative); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify Assert.IsFalse(navigationFromInvoked); } [TestMethod] public void WhenNavigatingFromActiveViewWithNavigatinAwareDataConext_NotifiesContextOfNavigatingFrom() { // Arrange var region = new Region(); var mockDataContext = new Mock<INavigationAware>(); var view1Mock = new Mock<FrameworkElement>(); var view1 = view1Mock.Object; view1.DataContext = mockDataContext.Object; region.Add(view1); var view2 = new object(); region.Add(view2); region.Activate(view1); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify mockDataContext.Verify(v => v.OnNavigatedFrom(It.Is<NavigationContext>(ctx => ctx.Uri == navigationUri && ctx.Parameters.Count() == 0))); } [TestMethod] public void WhenNavigatingWithNullCallback_ThenThrows() { var region = new Region(); var navigationUri = new Uri("/", UriKind.Relative); IServiceLocator serviceLocator = new Mock<IServiceLocator>().Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; ExceptionAssert.Throws<ArgumentNullException>( () => { target.RequestNavigate(navigationUri, null); }); } [TestMethod] public void WhenNavigatingWithNoRegionSet_ThenMarshallExceptionToCallback() { var navigationUri = new Uri("/", UriKind.Relative); IServiceLocator serviceLocator = new Mock<IServiceLocator>().Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); Exception error = null; target.RequestNavigate(navigationUri, nr => error = nr.Error); Assert.IsNotNull(error); Assert.IsInstanceOfType(error, typeof(InvalidOperationException)); } [TestMethod] public void WhenNavigatingWithNullUri_ThenMarshallExceptionToCallback() { IServiceLocator serviceLocator = new Mock<IServiceLocator>().Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = new Region(); Exception error = null; target.RequestNavigate(null, nr => error = nr.Error); Assert.IsNotNull(error); Assert.IsInstanceOfType(error, typeof(ArgumentNullException)); } [TestMethod] public void WhenNavigationFailsBecauseTheContentViewCannotBeRetrieved_ThenNavigationFailedIsRaised() { // Prepare var region = new Region { Name = "RegionName" }; var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Throws<InvalidOperationException>(); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; RegionNavigationFailedEventArgs eventArgs = null; target.NavigationFailed += delegate(object sender, RegionNavigationFailedEventArgs e) { if (sender == target) { eventArgs = e; } }; // Act bool? isNavigationSuccessful = null; target.RequestNavigate(new Uri("invalid", UriKind.Relative), nr => isNavigationSuccessful = nr.Result); // Verify Assert.IsFalse(isNavigationSuccessful.Value); Assert.IsNotNull(eventArgs); Assert.IsNotNull(eventArgs.Error); } [TestMethod] public void WhenNavigationFailsBecauseActiveViewRejectsIt_ThenNavigationFailedIsRaised() { // Prepare var region = new Region { Name = "RegionName" }; var view1Mock = new Mock<IConfirmNavigationRequest>(); view1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(false)) .Verifiable(); var view1 = view1Mock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Returns(view2); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; RegionNavigationFailedEventArgs eventArgs = null; target.NavigationFailed += delegate(object sender, RegionNavigationFailedEventArgs e) { if (sender == target) { eventArgs = e; } }; // Act bool? isNavigationSuccessful = null; target.RequestNavigate(navigationUri, nr => isNavigationSuccessful = nr.Result); // Verify view1Mock.VerifyAll(); Assert.IsFalse(isNavigationSuccessful.Value); Assert.IsNotNull(eventArgs); Assert.IsNull(eventArgs.Error); } [TestMethod] public void WhenNavigationFailsBecauseDataContextForActiveViewRejectsIt_ThenNavigationFailedIsRaised() { // Prepare var region = new Region { Name = "RegionName" }; var viewModel1Mock = new Mock<IConfirmNavigationRequest>(); viewModel1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(false)) .Verifiable(); var view1Mock = new Mock<FrameworkElement>(); var view1 = view1Mock.Object; view1.DataContext = viewModel1Mock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Returns(view2); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; RegionNavigationFailedEventArgs eventArgs = null; target.NavigationFailed += delegate(object sender, RegionNavigationFailedEventArgs e) { if (sender == target) { eventArgs = e; } }; // Act bool? isNavigationSuccessful = null; target.RequestNavigate(navigationUri, nr => isNavigationSuccessful = nr.Result); // Verify viewModel1Mock.VerifyAll(); Assert.IsFalse(isNavigationSuccessful.Value); Assert.IsNotNull(eventArgs); Assert.IsNull(eventArgs.Error); } } }
#region license // Copyright 2004-2012 Castle Project, Henrik Feldt &contributors - https://github.com/castleproject // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using Castle.IO.Extensions; using Castle.IO.Internal; namespace Castle.IO { ///<summary> /// Utility class meant to replace the <see cref = "System.IO.Path" /> class completely. This class handles these types of paths: /// <list> /// <item>UNC network paths: \\server\folder</item> /// <item>UNC-specified network paths: \\?\UNC\server\folder</item> /// <item>IPv4 network paths: \\192.168.3.22\folder</item> /// <item>IPv4 network paths: \\[2001:34:23:55::34]\folder</item> /// <item>Rooted paths: /dev/cdrom0</item> /// <item>Rooted paths: C:\folder</item> /// <item>UNC-rooted paths: \\?\C:\folder\file</item> /// <item>Fully expanded IPv6 paths</item> /// </list> ///</summary> public partial class Path { // can of worms shut! // TODO: v3.2: 2001:0db8::1428:57ab and 2001:0db8:0:0::1428:57ab are not matched! // ip6: thanks to http://blogs.msdn.com/mpoulson/archive/2005/01/10/350037.aspx private static readonly List<char> _InvalidChars = new List<char>(GetInvalidPathChars()); // _Reserved = new List<string>("CON|PRN|AUX|NUL|COM1|COM2|COM3|COM4|COM5|COM6|COM7|COM8|COM9|LPT1|LPT2|LPT3|LPT4|LPT5|LPT6|LPT7|LPT8|LPT9" // .Split('|')); ///<summary> /// Returns whether the path is rooted. An empty string isn't. ///</summary> ///<param name = "path">Gets whether the path is rooted or relative.</param> ///<returns>Whether the path is rooted or not.</returns> ///<exception cref = "ArgumentNullException">If the passed argument is null.</exception> [Pure] public static bool IsPathRooted(string path) { Contract.Requires(path != null); if (string.IsNullOrEmpty(path)) return false; return !string.IsNullOrEmpty(PathInfo.Parse(path).Root); } /// <summary> /// Gets the path root, i.e. e.g. \\?\C:\ if the passed argument is \\?\C:\a\b\c.abc. /// </summary> /// <param name = "path">The path to get the root for.</param> /// <returns>The string denoting the root.</returns> [Pure] public static string GetPathRoot(string path) { Contract.Requires(!string.IsNullOrEmpty(path)); if (ContainsInvalidChars(path)) throw new ArgumentException("path contains invalid characters."); return PathInfo.Parse(path).Root; } [Pure] private static bool ContainsInvalidChars(string path) { var c = _InvalidChars.Count; var l = path.Length; for (var i = 0; i < l; i++) for (var j = 0; j < c; j++) if (path[i] == _InvalidChars[j]) return true; return false; } ///<summary> /// Gets a path without root. ///</summary> ///<param name = "path"></param> ///<returns></returns> ///<exception cref = "ArgumentNullException"></exception> [Pure] public static string GetPathWithoutRoot(string path) { Contract.Requires(path != null); if (path.Length == 0) return string.Empty; var startIndex = GetPathRoot(path).Length; if (path.Length < startIndex) return string.Empty; return path.Substring(startIndex); } ///<summary> /// Normalize all the directory separation chars. /// Also removes empty space in beginning and end of string. ///</summary> ///<param name = "pathWithAlternatingChars"></param> ///<returns>The directory string path with all occurrances of the alternating chars /// replaced for that specified in <see cref = "System.IO.Path.DirectorySeparatorChar" /></returns> [Pure] public static string NormDirSepChars(string pathWithAlternatingChars) { Contract.Requires(!string.IsNullOrEmpty(pathWithAlternatingChars)); Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); var sb = new StringBuilder(); for (var i = 0; i < pathWithAlternatingChars.Length; i++) if (pathWithAlternatingChars[i] == '\\' || pathWithAlternatingChars[i] == '/') sb.Append(DirectorySeparatorChar); else sb.Append(pathWithAlternatingChars[i]); var ret = sb.ToString().Trim(' '); Contract.Assume(!string.IsNullOrEmpty(ret), "because input was non-empty string and for every item in the string " + "we append to the string builder a non-whitespace char, so it can't be empty"); return ret; } ///<summary> /// Gets path info (drive and non root path) ///</summary> ///<param name = "path">The path to get the info from.</param> ///<returns></returns> ///<exception cref = "ArgumentNullException"></exception> [Pure] public static PathInfo GetPathInfo(string path) { Contract.Requires(path != null); return PathInfo.Parse(path); } ///<summary> /// Gets the full path for a given path. ///</summary> ///<param name = "path"></param> ///<returns>The full path string</returns> ///<exception cref = "ArgumentNullException">if path is null</exception> [Pure] public static string GetFullPath(string path) { Contract.Requires(!string.IsNullOrEmpty(path)); Contract.Ensures(Contract.Result<string>() != null); if (path.StartsWith("file:///")) return new Uri(path).LocalPath; return LongPathCommon.NormalizeLongPath(path); } /// <summary> /// Removes the last directory/file off the path. /// /// Example input/output: "/a/b/c" -> "/a/b"; /// "\\?\C:\folderA\folder\B\C\d.txt" -> "\\?\C:\folderA\folder\B\C" /// "\a\" -> "\"; /// "C:\a\b" -> "C:\a"; /// "C:\a\b\" -> "C:\a" /// </summary> /// <param name = "path">The path string to modify</param> /// <returns></returns> [Pure] public static Path GetPathWithoutLastBit(string path) { Contract.Requires(!string.IsNullOrEmpty(path)); Contract.Requires(path.Length >= 2); for (int i = path.Length - 1; i >= 0; i--) if (GetDirectorySeparatorChars().Contains(path[i])) if (path.Length - 1 == i) // last char continue; else // otherwise, return everything before the last \ or |, unless it's the root if (PathInfo.Parse(path.Substring(0, i + 1)).Root == path.Substring(0, i + 1)) return new Path(path.Substring(0, i + 1)); else return new Path(path.Substring(0, i)); //var p = new Path(path); //var segments = p.Segments.ToList(); //return segments.TakeWhile((s,i) => i != segments.Count-1) // .Aggregate(segments.First(), System.IO.Path.Combine) // .ToPath(); return new Path(path); } [Pure] public static string GetFileName(string path) { Contract.Requires(!string.IsNullOrEmpty(path), "path musn't be null"); if (path.EndsWith("/") || path.EndsWith("\\")) return string.Empty; var nonRoot = PathInfo.Parse(path).FolderAndFiles; int strIndex; // resharper is wrong that you can transform this to a ternary operator. if ((strIndex = nonRoot.LastIndexOfAny(new[] {DirectorySeparatorChar, AltDirectorySeparatorChar})) != -1) return nonRoot.Substring(strIndex + 1); return nonRoot; } [Pure] public static string GetDirectoryName(string path) { return GetFileName(path); } [Pure] public static bool HasExtension(string path) { Contract.Requires(!string.IsNullOrEmpty(path)); return GetFileName(path).Length != GetFileNameWithoutExtension(path).Length; } [Pure] public static string GetExtension(string path) { Contract.Requires(!string.IsNullOrEmpty(path)); var fn = GetFileName(path); var lastPeriod = fn.LastIndexOf('.'); return lastPeriod == -1 ? string.Empty : fn.Substring(lastPeriod); } [Pure] public static string GetFileNameWithoutExtension(string path) { Contract.Requires(!string.IsNullOrEmpty(path)); var filename = GetFileName(path); var lastPeriod = filename.LastIndexOf('.'); return lastPeriod == -1 ? filename : filename.Substring(0, lastPeriod); } [Pure] public static string GetRandomFileName() { return System.IO.Path.GetRandomFileName(); } [Pure] public static char[] GetInvalidPathChars() { return System.IO.Path.GetInvalidPathChars(); } [Pure] public static char[] GetInvalidFileNameChars() { return System.IO.Path.GetInvalidFileNameChars(); } [Pure] public static char DirectorySeparatorChar { get { return System.IO.Path.DirectorySeparatorChar; } } [Pure] public static char AltDirectorySeparatorChar { get { return System.IO.Path.AltDirectorySeparatorChar; } } [Pure] public static char[] GetDirectorySeparatorChars() { return new[] {DirectorySeparatorChar, AltDirectorySeparatorChar}; } [Pure] public static Path GetTempPath() { return new Path(System.IO.Path.GetTempPath()); } [Pure] public static string GetTempFileName() { return System.IO.Path.GetTempFileName(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using InControl; /** * WARNING: This is NOT an example of how to use InControl. * It is intended for testing and troubleshooting the library. * It can also be used for create new device profiles as it will * show the default Unity mappings for unknown devices. **/ public class TestInputManager : MonoBehaviour { GUIStyle style = new GUIStyle(); List<LogMessage> logMessages = new List<LogMessage>(); bool isPaused; void Start() { isPaused = false; Time.timeScale = 1.0f; Logger.OnLogMessage += logMessage => logMessages.Add( logMessage ); // InputManager.HideDevicesWithProfile( typeof( Xbox360MacProfile ) ); // InputManager.InvertYAxis = true; // InputManager.EnableXInput = true; InputManager.Setup(); InputManager.OnDeviceAttached += inputDevice => Debug.Log( "Attached: " + inputDevice.Name ); InputManager.OnDeviceDetached += inputDevice => Debug.Log( "Detached: " + inputDevice.Name ); InputManager.OnActiveDeviceChanged += inputDevice => Debug.Log( "Active device changed to: " + inputDevice.Name ); InputManager.AttachDevice( new UnityInputDevice( new FPSProfile() ) ); TestInputMappings(); Debug.Log( "InControl (version " + InputManager.Version + ")" ); } void FixedUpdate() { InputManager.Update(); CheckForPauseButton(); if (InputManager.ActiveDevice.Action1.WasPressed) { Debug.Log( "BOOM!" ); } } void Update() { if (isPaused) { InputManager.Update(); CheckForPauseButton(); } if (Input.GetKeyDown( KeyCode.R )) { Application.LoadLevel( "TestInputManager" ); } } void CheckForPauseButton() { if (Input.GetKeyDown( KeyCode.P ) || InputManager.MenuWasPressed) { Time.timeScale = isPaused ? 1.0f : 0.0f; isPaused = !isPaused; } } void SetColor( Color color ) { style.normal.textColor = color; } void OnGUI() { var w = 300; var x = 10; var y = 10; var lineHeight = 15; SetColor( Color.white ); string info = "Devices:"; info += " (Platform: " + InputManager.Platform + ")"; // info += " (Joysticks " + InputManager.JoystickHash + ")"; info += " " + InputManager.ActiveDevice.Direction; if (isPaused) { SetColor( Color.red ); info = "+++ PAUSED +++"; } GUI.Label( new Rect( x, y, x + w, y + 10 ), info, style ); SetColor( Color.white ); foreach (var inputDevice in InputManager.Devices) { bool active = InputManager.ActiveDevice == inputDevice; Color color = active ? Color.yellow : Color.white; y = 35; SetColor( color ); GUI.Label( new Rect( x, y, x + w, y + 10 ), inputDevice.Name, style ); y += lineHeight; GUI.Label( new Rect( x, y, x + w, y + 10 ), "SortOrder: " + inputDevice.SortOrder, style ); y += lineHeight; GUI.Label( new Rect( x, y, x + w, y + 10 ), "LastChangeTick: " + inputDevice.LastChangeTick, style ); y += lineHeight; foreach (var control in inputDevice.Controls) { if (control != null) { string controlName; if (inputDevice.IsKnown) { controlName = string.Format( "{0} ({1})", control.Target, control.Handle ); } else { controlName = control.Handle; } SetColor( control.State ? Color.green : color ); var label = string.Format( "{0} {1}", controlName, control.State ? "= " + control.Value : "" ); GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style ); y += lineHeight; } } x += 200; } Color[] logColors = { Color.gray, Color.yellow, Color.white }; SetColor( Color.white ); x = 10; y = Screen.height - (10 + lineHeight); for (int i = logMessages.Count - 1; i >= 0; i--) { var logMessage = logMessages[i]; SetColor( logColors[(int)logMessage.type] ); foreach (var line in logMessage.text.Split('\n')) { GUI.Label( new Rect( x, y, Screen.width, y + 10 ), line, style ); y -= lineHeight; } } } void OnDrawGizmos() { Vector3 delta = InputManager.ActiveDevice.Direction * 2.0f; Gizmos.color = Color.yellow; Gizmos.DrawSphere( transform.position + delta, 1 ); } void TestInputMappings() { var complete = InputControlMapping.Range.Complete; var positive = InputControlMapping.Range.Positive; var negative = InputControlMapping.Range.Negative; var noInvert = false; var doInvert = true; TestInputMapping( complete, complete, noInvert, -1.0f, 0.0f, 1.0f ); TestInputMapping( complete, negative, noInvert, -1.0f, -0.5f, 0.0f ); TestInputMapping( complete, positive, noInvert, 0.0f, 0.5f, 1.0f ); TestInputMapping( negative, complete, noInvert, -1.0f, 1.0f, 0.0f ); TestInputMapping( negative, negative, noInvert, -1.0f, 0.0f, 0.0f ); TestInputMapping( negative, positive, noInvert, 0.0f, 1.0f, 0.0f ); TestInputMapping( positive, complete, noInvert, 0.0f, -1.0f, 1.0f ); TestInputMapping( positive, negative, noInvert, 0.0f, -1.0f, 0.0f ); TestInputMapping( positive, positive, noInvert, 0.0f, 0.0f, 1.0f ); TestInputMapping( complete, complete, doInvert, 1.0f, 0.0f, -1.0f ); TestInputMapping( complete, negative, doInvert, 1.0f, 0.5f, 0.0f ); TestInputMapping( complete, positive, doInvert, 0.0f, -0.5f, -1.0f ); TestInputMapping( negative, complete, doInvert, 1.0f, -1.0f, 0.0f ); TestInputMapping( negative, negative, doInvert, 1.0f, 0.0f, 0.0f ); TestInputMapping( negative, positive, doInvert, 0.0f, -1.0f, 0.0f ); TestInputMapping( positive, complete, doInvert, 0.0f, 1.0f, -1.0f ); TestInputMapping( positive, negative, doInvert, 0.0f, 1.0f, 0.0f ); TestInputMapping( positive, positive, doInvert, 0.0f, 0.0f, -1.0f ); } void TestInputMapping( InputControlMapping.Range sourceRange, InputControlMapping.Range targetRange, bool invert, float expectA, float expectB, float expectC ) { var mapping = new InputControlMapping() { SourceRange = sourceRange, TargetRange = targetRange, Invert = invert }; float input; float value; string sr = "Complete"; if (sourceRange == InputControlMapping.Range.Negative) sr = "Negative"; else if (sourceRange == InputControlMapping.Range.Positive) sr = "Positive"; string tr = "Complete"; if (targetRange == InputControlMapping.Range.Negative) tr = "Negative"; else if (targetRange == InputControlMapping.Range.Positive) tr = "Positive"; input = -1.0f; value = mapping.MapValue( input ); if (Mathf.Abs( value - expectA ) > Single.Epsilon) { Debug.LogError( "Input of " + input + " got value of " + value + " instead of " + expectA + " (SR = " + sr + ", TR = " + tr + ")" ); } input = 0.0f; value = mapping.MapValue( input ); if (Mathf.Abs( value - expectB ) > Single.Epsilon) { Debug.LogError( "Input of " + input + " got value of " + value + " instead of " + expectB + " (SR = " + sr + ", TR = " + tr + ")" ); } input = 1.0f; value = mapping.MapValue( input ); if (Mathf.Abs( value - expectC ) > Single.Epsilon) { Debug.LogError( "Input of " + input + " got value of " + value + " instead of " + expectC + " (SR = " + sr + ", TR = " + tr + ")" ); } } }
using System; using System.Data; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using Epi; using Epi.Windows; using Epi.Analysis; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for List command /// </summary> public partial class ListDialog : CommandDesignDialog { #region Constructor /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public ListDialog() { InitializeComponent(); Construct(); } /// <summary> /// Constructor for the List dialog /// </summary> /// <param name="frm"></param> public ListDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } private void Construct() { //disabling this feature for now this.rdbAllowUpdates.Enabled = false; if (!this.DesignMode) // designer throws an error { this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.cmbVar.Validating += new CancelEventHandler(cmbVar_Validating); this.cmbVar.Validated += new EventHandler(cmbVar_Validated); this.cmbVar.TextChanged += new EventHandler(cmbVar_TextChanged); } } #endregion Constructors #region Event Handlers /// <summary> /// Handles click event of Clear button /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnClear_Click(object sender, System.EventArgs e) { lbxVariables.Items.Clear(); rdbWeb.Checked = true; cbxAllExcept.Checked = false; cmbVar.SelectedIndex = 0; } /// <summary> /// Handles the load event of List dialog /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void ListDialog_Load(object sender, System.EventArgs e) { LoadVariables(); } /// <summary> /// Handles the SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbVar_SelectedIndexChanged(object sender, System.EventArgs e) { this.Validate(); } private void lbxVariables_SelectedIndexChanged(object sender, System.EventArgs e) { if (lbxVariables.SelectedIndex != -1) { cmbVar.Items.Add(lbxVariables.Items[lbxVariables.SelectedIndex].ToString()); lbxVariables.Items.RemoveAt(lbxVariables.SelectedIndex); if (lbxVariables.Items.Count < 1 && cmbVar.Text!=StringLiterals.STAR) { btnOK.Enabled = false; btnSaveOnly.Enabled = false; } else if (lbxVariables.Items.Count < 1 && cmbVar.Text == StringLiterals.STAR) { btnOK.Enabled = true; btnSaveOnly.Enabled = true; } } } private void cmbVar_Validated(object sender, EventArgs e) { if (cmbVar.SelectedItem != null && cmbVar.Text != StringLiterals.STAR) { lbxVariables.Items.Add(cmbVar.SelectedItem); cmbVar.Items.Remove(cmbVar.SelectedItem); if (lbxVariables.Items.Count > 0) { btnOK.Enabled = true; btnSaveOnly.Enabled = true; } } } private void cmbVar_Validating(object sender, CancelEventArgs e) { if (cmbVar.SelectedItem == null) { if (!String.IsNullOrEmpty(cmbVar.Text)) { e.Cancel = true; cmbVar.Text = String.Empty; } } } private void cmbVar_TextChanged(object sender, EventArgs e) { if (cmbVar.Text == StringLiterals.STAR) { btnOK.Enabled = true; btnSaveOnly.Enabled = true; } else if (cmbVar.Text != StringLiterals.STAR && lbxVariables.Items.Count < 1) { btnOK.Enabled = false; btnSaveOnly.Enabled = false; } } /// <summary> /// Opens a process to show the related help topic /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> protected override void btnHelp_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-list.html"); } #endregion //Event Handlers #region Protected Methods /// <summary> /// Generates the command text /// </summary> protected override void GenerateCommand() { WordBuilder command = new WordBuilder(); command.Append(CommandNames.LIST); if (lbxVariables.Items.Count > 0) { if (cbxAllExcept.Checked) { command.Append(StringLiterals.STAR); command.Append(StringLiterals.SPACE); command.Append(CommandNames.EXCEPT); } foreach (string item in lbxVariables.Items) { command.Append(FieldNameNeedsBrackets(item) ? Util.InsertInSquareBrackets(item) : item); } } else { command.Append(cmbVar.Text); } if (WinUtil.GetSelectedRadioButton(gbxDisplayMode) == rdbGrid) { command.Append(CommandNames.GRIDTABLE); } else if (WinUtil.GetSelectedRadioButton(gbxDisplayMode) == rdbAllowUpdates) { command.Append(CommandNames.UPDATE); } CommandText = command.ToString(); } #endregion //Protected Methods #region Private Methods private void LoadVariables() { VariableType scopeWord = VariableType.DataSource | VariableType.DataSourceRedefined | VariableType.Standard | VariableType.Global; FillVariableCombo(cmbVar, scopeWord); cmbVar.Items.Insert(0, "*"); cmbVar.SelectedIndex = 0; //Data binding a combo box raises this event. Adding event handler here prevents this event being consumed prematurely this.cmbVar.SelectedIndexChanged += new System.EventHandler(this.cmbVar_SelectedIndexChanged); } #endregion Private Methods } }
#region License // /* // See license included in this library folder. // */ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Text; using System.Threading; using Sqloogle.Libs.NLog.Common; using Sqloogle.Libs.NLog.Config; using Sqloogle.Libs.NLog.Internal; using Sqloogle.Libs.NLog.Internal.FileAppenders; using Sqloogle.Libs.NLog.Layouts; #if !SILVERLIGHT2 && !SILVERLIGHT3 && !WINDOWS_PHONE namespace Sqloogle.Libs.NLog.Targets { /// <summary> /// Writes log messages to one or more files. /// </summary> /// <seealso href="http://nlog-project.org/wiki/File_target">Documentation on NLog Wiki</seealso> [Target("File")] public class FileTarget : TargetWithLayoutHeaderAndFooter, ICreateFileParameters { private readonly Dictionary<string, DateTime> initializedFiles = new Dictionary<string, DateTime>(); private LineEndingMode lineEndingMode = LineEndingMode.Default; private IFileAppenderFactory appenderFactory; private BaseFileAppender[] recentAppenders; private Timer autoClosingTimer; private int initializedFilesCounter; /// <summary> /// Initializes a new instance of the <see cref="FileTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Sequence; MaxArchiveFiles = 9; ConcurrentWriteAttemptDelay = 1; ArchiveEvery = FileArchivePeriod.None; ArchiveAboveSize = -1; ConcurrentWriteAttempts = 10; ConcurrentWrites = true; #if SILVERLIGHT this.Encoding = Encoding.UTF8; #else Encoding = Encoding.Default; #endif BufferSize = 32768; AutoFlush = true; #if !SILVERLIGHT && !NET_CF FileAttributes = Win32FileAttributes.Normal; #endif NewLineChars = EnvironmentHelper.NewLine; EnableFileDelete = true; OpenFileCacheTimeout = -1; OpenFileCacheSize = 5; CreateDirs = true; } /// <summary> /// Gets or sets the name of the file to write to. /// </summary> /// <remarks> /// This FileName string is a layout which may include instances of layout renderers. /// This lets you use a single target to write to multiple files. /// </remarks> /// <example> /// The following value makes NLog write logging events to files based on the log level in the directory where /// the application runs. /// <code>${basedir}/${level}.log</code> /// All <c>Debug</c> messages will go to <c>Debug.log</c>, all <c>Info</c> messages will go to <c>Info.log</c> and so on. /// You can combine as many of the layout renderers as you want to produce an arbitrary log file name. /// </example> /// <docgen category='Output Options' order='1' /> [RequiredParameter] public Layout FileName { get; set; } /// <summary> /// Gets or sets a value indicating whether to create directories if they don't exist. /// </summary> /// <remarks> /// Setting this to false may improve performance a bit, but you'll receive an error /// when attempting to write to a directory that's not present. /// </remarks> /// <docgen category='Output Options' order='10' /> [DefaultValue(true)] [Advanced] public bool CreateDirs { get; set; } /// <summary> /// Gets or sets a value indicating whether to delete old log file on startup. /// </summary> /// <remarks> /// This option works only when the "FileName" parameter denotes a single file. /// </remarks> /// <docgen category='Output Options' order='10' /> [DefaultValue(false)] public bool DeleteOldFileOnStartup { get; set; } /// <summary> /// Gets or sets a value indicating whether to replace file contents on each write instead of appending log message at the end. /// </summary> /// <docgen category='Output Options' order='10' /> [DefaultValue(false)] [Advanced] public bool ReplaceFileContentsOnEachWrite { get; set; } /// <summary> /// Gets or sets a value indicating whether to keep log file open instead of opening and closing it on each logging event. /// </summary> /// <remarks> /// Setting this property to <c>True</c> helps improve performance. /// </remarks> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(false)] public bool KeepFileOpen { get; set; } /// <summary> /// Gets or sets a value indicating whether to enable log file(s) to be deleted. /// </summary> /// <docgen category='Output Options' order='10' /> [DefaultValue(true)] public bool EnableFileDelete { get; set; } #if !NET_CF && !SILVERLIGHT /// <summary> /// Gets or sets the file attributes (Windows only). /// </summary> /// <docgen category='Output Options' order='10' /> [Advanced] public Win32FileAttributes FileAttributes { get; set; } #endif /// <summary> /// Gets or sets the line ending mode. /// </summary> /// <docgen category='Layout Options' order='10' /> [Advanced] public LineEndingMode LineEnding { get { return lineEndingMode; } set { lineEndingMode = value; switch (value) { case LineEndingMode.CR: NewLineChars = "\r"; break; case LineEndingMode.LF: NewLineChars = "\n"; break; case LineEndingMode.CRLF: NewLineChars = "\r\n"; break; case LineEndingMode.Default: NewLineChars = EnvironmentHelper.NewLine; break; case LineEndingMode.None: NewLineChars = string.Empty; break; } } } /// <summary> /// Gets or sets a value indicating whether to automatically flush the file buffers after each log message. /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(true)] public bool AutoFlush { get; set; } /// <summary> /// Gets or sets the number of files to be kept open. Setting this to a higher value may improve performance /// in a situation where a single File target is writing to many files /// (such as splitting by level or by logger). /// </summary> /// <remarks> /// The files are managed on a LRU (least recently used) basis, which flushes /// the files that have not been used for the longest period of time should the /// cache become full. As a rule of thumb, you shouldn't set this parameter to /// a very high value. A number like 10-15 shouldn't be exceeded, because you'd /// be keeping a large number of files open which consumes system resources. /// </remarks> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(5)] [Advanced] public int OpenFileCacheSize { get; set; } /// <summary> /// Gets or sets the maximum number of seconds that files are kept open. If this number is negative the files are /// not automatically closed after a period of inactivity. /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(-1)] [Advanced] public int OpenFileCacheTimeout { get; set; } /// <summary> /// Gets or sets the log file buffer size in bytes. /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(32768)] public int BufferSize { get; set; } /// <summary> /// Gets or sets the file encoding. /// </summary> /// <docgen category='Layout Options' order='10' /> public Encoding Encoding { get; set; } /// <summary> /// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on the same host. /// </summary> /// <remarks> /// This makes multi-process logging possible. NLog uses a special technique /// that lets it keep the files open for writing. /// </remarks> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(true)] public bool ConcurrentWrites { get; set; } /// <summary> /// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on different network hosts. /// </summary> /// <remarks> /// This effectively prevents files from being kept open. /// </remarks> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(false)] public bool NetworkWrites { get; set; } /// <summary> /// Gets or sets the number of times the write is appended on the file before NLog /// discards the log message. /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(10)] [Advanced] public int ConcurrentWriteAttempts { get; set; } /// <summary> /// Gets or sets the delay in milliseconds to wait before attempting to write to the file again. /// </summary> /// <remarks> /// The actual delay is a random value between 0 and the value specified /// in this parameter. On each failed attempt the delay base is doubled /// up to <see cref="ConcurrentWriteAttempts" /> times. /// </remarks> /// <example> /// Assuming that ConcurrentWriteAttemptDelay is 10 the time to wait will be:<p /> /// a random value between 0 and 10 milliseconds - 1st attempt<br /> /// a random value between 0 and 20 milliseconds - 2nd attempt<br /> /// a random value between 0 and 40 milliseconds - 3rd attempt<br /> /// a random value between 0 and 80 milliseconds - 4th attempt<br /> /// ...<p /> /// and so on. /// </example> /// <docgen category='Performance Tuning Options' order='10' /> [DefaultValue(1)] [Advanced] public int ConcurrentWriteAttemptDelay { get; set; } /// <summary> /// Gets or sets the size in bytes above which log files will be automatically archived. /// </summary> /// <remarks> /// Caution: Enabling this option can considerably slow down your file /// logging in multi-process scenarios. If only one process is going to /// be writing to the file, consider setting <c>ConcurrentWrites</c> /// to <c>false</c> for maximum performance. /// </remarks> /// <docgen category='Archival Options' order='10' /> public long ArchiveAboveSize { get; set; } /// <summary> /// Gets or sets a value indicating whether to automatically archive log files every time the specified time passes. /// </summary> /// <remarks> /// Files are moved to the archive as part of the write operation if the current period of time changes. For example /// if the current <c>hour</c> changes from 10 to 11, the first write that will occur /// on or after 11:00 will trigger the archiving. /// <p> /// Caution: Enabling this option can considerably slow down your file /// logging in multi-process scenarios. If only one process is going to /// be writing to the file, consider setting <c>ConcurrentWrites</c> /// to <c>false</c> for maximum performance. /// </p> /// </remarks> /// <docgen category='Archival Options' order='10' /> public FileArchivePeriod ArchiveEvery { get; set; } /// <summary> /// Gets or sets the name of the file to be used for an archive. /// </summary> /// <remarks> /// It may contain a special placeholder {#####} /// that will be replaced with a sequence of numbers depending on /// the archiving strategy. The number of hash characters used determines /// the number of numerical digits to be used for numbering files. /// </remarks> /// <docgen category='Archival Options' order='10' /> public Layout ArchiveFileName { get; set; } /// <summary> /// Gets or sets the maximum number of archive files that should be kept. /// </summary> /// <docgen category='Archival Options' order='10' /> [DefaultValue(9)] public int MaxArchiveFiles { get; set; } /// <summary> /// Gets or sets the way file archives are numbered. /// </summary> /// <docgen category='Archival Options' order='10' /> public ArchiveNumberingMode ArchiveNumbering { get; set; } /// <summary> /// Gets the characters that are appended after each line. /// </summary> protected internal string NewLineChars { get; private set; } /// <summary> /// Removes records of initialized files that have not been /// accessed in the last two days. /// </summary> /// <remarks> /// Files are marked 'initialized' for the purpose of writing footers when the logging finishes. /// </remarks> public void CleanupInitializedFiles() { CleanupInitializedFiles(DateTime.Now.AddDays(-2)); } /// <summary> /// Removes records of initialized files that have not been /// accessed after the specified date. /// </summary> /// <param name="cleanupThreshold">The cleanup threshold.</param> /// <remarks> /// Files are marked 'initialized' for the purpose of writing footers when the logging finishes. /// </remarks> public void CleanupInitializedFiles(DateTime cleanupThreshold) { // clean up files that are two days old var filesToUninitialize = new List<string>(); foreach (var de in initializedFiles) { var fileName = de.Key; var lastWriteTime = de.Value; if (lastWriteTime < cleanupThreshold) { filesToUninitialize.Add(fileName); } } foreach (var fileName in filesToUninitialize) { WriteFooterAndUninitialize(fileName); } } /// <summary> /// Flushes all pending file operations. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <remarks> /// The timeout parameter is ignored, because file APIs don't provide /// the needed functionality. /// </remarks> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { for (var i = 0; i < recentAppenders.Length; ++i) { if (recentAppenders[i] == null) { break; } recentAppenders[i].Flush(); } asyncContinuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } } /// <summary> /// Initializes file logging by creating data structures that /// enable efficient multi-file logging. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); if (!KeepFileOpen) { appenderFactory = RetryingMultiProcessFileAppender.TheFactory; } else { if (ArchiveAboveSize != -1 || ArchiveEvery != FileArchivePeriod.None) { if (NetworkWrites) { appenderFactory = RetryingMultiProcessFileAppender.TheFactory; } else if (ConcurrentWrites) { #if NET_CF || SILVERLIGHT this.appenderFactory = RetryingMultiProcessFileAppender.TheFactory; #elif MONO // // mono on Windows uses mutexes, on Unix - special appender // if (PlatformDetector.IsUnix) { this.appenderFactory = UnixMultiProcessFileAppender.TheFactory; } else { this.appenderFactory = MutexMultiProcessFileAppender.TheFactory; } #else appenderFactory = MutexMultiProcessFileAppender.TheFactory; #endif } else { appenderFactory = CountingSingleProcessFileAppender.TheFactory; } } else { if (NetworkWrites) { appenderFactory = RetryingMultiProcessFileAppender.TheFactory; } else if (ConcurrentWrites) { #if NET_CF || SILVERLIGHT this.appenderFactory = RetryingMultiProcessFileAppender.TheFactory; #elif MONO // // mono on Windows uses mutexes, on Unix - special appender // if (PlatformDetector.IsUnix) { this.appenderFactory = UnixMultiProcessFileAppender.TheFactory; } else { this.appenderFactory = MutexMultiProcessFileAppender.TheFactory; } #else appenderFactory = MutexMultiProcessFileAppender.TheFactory; #endif } else { appenderFactory = SingleProcessFileAppender.TheFactory; } } } recentAppenders = new BaseFileAppender[OpenFileCacheSize]; if ((OpenFileCacheSize > 0 || EnableFileDelete) && OpenFileCacheTimeout > 0) { autoClosingTimer = new Timer( AutoClosingTimerCallback, null, OpenFileCacheTimeout*1000, OpenFileCacheTimeout*1000); } // Console.Error.WriteLine("Name: {0} Factory: {1}", this.Name, this.appenderFactory.GetType().FullName); } /// <summary> /// Closes the file(s) opened for writing. /// </summary> protected override void CloseTarget() { base.CloseTarget(); foreach (var fileName in new List<string>(initializedFiles.Keys)) { WriteFooterAndUninitialize(fileName); } if (autoClosingTimer != null) { autoClosingTimer.Change(Timeout.Infinite, Timeout.Infinite); autoClosingTimer.Dispose(); autoClosingTimer = null; } for (var i = 0; i < recentAppenders.Length; ++i) { if (recentAppenders[i] == null) { break; } recentAppenders[i].Close(); recentAppenders[i] = null; } } /// <summary> /// Writes the specified logging event to a file specified in the FileName /// parameter. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { var fileName = FileName.Render(logEvent); var bytes = GetBytesToWrite(logEvent); if (ShouldAutoArchive(fileName, logEvent, bytes.Length)) { InvalidateCacheItem(fileName); DoAutoArchive(fileName, logEvent); } WriteToFile(fileName, bytes, false); } /// <summary> /// Writes the specified array of logging events to a file specified in the FileName /// parameter. /// </summary> /// <param name="logEvents"> /// An array of <see cref="LogEventInfo " /> objects. /// </param> /// <remarks> /// This function makes use of the fact that the events are batched by sorting /// the requests by filename. This optimizes the number of open/close calls /// and can help improve performance. /// </remarks> protected override void Write(AsyncLogEventInfo[] logEvents) { var buckets = logEvents.BucketSort(c => FileName.Render(c.LogEvent)); using (var ms = new MemoryStream()) { var pendingContinuations = new List<AsyncContinuation>(); foreach (var bucket in buckets) { var fileName = bucket.Key; ms.SetLength(0); ms.Position = 0; LogEventInfo firstLogEvent = null; foreach (var ev in bucket.Value) { if (firstLogEvent == null) { firstLogEvent = ev.LogEvent; } var bytes = GetBytesToWrite(ev.LogEvent); ms.Write(bytes, 0, bytes.Length); pendingContinuations.Add(ev.Continuation); } FlushCurrentFileWrites(fileName, firstLogEvent, ms, pendingContinuations); } } } /// <summary> /// Formats the log event for write. /// </summary> /// <param name="logEvent">The log event to be formatted.</param> /// <returns>A string representation of the log event.</returns> protected virtual string GetFormattedMessage(LogEventInfo logEvent) { return Layout.Render(logEvent); } /// <summary> /// Gets the bytes to be written to the file. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns>Array of bytes that are ready to be written.</returns> protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent) { var renderedText = GetFormattedMessage(logEvent) + NewLineChars; return TransformBytes(Encoding.GetBytes(renderedText)); } /// <summary> /// Modifies the specified byte array before it gets sent to a file. /// </summary> /// <param name="value">The byte array.</param> /// <returns>The modified byte array. The function can do the modification in-place.</returns> protected virtual byte[] TransformBytes(byte[] value) { return value; } private static string ReplaceNumber(string pattern, int value) { var firstPart = pattern.IndexOf("{#", StringComparison.Ordinal); var lastPart = pattern.IndexOf("#}", StringComparison.Ordinal) + 2; var numDigits = lastPart - firstPart - 2; return pattern.Substring(0, firstPart) + Convert.ToString(value, 10).PadLeft(numDigits, '0') + pattern.Substring(lastPart); } private void FlushCurrentFileWrites(string currentFileName, LogEventInfo firstLogEvent, MemoryStream ms, List<AsyncContinuation> pendingContinuations) { Exception lastException = null; try { if (currentFileName != null) { if (ShouldAutoArchive(currentFileName, firstLogEvent, (int) ms.Length)) { WriteFooterAndUninitialize(currentFileName); InvalidateCacheItem(currentFileName); DoAutoArchive(currentFileName, firstLogEvent); } WriteToFile(currentFileName, ms.ToArray(), false); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } lastException = exception; } foreach (var cont in pendingContinuations) { cont(lastException); } pendingContinuations.Clear(); } private void RecursiveRollingRename(string fileName, string pattern, int archiveNumber) { if (archiveNumber >= MaxArchiveFiles) { File.Delete(fileName); return; } if (!File.Exists(fileName)) { return; } var newFileName = ReplaceNumber(pattern, archiveNumber); if (File.Exists(fileName)) { RecursiveRollingRename(newFileName, pattern, archiveNumber + 1); } InternalLogger.Trace("Renaming {0} to {1}", fileName, newFileName); try { File.Move(fileName, newFileName); } catch (IOException) { var dir = Path.GetDirectoryName(newFileName); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.Move(fileName, newFileName); } } private void SequentialArchive(string fileName, string pattern) { var baseNamePattern = Path.GetFileName(pattern); var firstPart = baseNamePattern.IndexOf("{#", StringComparison.Ordinal); var lastPart = baseNamePattern.IndexOf("#}", StringComparison.Ordinal) + 2; var trailerLength = baseNamePattern.Length - lastPart; var fileNameMask = baseNamePattern.Substring(0, firstPart) + "*" + baseNamePattern.Substring(lastPart); var dirName = Path.GetDirectoryName(Path.GetFullPath(pattern)); var nextNumber = -1; var minNumber = -1; var number2name = new Dictionary<int, string>(); try { #if SILVERLIGHT foreach (string s in Directory.EnumerateFiles(dirName, fileNameMask)) #else foreach (var s in Directory.GetFiles(dirName, fileNameMask)) #endif { var baseName = Path.GetFileName(s); var number = baseName.Substring(firstPart, baseName.Length - trailerLength - firstPart); int num; try { num = Convert.ToInt32(number, CultureInfo.InvariantCulture); } catch (FormatException) { continue; } nextNumber = Math.Max(nextNumber, num); if (minNumber != -1) { minNumber = Math.Min(minNumber, num); } else { minNumber = num; } number2name[num] = s; } nextNumber++; } catch (DirectoryNotFoundException) { Directory.CreateDirectory(dirName); nextNumber = 0; } if (minNumber != -1) { var minNumberToKeep = nextNumber - MaxArchiveFiles + 1; for (var i = minNumber; i < minNumberToKeep; ++i) { string s; if (number2name.TryGetValue(i, out s)) { File.Delete(s); } } } var newFileName = ReplaceNumber(pattern, nextNumber); File.Move(fileName, newFileName); } private void DoAutoArchive(string fileName, LogEventInfo ev) { var fi = new FileInfo(fileName); if (!fi.Exists) { return; } // Console.WriteLine("DoAutoArchive({0})", fileName); string fileNamePattern; if (ArchiveFileName == null) { var ext = Path.GetExtension(fileName); fileNamePattern = Path.ChangeExtension(fi.FullName, ".{#}" + ext); } else { fileNamePattern = ArchiveFileName.Render(ev); } switch (ArchiveNumbering) { case ArchiveNumberingMode.Rolling: RecursiveRollingRename(fi.FullName, fileNamePattern, 0); break; case ArchiveNumberingMode.Sequence: SequentialArchive(fi.FullName, fileNamePattern); break; } } private bool ShouldAutoArchive(string fileName, LogEventInfo ev, int upcomingWriteSize) { if (ArchiveAboveSize == -1 && ArchiveEvery == FileArchivePeriod.None) { return false; } DateTime lastWriteTime; long fileLength; if (!GetFileInfo(fileName, out lastWriteTime, out fileLength)) { return false; } if (ArchiveAboveSize != -1) { if (fileLength + upcomingWriteSize > ArchiveAboveSize) { return true; } } if (ArchiveEvery != FileArchivePeriod.None) { string formatString; switch (ArchiveEvery) { case FileArchivePeriod.Year: formatString = "yyyy"; break; case FileArchivePeriod.Month: formatString = "yyyyMM"; break; default: case FileArchivePeriod.Day: formatString = "yyyyMMdd"; break; case FileArchivePeriod.Hour: formatString = "yyyyMMddHH"; break; case FileArchivePeriod.Minute: formatString = "yyyyMMddHHmm"; break; } var ts = lastWriteTime.ToString(formatString, CultureInfo.InvariantCulture); var ts2 = ev.TimeStamp.ToString(formatString, CultureInfo.InvariantCulture); if (ts != ts2) { return true; } } return false; } private void AutoClosingTimerCallback(object state) { lock (SyncRoot) { if (!IsInitialized) { return; } try { var timeToKill = DateTime.Now.AddSeconds(-OpenFileCacheTimeout); for (var i = 0; i < recentAppenders.Length; ++i) { if (recentAppenders[i] == null) { break; } if (recentAppenders[i].OpenTime < timeToKill) { for (var j = i; j < recentAppenders.Length; ++j) { if (recentAppenders[j] == null) { break; } recentAppenders[j].Close(); recentAppenders[j] = null; } break; } } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Warn("Exception in AutoClosingTimerCallback: {0}", exception); } } } private void WriteToFile(string fileName, byte[] bytes, bool justData) { if (ReplaceFileContentsOnEachWrite) { using (var fs = File.Create(fileName)) { var headerBytes = GetHeaderBytes(); var footerBytes = GetFooterBytes(); if (headerBytes != null) { fs.Write(headerBytes, 0, headerBytes.Length); } fs.Write(bytes, 0, bytes.Length); if (footerBytes != null) { fs.Write(footerBytes, 0, footerBytes.Length); } } return; } var writeHeader = false; if (!justData) { if (!initializedFiles.ContainsKey(fileName)) { if (DeleteOldFileOnStartup) { try { File.Delete(fileName); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Warn("Unable to delete old log file '{0}': {1}", fileName, exception); } } initializedFiles[fileName] = DateTime.Now; initializedFilesCounter++; writeHeader = true; if (initializedFilesCounter >= 100) { initializedFilesCounter = 0; CleanupInitializedFiles(); } } initializedFiles[fileName] = DateTime.Now; } // // BaseFileAppender.Write is the most expensive operation here // so the in-memory data structure doesn't have to be // very sophisticated. It's a table-based LRU, where we move // the used element to become the first one. // The number of items is usually very limited so the // performance should be equivalent to the one of the hashtable. // BaseFileAppender appenderToWrite = null; var freeSpot = recentAppenders.Length - 1; for (var i = 0; i < recentAppenders.Length; ++i) { if (recentAppenders[i] == null) { freeSpot = i; break; } if (recentAppenders[i].FileName == fileName) { // found it, move it to the first place on the list // (MRU) // file open has a chance of failure // if it fails in the constructor, we won't modify any data structures var app = recentAppenders[i]; for (var j = i; j > 0; --j) { recentAppenders[j] = recentAppenders[j - 1]; } recentAppenders[0] = app; appenderToWrite = app; break; } } if (appenderToWrite == null) { var newAppender = appenderFactory.Open(fileName, this); if (recentAppenders[freeSpot] != null) { recentAppenders[freeSpot].Close(); recentAppenders[freeSpot] = null; } for (var j = freeSpot; j > 0; --j) { recentAppenders[j] = recentAppenders[j - 1]; } recentAppenders[0] = newAppender; appenderToWrite = newAppender; } if (writeHeader && !justData) { var headerBytes = GetHeaderBytes(); if (headerBytes != null) { appenderToWrite.Write(headerBytes); } } appenderToWrite.Write(bytes); } private byte[] GetHeaderBytes() { if (Header == null) { return null; } var renderedText = Header.Render(LogEventInfo.CreateNullEvent()) + NewLineChars; return TransformBytes(Encoding.GetBytes(renderedText)); } private byte[] GetFooterBytes() { if (Footer == null) { return null; } var renderedText = Footer.Render(LogEventInfo.CreateNullEvent()) + NewLineChars; return TransformBytes(Encoding.GetBytes(renderedText)); } private void WriteFooterAndUninitialize(string fileName) { var footerBytes = GetFooterBytes(); if (footerBytes != null) { if (File.Exists(fileName)) { WriteToFile(fileName, footerBytes, true); } } initializedFiles.Remove(fileName); } private bool GetFileInfo(string fileName, out DateTime lastWriteTime, out long fileLength) { for (var i = 0; i < recentAppenders.Length; ++i) { if (recentAppenders[i] == null) { break; } if (recentAppenders[i].FileName == fileName) { recentAppenders[i].GetFileInfo(out lastWriteTime, out fileLength); return true; } } var fi = new FileInfo(fileName); if (fi.Exists) { fileLength = fi.Length; lastWriteTime = fi.LastWriteTime; return true; } else { fileLength = -1; lastWriteTime = DateTime.MinValue; return false; } } private void InvalidateCacheItem(string fileName) { for (var i = 0; i < recentAppenders.Length; ++i) { if (recentAppenders[i] == null) { break; } if (recentAppenders[i].FileName == fileName) { recentAppenders[i].Close(); for (var j = i; j < recentAppenders.Length - 1; ++j) { recentAppenders[j] = recentAppenders[j + 1]; } recentAppenders[recentAppenders.Length - 1] = null; break; } } } } } #endif